blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
62cbd1bb70a63056c31bf7eb173481b151060d0b | zatserkl/learn | /python/plot.py | 849 | 4.1875 | 4 | """See Python and Matplotlib Essentials for Scientists and Engineers.pdf
"""
import matplotlib.pyplot as plt
x = range(5)
y = [xi**2 for xi in x]
plt.figure()
# fig = plt.figure() # create a figure pointed by fig
# fig.number # get number of the figure pointed by fig
# plt.gcf().number # get number of the curent figure
# plt.figure(1) # make figure No. 1 current
# plt.clf() # clear current figure
plt.plot(x, y, marker='o', color='black', label='square', linestyle='None')
plt.title('y vs x')
plt.xlabel('x')
plt.ylabel('y')
# plt.legend(loc=1, numpoints=1) # defaults: loc=1, numpoints=2 in the legend
plt.legend(loc=2, numpoints=1) # loc=2 is the top left corner
plt.grid(True) # turn on gridlines
# plt.gcf().set_size_inches(6.5, 5) # gcf: get current figure
plt.show()
| true |
821e0a1793c5fb08e85102dfe2f73d3744f24589 | zatserkl/learn | /python/generator_comprehension.py | 481 | 4.3125 | 4 | # modified example from https://wiki.python.org/moin/Generators
nmax = 5
# Generator expression: like list comprehension
doubles = (2*n for n in range(nmax)) # parenthesis () instead of brackets []
# print("list of doubles:", list(doubles))
while True:
try:
number = next(doubles) # raises StopIteration if no default value
except StopIteration:
print("caught StopIteration") # StopIteration e returns empty string
break
print(number)
| true |
2e449b4aeae7d9409d28e6ff4ae686b58ab315b5 | zatserkl/learn | /python/numpy_matrix.py | 1,614 | 4.375 | 4 | ###################################################################
# This is the final solution: use array for the matrix operations #
###################################################################
"""
See https://docs.scipy.org/doc/numpy-dev/user/numpy-for-matlab-users.html
NumPy matrix operations: use arrays and dot(A, B) for multiplication.
NB: for ndarray all operations (*, /, +, - etc.) are elementwise
The vector is considered as a row or a column depending on context.
dot(A,v) treats v as a column vector, while dot(v,A) treats v as a row vector.
NB: attribute Transpose does not change the ndarray vector.
To use convenient interface like mat("1 -2 1;0 2 -8;-4 5 9")
use casting A = np.array(np.mat("1 -2 1;0 2 -8;-4 5 9"))
Solve equation A*x = b
where all variables are represented by ndarray.
"""
import numpy as np
def solve_matrix_array():
A = np.array(np.mat("1 -2 1;0 2 -8;-4 5 9")) # convenient mat interface
print("A:\n", A)
print("type(A) =", type(A))
b = np.array([0, 8, -9])
print("b is a numpy array:\n", b)
print("type(b) =", type(b))
x = np.linalg.solve(A, b) # b will be treated as a column vector
print("Solution of the equation A*x = b:\n", x, "\ntype(x) =", type(x))
# check the solution
b1 = np.dot(A, x) # x will be treated as a column vector
print('b1 = np.dot(A, x):\n', b1)
print("type(b1) =", type(b1))
print("\nSolve equation A*x = b")
print("where we use dot-product np.dot(A, x)")
print("\ndefine b as a ndarray: it will be treated row- or column-wise "
"depending on context")
solve_matrix_array()
| true |
bbfa8595002901875ce4e6dd72babcf52921757f | rodrigor/IntroProgramacao-Code | /2014.2-Prova1/prova1-solucao2.py | 2,495 | 4.25 | 4 | # Resolução da prova1: Solução 01
# Prof. Rodrigo Rebouças
# [Uma lista, sem função, sem validação]
# Nesta solução usamos uma lista para armazenar
# o nome e a média do aluno. O nome do aluno
# fica armazenado na primeira posição de cada elemento
# e a média do aluno fica armazenado na segunda posição
NOME = 0 # Variável que representa a posiçao do nome em cada elemento da lista
MEDIA = 1 # Variável que representa a posição da média em cada elemento da lista
opcao = -1
alunos = []
while opcao != 0:
print("*** MENU ***")
print("[1] Cadastrar aluno")
print("[2] Listar alunos")
print("[3] Maior média?")
print("[4] Menor média?")
print("[5] Média dos alunos?")
print("[6] Buscar alunos")
print("[0] Sair")
print("*************")
opcao = int(input("Digite sua opção:"))
if opcao == 1:
print("")
print("** 1-Cadastrar Aluno")
nome = input("Nome:")
media = float(input("Média:"))
alunos.append([nome,media])
elif opcao == 2:
print("")
print("** 2-Listar Alunos")
for aluno in alunos:
print(alunos[NOME], ":", alunos[MEDIA])
elif opcao == 3:
print('')
print('** 3-Maior Média')
indiceMaior = 0
for i in range(len(alunos)):
if alunos[i][MEDIA] > alunos[indiceMaior][MEDIA]:
indiceMaior = i
print(alunos[indiceMaior][NOME], ":", alunos[indiceMaior][MEDIA])
elif opcao == 4:
print("")
print("** 4-Menor Média")
indiceMenor = 0
for i in range(len(alunos)):
if alunos[i][MEDIA] < alunos[indiceMenor][MEDIA]:
indiceMenor = i
print(alunos[indiceMenor][NOME], ":", alunos[indiceMenor][MEDIA])
elif opcao == 5:
print("")
print("** 5-Média dos alunos")
soma = 0
for aluno in alunos:
soma += aluno[MEDIA]
media = soma / len(alunos)
print("A média dos alunos é:", media)
elif opcao == 6:
print("")
print("** 6-Buscar alunos")
nome = input("Nome do aluno:")
indiceAluno = -1
for i in range(len(alunos)):
if alunos[i][NOME] == nome:
indiceAluno = i
break
if indiceAluno != -1:
print("Aluno encontrado:", alunos[indiceAluno][NOME], ", média:", alunos[indiceAluno][MEDIA])
else:
print("Aluno não encontrado:", nome)
| false |
b02955a662cd3093d93d4783334982e507492132 | liyangwill/python_repository | /plot.py | 1,395 | 4.15625 | 4 | # Print the last item from year and pop
print(year[-1])
print(pop[-1])
# Import matplotlib.pyplot as plt
import matplotlib.pyplot as plt
# Make a line plot: year on the x-axis, pop on the y-axis
plt.plot(year,pop)
plt.show()
# Print the last item of gdp_cap and life_exp
print(gdp_cap[-1])
print(life_exp[-1])
# Make a line plot, gdp_cap on the x-axis, life_exp on the y-axis
plt.plot(gdp_cap,life_exp)
# Display the plot
plt.show()
# Change the line plot below to a scatter plot
plt.scatter(gdp_cap, life_exp)
# Put the x-axis on a logarithmic scale
plt.xscale('log')
# Show plot
plt.show()
# Import package
import matplotlib.pyplot as plt
# Build Scatter plot
plt.scatter(pop, life_exp)
# Show plot
plt.show()
# Create histogram of life_exp data
plt.hist(life_exp)
# Display histogram
plt.show()
# Build histogram with 5 bins
plt.hist(life_exp, bins=5)
# Show and clean up plot
plt.show()
plt.clf()
# Build histogram with 20 bins
plt.hist(life_exp, bins=20)
# Show and clean up again
plt.show()
plt.clf()
# Specify c and alpha inside plt.scatter()
plt.scatter(x = gdp_cap, y = life_exp, s = np.array(pop) * 2, c=col, alpha=0.8)
# Previous customizations
plt.xscale('log')
plt.xlabel('GDP per Capita [in USD]')
plt.ylabel('Life Expectancy [in years]')
plt.title('World Development in 2007')
plt.xticks([1000,10000,100000], ['1k','10k','100k'])
# Show the plot
plt.show()
| true |
f236b8b9866ac9eae15b53802cc2c01854c248f9 | MainakRepositor/Advanced-Programming-Practice | /Week 3/Q.1.py | 543 | 4.4375 | 4 | '''1.Develop an Python code to display the following output using class and object (only one
class and two objects)'''
class Birdie:
species = "bird"
def __init__(self, name, age):
self.name = name
self.age = age
blu = Birdie("Blu", 10)
woo = Birdie("Woo", 15)
print("Blu is a {}".format(blu.__class__.species))
print("Woo is also a {}".format(woo.__class__.species))
# access the instance attributes
print("{} is {} years old".format( blu.name, blu.age))
print("{} is {} years old".format( woo.name, woo.age))
| true |
63458826fb3151c4a1f02905ee5b73d4c51641b0 | juanignaciolagos/python | /07-Ejercicios/ejercicio4.py | 467 | 4.4375 | 4 | """
Pedir dos numeros al usuario y hacer todas las operaciones basicas de una calculadora
mostrarlo por pantalla
"""
numero1 = int(input("Introduce el numero 1: "))
numero2 = int(input("Introduce el numero 2: "))
print(f"La suma de los dos numeros es: {numero1+numero2}")
print(f"La resta de los dos numeros es: {numero1-numero2}")
print(f"La multiplicacion de los dos numeros es: {numero1*numero2}")
print(f"La division de los dos numeros es: {numero1/numero2}")
| false |
9958f3ae8ed45d535d2fab9444a43426100ede7f | juanignaciolagos/python | /08-Funciones/predefinidas.py | 892 | 4.1875 | 4 | nombre = "Juan Lagos"
#funciones Generales
print(nombre)
print(type(nombre))
#detectar el tipado
comprobar = isinstance(nombre,int)
if comprobar:
print("Esta variable es un string")
else:
print("no es un string")
if not isinstance(nombre,float):
print("la variable no es un numero decimal")
#limpiar espacios
frase = " mi contenido "
print(frase)
print(frase.strip())
#eliminar variables
year = 2020
print(year)
del year
#print(year)
#comprobar variable vacia
texto = " FF "
#largo de variable
print(len(texto))
#comprobar variable vacia
if len(texto) <=0:
print("esta variable esta vacia")
else:
print("variable activa y tiene ",len(texto)," espacios")
print(isinstance(nombre,float))
#encontrar caracteres
frase = "la vida es bella"
print(frase.find("vida"))
# Mayusculas y minusculas
print(nombre)
print(nombre.upper())
print(nombre.lower())
| false |
379b9516400816ed7641602198bddc6cd690f555 | juanignaciolagos/python | /07-Ejercicios/ejercicio7.py | 391 | 4.125 | 4 | """
entre dos numeros que el usuario ingrese mostrar solo los numeros impares
"""
numero1 = int(input("Introduce el numero 1: "))
numero2 = int(input("Introduce el numero 2: "))
if numero1 <= numero2:
rango = range(numero1,numero2)
for contador in rango:
print( 2*contador )
else:
rango = range(numero2,numero1)
for contador in rango:
print( 2*contador ) | false |
12b16dbd277eb214c3ccc2dc47d64dccfceb0d36 | hari-bhandari/pythonAlgoExpert | /QuickAndBubbleSort.py | 684 | 4.15625 | 4 | def quickSort(array):
length=len(array)
if length<=1:
return array
else:
pivot=array.pop()
itemsGreater=[]
itemsLower=[]
for item in array:
if(item>pivot):
itemsGreater.append(item)
else:
itemsLower.append(item)
return quickSort(itemsLower)+[pivot]+quickSort(itemsGreater)
print(quickSort([1,5,2,3,4,12,32,11,2122,1,23,23]))
def bubbleSort(array):
for i in range(len(array)-1):
for j in range(0,len(array)-1-i):
if array[j] > array[j + 1]:
array[j], array[j + 1] = array[j + 1], array[j]
return array
print(bubbleSort([1,5,2,3,4,12,32,11,2122,1,23,23]))
| true |
357fbd822fa1d9e68afd1b880fc4c2f76988b384 | jjen6894/PythonIntroduction | /Challenge/IfChallenge.py | 593 | 4.21875 | 4 | # Write a small program to ask for a name and an age.
# When both values have been entered, check if the person
# is the right age to gon on an 18-30 holiday must be over 18
# under 31
# if they are welcome them to the holiday otherwise print a polite message
# refusing them entry
name = input("What's your name? ")
age = int(input("Also, what's your age {0}? ".format(name)))
if 18 <= age < 31:
print("Welcome {0}! You are entitled to go on this amazing lad or ladette holiday".format(name))
else:
print("Sorry {0}, you aren't eligible to part-take in this holiday!".format(name))
| true |
49a053c483508ebe7a6bed95bafbe294b56239c1 | gabmwendwa/PythonLearning | /3. Conditions/2-while.py | 396 | 4.34375 | 4 | # With the while loop we can execute a set of statements as long as a condition is true.
i = 1
while i <= 10:
print(i)
i += 1
print("---------")
# Break while loop
i = 1
while i <= 10:
print(i)
if i == 5: break
i += 1
print("---------")
# With the continue statement we can stop the current iteration, and continue with the next:
i = 0
while i < 10:
i += 1
if i == 5: continue
print(i)
| true |
b5ab9138384b9079b73d6a64e922a307d500fe42 | gabmwendwa/PythonLearning | /4. Functions/1-functions.py | 2,308 | 4.71875 | 5 | # In Python a function is defined using the def keyword:
def myfunction():
print("Hello from function")
# Call function
myfunction()
print("-------")
# Information can be passed to functions as parameter.
def namefunc(fname):
print(fname + " Mutisya")
namefunc("Mutua")
namefunc("Kalui")
namefunc("Mwendwa")
print("-------")
# The following example shows how to use a default parameter value.
# If we call the function without parameter, it uses the default value:
def mycountry(country = "Kenya"):
print("I am from " + country)
mycountry("Tanzania")
mycountry("Rwanda")
mycountry()
mycountry("Uganda")
print("-------")
#You can send any data types of parameter to a function (string, number, list, dictionary etc.), and it will be treated as the same data type inside the function.
#E.g. if you send a List as a parameter, it will still be a List when it reaches the function:
def myfunc(food):
for x in food:
print(x)
fruits = ["apple", "mango", "cherry"]
myfunc(fruits)
print("-------")
# To let a function return a value, use the return statement:
def myfunc(x):
return 5 * x
print(myfunc(3))
print(myfunc(4))
print(myfunc(5))
print("-------")
# Python also accepts function recursion, which means a defined function can call itself.
# Recursion is a common mathematical and programming concept. It means that a function calls itself. This has the benefit of meaning that you can loop through data to reach a result.
# The developer should be very careful with recursion as it can be quite easy to slip into writing a function which never terminates, or one that uses excess amounts of memory or processor power. However, when written correctly recursion can be a very efficient and mathematically-elegant approach to programming.
#In this example, tri_recursion() is a function that we have defined to call itself ("recurse"). We use the k variable as the data, which decrements (-1) every time we recurse. The recursion ends when the condition is not greater than 0 (i.e. when it is 0).
#To a new developer it can take some time to work out how exactly this works, best way to find out is by testing and modifying it.
def tri_recursion(k):
if(k>0):
result = k+tri_recursion(k-1)
print(result)
else:
result = 0
return result
print("\n\nRecursion Example Results")
tri_recursion(6) | true |
71b8b67c39bb8c55568ba0c8dcdbb0e3565c1972 | gabmwendwa/PythonLearning | /2. Collections/4-dictionary.py | 2,577 | 4.34375 | 4 | # Dictionary is a collection which is unordered, changeable and indexed. No duplicate members.
# A dictionary is a collection which is unordered, changeable and indexed. In Python dictionaries are written with curly brackets, and they have keys and values.
mdic = {
"brand" : "Ford",
"model" : "Mustang",
"year" : 1969
}
print(mdic)
# Get the value of the "model" key:
print(mdic["model"])
# There is also a method called get() that will give you the same result:
print(mdic.get("model"))
# You can change the value of a specific item by referring to its key name:
mdic["year"] = 2019
print(mdic)
# Print all key names in the dictionary, one by one:
for x in mdic:
print(x)
# Print all values in the dictionary, one by one:
for x in mdic:
print(mdic[x])
# You can also use the values() function to return values of a dictionary:
for x in mdic.values():
print(x)
# Loop through both keys and values, by using the items() function:
for x, y in mdic.items():
print(x, y)
# To determine if a specified key is present in a dictionary use the in keyword:
if "model" in mdic:
print("Yes, \"model\" exists")
else:
print("None exists")
# To determine how many items (key-value pairs) a dictionary has, use the len() method.
print(len(mdic))
# Adding an item to the dictionary is done by using a new index key and assigning a value to it:
mdic["color"] = "red"
print(mdic)
# There are several methods to remove items from a dictionary:
# The pop() method removes the item with the specified key name:
mdic.pop("model")
print(mdic)
# The popitem() method removes the last inserted item (in versions before 3.7, a random item is removed instead):
mdic.popitem()
print(mdic)
# The del keyword removes the item with the specified key name:
mdic = {
"brand" : "Ford",
"model" : "Mustang",
"year" : 1969
}
del mdic["model"]
print(mdic)
# The del keyword can also delete the dictionary completely:
del mdic
#print(mdic)
# The clear() keyword empties the dictionary:
mdic = {
"brand" : "Ford",
"model" : "Mustang",
"year" : 1969
}
mdic.clear()
print(mdic)
# Make a copy of a dictionary with the copy() method:
mdic = {
"brand" : "Ford",
"model" : "Mustang",
"year" : 1969
}
ndic = mdic.copy()
print(ndic)
# Another way to make a copy is to use the built-in method dict().
odic = dict(mdic)
print(odic)
# It is also possible to use the dict() constructor to make a new dictionary:
vdic = dict(Brand="Ford", Model="Mustang", Year=1969)
# note that keywords are not string literals
# note the use of equals rather than colon for the assignment
print(vdic)
| true |
e184909d1fc15daaeb34b22bd9f570d55038acfa | CPlusPlusNewb/python | /edhesive/notneededgarbage/2.2 Lesson Practice/question7.py | 271 | 4.28125 | 4 | if (3 * (6 + 2) / 2) == int("19"):
print("Its the 1st")
elif ((3 * 6) + 2 / 2) == int("19"):
print("Its the 2nd")
elif ((3 * 6 + 2) / 2) == int("19"):
print("Its the 3rd")
elif (3 * (6 + 2 / 2)) == int("19"):
print("Its the 4th")
else:
print("Something went wrong")
| false |
252d6fb9fb6b77cfd70c38325fedc0b50e1d530d | alantanlc/what-is-torch-nn-really | /functions-as-objects-in-python.py | 1,897 | 4.71875 | 5 | # Functions can be passed as arguments
# We define an 'apply' function which will take as input a list, _L_ and a function, _f_ and apply the function to each element of the list.
def apply(L, f):
"""
Applies function given by f to each element in L
Parameters
----------
L : list containing the operands
f : the function
Returns
--------
result: resulting list
"""
result = []
for i in L:
result.append(f(i))
return result
L = [1, -2, -5, 6.2]
a = apply(L, abs)
print(a) # [1, 2, 5, 6.2]
# abs is applied on elements passed in L
a = apply(L, int)
print(a) # [1, -2, -5, 6]
# We can also pass a self-defined function. For example:
def sqr(num):
return num ** 2
a = apply(L, sqr)
print(a) # [1, 4, 25, 38.440000000000005]
# The ability to perform the same operation on a list of elements is also provided by a higher-order python function called __map__.
# In its simplest form, it takes in a 'unary' function and a collection of suitable arguments and returns an 'iterable' which we must walk down.
for i in map(abs, L):
print(i)
# Functions as elements of a list
# Functions can be stored as elements of a list or any other data structure in Python. For example, if we wish to perform multiple operations to a particular number, we define `apply_func(L, x)` that takes a list of functions, L and an operand, x and applies each function in L on x.
from math import exp
def apply_func(L,x):
result = []
for f in L:
result.append(f(x))
return result
function_list = [abs, exp, int]
print(apply_func(function_list, -2.3))
print(apply_func(function_list, -4))
# Side Note: In both the above examples, we could have used list comprehensions, which provide an elegant way of creating lists based on another list or iterator.
output = [f(-2.3) for f in function_list]
print(f'output: {output}') | true |
78c1296a009f6ff19884a46f48e67f6795e312f4 | mariarozanska/python_exercises | /zad9.py | 768 | 4.34375 | 4 | '''Generate a random number between 1 and 9 (including 1 and 9).
Ask the user to guess the number,
then tell them whether they guessed too low, too high, or exactly right.
Extras:
Keep the game going until the user types “exit”
Keep track of how many guesses the user has taken, and when the game ends, print this out.'''
import random
number = random.randint(1, 9)
tries = 1
while True:
guess = int(input('Guess the number (1-9): '))
if number == guess:
print('Yes, it\'s {}. It took you {} tries.'.format(number, tries))
break
if number > guess:
print('Too low...')
else:
print('Too high...')
game = input('Do you want to try again? (y/exit) ')
if game == 'exit':
break
tries += 1
| true |
4b610d707b407ef845cc19fde9da3eefc6115065 | BlakeBeyond/python-onsite | /week_02/08_dictionaries/09_03_count_cases.py | 1,065 | 4.5 | 4 | '''
Write a script that takes a sentence from the user and returns:
- the number of lower case letters
- the number of uppercase letters
- the number of punctuations characters (count)
- the total number of characters (len)
Use a dictionary to store the count of each of the above.
Note: ignore all spaces.
Example input:
I love to work with dictionaries!
Example output:
Upper case: 1
Lower case: 26
Punctuation: 1
'''
message = input("Type word: ")
message.replace(" ", "")
up = "Upper Case: " + str(sum(1 for c in message if c.isupper()))
low = "Lower Case: " + str(sum(1 for c in message if c.islower()))
punctuation = [".", "?", "!", ","]
punct = "Punctuation: "+ str(sum(1 for c in message if c in punctuation))
char = "Characters: " + str(len(message))
print(up)
print(low)
print(punct)
print(char)
dict_count = {"Upper Case": sum(1 for c in message if c.isupper()), "Lower Case": sum(1 for c in message if c.islower()), "Punctuation": sum(1 for c in message if c in punctuation), "Characters": len(message)}
print(dict_count)
| true |
68a19b536b3ba06cd7ae5107106d15dd175682e5 | BlakeBeyond/python-onsite | /week_02/08_dictionaries/09_02_combine_dicts.py | 334 | 4.34375 | 4 | '''
Create a new dictionary using the three dictionaries below.
Then print out each key-value pair.
'''
dict_1 = {1: 1, 2: 4}
dict_2 = {3: 9, 4: 16}
dict_3 = {5: 25, 6: 36, 7: 49}
new_dict = {}
def add_dict(d):
for k, v in d.items():
new_dict[k] = v
add_dict(dict_1)
add_dict(dict_2)
add_dict(dict_3)
print(new_dict) | false |
d7af1592985a4677bc8929c35905f045b25ca842 | BlakeBeyond/python-onsite | /week_02/06_tuples/02_word_frequencies.py | 628 | 4.40625 | 4 | '''
Write a function called most_frequent that takes a string and prints
the letters in decreasing order of frequency.
For example, the follow string should produce the following result.
string_ = 'hello'
Output:
l, h, e, o
For letters that are the same frequency, the order does not matter.
'''
my_dict = {}
sorted_list = []
def most_frequent(fstring_):
for ch in fstring_:
if ch not in my_dict:
my_dict[ch] = fstring_.count(ch)
for key, value in sorted(my_dict.items(), key=lambda v: v):
sorted_list.append(key)
print(sorted_list)
function_output = most_frequent("kanapka")
| true |
e8f1c5cd3e440886e0fa8f594d1092fb58fb509a | cp105/dynamic_programming_101 | /dp101/knapsack01.py | 1,896 | 4.4375 | 4 | """
The knapsack problem is a problem in combinatorial optimization: Given a set of items,
each with a weight and a value, determine the number of each item to include in a collection so that
the total weight is less than or equal to a given limit and the total value is as large as possible.
It derives its name from the problem faced by someone who is constrained by a fixed-size knapsack
and must fill it with the most valuable items. The problem often arises in resource allocation where
the decision makers have to choose from a set of non-divisible projects or tasks
under a fixed budget or time constraint, respectively.
https://en.wikipedia.org/wiki/Knapsack_problem
function "knapsack(item_names, value, weight, capacity)" takes the items' names, values, weights,
and maximum weight that the backpack can carry as arguments.
Returned tuple containing array of names of selected items, total value of selected items and total weight.
"""
def knapsack01(item_names, value, weight, capacity):
if (len(value) != len(weight)) or (len(value) != len(item_names)):
raise RuntimeError('value, weight and item_names must be of same size.')
for i in range(len(value)):
if weight[i] < 0:
raise RuntimeError('weights must be positive numbers.')
return knapsack01_(item_names, value, weight, capacity)
def knapsack01_(item_names, value, weight, capacity):
if (not item_names) or (capacity <= 0):
return [], 0, 0
names0, v0, w0 = knapsack01_(item_names[1:], value[1:], weight[1:], capacity)
if capacity >= weight[0]:
names0, v0, w0 = knapsack01_(item_names[1:], value[1:], weight[1:], capacity)
names1, v1, w1 = knapsack01_(item_names[1:], value[1:], weight[1:], capacity - weight[0])
if (v1 + value[0]) > v0:
return [item_names[0]] + names1, v1 + value[0], w1 + weight[0]
return names0, v0, w0
| true |
2f38f4bc5978ba371014073dd189675134becea2 | lucho1021/python | /practic.py | 2,238 | 4.21875 | 4 | #puntoA
"""factorial = input ('ingresa un numero ')
factorial = int (factorial)
def calculafactorial(factorial):
if factorial==0 or factorial==1:
resultado=1
elif factorial > 1:
resultado=factorial*calculafactorial(factorial-1)
return resultado
print("el factorial de",factorial ,"es: ",calculafactorial(factorial))"""
# puntoB
"""num = input('ingresa un numero ')
num = int(num)
def calcularFibonacci(num):
i = 0
n1 = 0
n2 = 1
for i in range(num):
print(num, end=' ')
num = (num-1) + (num-2)
return num
print(calcularFibonacci(num)) """
"""
num = int(input("Ingresa el limite del fibonacci "))
def calcularFibonacci(num):
n1= 0
n2 = 1
count = 1
#ingresar un numero correcto
if num <= 0:
print("Opss ingresaste un numero incorrecto, revisa e intentalo nuevamente")
else:
print("secuencia fibonacci: ")
while count < num:
print(n1)
resultadito = n1 + n2
n1 = n2
n2 = resultadito
return n1
print(calcularFibonacci(num))"""
#puntoC
"""
prestamo = int(input("Ingresa el valor del prestamo: "))
cuota = int(input("Ingresa el total de cuotas a pagar: "))
def calcularcuotavalor(prestamo, cuota):
resultadocuota = prestamo / cuota
tasamensual = resultadocuota * 0.03
resultadoT = resultadocuota + tasamensual
return resultadoT
print("El total a pagar cada cuota es de: ",calcularcuotavalor(prestamo,cuota))"""
#puntoD
"""
mostrardatos = ["hola", "asd", 13]
print(mostrardatos)"""
#puntoE
"""
diccionario = {"saludo": "hola", "pregunta": "¿?"}
print (diccionario["saludo"])"""
#puntoF
"""
dpagos = {"placa": "tis123", "marca": "Aveo", "pagos":[100,200,30,400]}
print (sum(dpagos["pagos"]))"""
#punto4
"""
datos = int(input("Ingresa la cantidad de datos a ingresar: "))
i = 1
while i <= datos:
print(i)
i += 1 """
#punto5
"""
datosimp = int(input("Ingresa la cantidad de datos a ingresar: "))
i = 1
while i <= datosimp:
print(i)
i += 1 * 2 """
datos3 = int(input("Ingresa la cantidad de datos a ingresar: "))
i = 3
while i <= datos3:
print(i)
i += 1 * 10
| false |
e441e0e4fa599fefe6f3f49f32477c68dd46e29a | jtannas/intermediate_python | /caching.py | 1,368 | 4.65625 | 5 | """
24. Function caching
Function caching allows us to cache the return values of a function
depending on the arguments. It can save time when an I/O bound function
is periodically called with the same arguments. Before Python 3.2 we
had to write a custom implementation. In Python 3.2+ there is an
lru_cache decorator which allows us to quickly cache and uncache the
return values of a function.
Let’s see how we can use it in Python 3.2+ and the versions before it.
"""
### PYTHON 3.2+ ###############################################################
from functools import lru_cache
@lru_cache(maxsize=32)
def fib(n):
if n < 2:
return n
return fib(n - 1) + fib(n - 2)
[n for n in range(16)]
#: The maxsize argument tells lru_cache about how many recent return
#: values to cache.
# It can be inspected via:
fib.cache_info()
# It can be cleared via:
fib.cache_clear()
### PYTHON 2+ #################################################################
from functools import wraps
def memoize(function):
memo = {}
@wraps(function)
def wrapper(*args):
if args in memo:
return memo[args]
else:
rv = function(*args)
memo[args] = rv
return rv
return wrapper
@memoize
def fibonacci(n):
if n < 2:
return n
return fibonacci(n - 1) + fibonacci(n - 2)
| true |
ebd261d238b7e9fe9a2167c9333de3046439771b | jtannas/intermediate_python | /ternary.py | 574 | 4.25 | 4 | """
6. Ternary Operators
Ternary operators are more commonly known as conditional expressions in
Python. These operators evaluate something based on a condition being
true or not. They became a part of Python in version 2.4
"""
# Modern Python Way.
def positive_test(num):
return 'positive' if num > 0 else 'not positive'
print(f"1 is {positive_test(1)}")
print(f"-1 is {positive_test(-1)}")
# Pre Python 2.4 way - do not use - it evaluates all possibities.
num = 3
print(('not positive', 'positve')[num > 0])
print(':-)' if True else 1/0)
print((1/0, ':D')[True])
| true |
fbdcbc79ff16ee1b43ad8a4beafcccf2ccf0d0f3 | xuyanlinux/code | /module01/第二章/用户交互和注释.py | 1,688 | 4.125 | 4 | # name = input("Name:")
# age = input("Age:")
# job = input("Job:")
# hometown = input("Hometown:")
#
# info = '''-------------info of %s----------------
# "Name:" %s
# "Age:" %s
# "Job:" %s
# "Hometown:" %s
# ----------------END----------------------
# '''% (name,name,age,job,hometown)
#
# print(info)
#
# a = 11
# b = 2
# print(a/b)
# print(a%b)
# print(a//b)
# score = int(input("Please input ur score:"))
# if score >100 or score < 0:
# print("Input your score between 0 and 100!")
# elif score > 89 and score <= 100:
# print("A")
# elif score > 79 and score < 90:
# print("B")
# elif score > 59 and score < 80:
# print("C")
# elif score > 39 and score < 60:
# print("D")
# else:
# print("E")
# count = 0
#
# while count <= 100:
# if count == 50:
# pass
# elif count >= 60 and count <=80:
# print(count ** 2)
# else:
# print("loop ",count)
# count += 1
#
# print("--------end-----------")
#
# age = 22
#
# count = 0
# 10
# while count < 3:
# guess = int(input("Please input the age:"))
# if age == guess:
# print("bingo,you get it!")
# break
# elif age > guess:
# print("try bigger!")
# else:
# print("try smaller!")
# count+=1
age = 22
count = 0
while count < 3:
guess = int(input("Please input the age:"))
if age == guess:
print("bingo,you get it!")
break
elif age > guess:
print("try bigger!")
else:
print("try smaller!")
count+=1
if count == 3:
re_or_not = input("one more chance? Please input 'yes' or 'no':")
if re_or_not == 'yes':
count =0 | false |
9b381446f85c86c9b92fb0749fe97301418828ff | Anjustdoit/Python-Basics-for-Data-Science | /string_try1.py | 546 | 4.25 | 4 | name = "hello"
print(type(name))
message = 'john said to me "I\'ll see you later"'
print(message)
paragraph = ''' Hi , I'm writing a book.
I will certainly do'''
print(paragraph)
hello = "Hello World!"
print(hello)
name = input('What is your name ? --> ')
print(name)
# What is your age
age = input('What is your age ? --> ')
print(age)
string = "you name is {} and you age is {}"
output = string.format(name,age)
print(output)
A = "part"
B=1
#print(A+str(B))
AF = "{} - {}".format(A,B)
print(AF) | true |
d50626ac217a242938030eb2621bc6263893c191 | martinak1/diceman | /diceman/roll.py | 2,993 | 4.25 | 4 | import random
def roll( num: int = 1, sides: int = 6) -> list:
'''
Produces a list of results from rolling a dice a number of times
Paramaters
----------
num: int
The number of times the dice will be rolled (Default is 1)
sides: int
The number of sides the dice has (Default is 6)
'''
results: list = []
[results.append(random.randint(1, sides)) for _ in range(1, sides)]
return results
# end roll
def filter_eq(results: list, qualifier: int) -> list:
'''
Filters the results from a dice roll that are equal to a certain value
Parameters
----------
results: list, required
The results of a dice roll, usually generated by the roll function
qualifier: int
The value the rolls are compaired against
'''
filtered_results: list = []
[filtered_results.append(i) for i in results if qualifier == i]
return filtered_results
# end filter_eq
def filter_gt(results: list, qualifier: int) -> list:
'''
Filters the results from a dice roll that are greater a certain value
Parameters
----------
results: list, required
The results of a dice roll, usually generated by the roll function
qualifier: int
The value the rolls are compaired against
'''
filtered_results: list = []
[filtered_results.append(i) for i in results if qualifier < i]
return filtered_results
# end filter_gt
def filter_gt_or_eq( results: list, qualifier: int ) -> list:
'''
filters the results from a dice roll that are greater than or equal to a certain value
parameters
----------
results: list, required
the results of a dice roll, usually generated by the roll function
qualifier: int
the value the rolls are compaired against
'''
filtered_results: list = []
[filtered_results.append(i) for i in results if qualifier <= i]
return filtered_results
# end filter_gt_or_eq
def filter_lt(results: list, qualifier: int) -> list:
'''
Filters the results from a dice roll that are less than a certain value
Parameters
----------
results: list, required
The results of a dice roll, usually generated by the roll function
qualifier: int
The value the rolls are compaired against
'''
filtered_results: list = []
[filtered_results.append(i) for i in results if i < qualifier]
return filtered_results
# end filter_lt
def filter_lt_or_eq( results: list, qualifier: int ) -> list:
'''
Filters the results from a dice roll that are less than or equal to a certain value
Parameters
----------
results: list, required
The results of a dice roll, usually generated by the roll function
qualifier: int
The value the rolls are compaired against
'''
filtered_results: list = []
[filtered_results.append(i) for i in results if i <= qualifier]
return filtered_results
# end filter_lt_or_eq
| true |
78238441fc78c9fe1c1ba488dc2db3120ed9a3fd | marcelomatz/py-studiesRepo | /python_udemy/introducao-python/dictionary-comprehension.py | 494 | 4.15625 | 4 | lista = [
('chave', 'valor'),
('chave2', 'valor2'),
]
d1 = {x.upper(): y.upper() for x, y in lista}
print(d1)
print()
print('# OU USANDO UM JEITO MAIS SIMPLES \t dict \t PORÉM SEM ALGUNS RECURSOS DE USAR OUTRAS FUNÇÕES NATIVAS')
print()
d1 = dict(lista)
print(d1)
# Usando enumerate para criar uma chave - meio sem utilidade porém prático para relembrar enumerate
d2 = {x: y for x, y in enumerate(range(21))}
print(d2)
d3 = {f'chave_{x}': x * 2 for x in range(15)}
print(d3)
| false |
40836d6ef03d53ffb58056150c265ec687fa64ef | marcelomatz/py-studiesRepo | /python_udemy/introducao-python/tuplas.py | 452 | 4.21875 | 4 | """
O que difere Tuplas de Listas é que nas Tuplas não é possível:
- alterar o valor das tuplas
- alterar o índice
- alterar porra nenhuma
"""
# t1 = 1, 2, 3, 'a', 'Marcelo Matzembacher'
# print(t1)
# t1 = (1, 2, 3, 4, 5)
# t2 = (6, 7, 8, 9, 10)
# t3 = t1 + t2
# print(t3, type(t3))
# UMA TUPLA NÃO ACEITA TER SEU VALOR MODIFICADO.
# t2 = (1, 2, 3, 4, 5)
# t2[1] = 5000
# print(t2)
t = (1, 2, 3, 4, 5)
t = list(t)
t[1] = 'Marcelo'
t = tuple(t)
print(t)
| false |
5f7c4b34d1211802b3a8eb13dfe2b37544e5b60f | Cakarena/CS-2 | /sum_double_f.py | 279 | 4.125 | 4 | def sum_double(a,b):
a=int(a)
b=int(b)
if a == b:
sum = (a + b) * 2
print (sum)
elif a != b:
sum = (a + b)
print (sum)
sum_double(1,2)
sum_double(3,2)
sum_double(2,2)
sum_double(-1,0)
sum_double(3,3)
sum_double(0,0)
sum_double(0,1)
sum_double(3,4) | false |
36028b8aae863b3c6de5d5e1e76f32c6037c7d7f | Cakarena/CS-2 | /numprint.py | 235 | 4.15625 | 4 | ##Write a Python program that prints all the numbers from 0 to 6 except 3 and 6.
## Note : Use 'continue' statement. Name the code. Expected Output : 0 1 2 4 5
for i in range(0,7):
if i==3 or i==6:
continue
print(i,end='')
| true |
097b292ea5a0d040181ec80c9beb3965f1cacb93 | JohnKlaus-254/python | /Python basics/String Operations.py | 1,105 | 4.28125 | 4 | #CONCACTINATION using a plus
#CONCACTINATION using a format
first_name= "John"
last_name = "Klaus"
full_name = first_name +' '+ last_name
print(full_name)
#a better way to do this is;
full_name = "{} {}".format(first_name, last_name)
print(full_name)
print("this man is called {} from the family of {} ".format(first_name, last_name))
#format
names ="John Klaus"
name2 = "jake williams"
name3 = "DENNIS WAWERU"
print(name2.title())
#count - counts the number of time something has been repeated
#python is case sensitive
sen="Man is to error because man did not create Man"
print(sen.lower().count("a"))
#String slicing
#left of the colon signify the starting element
#right of the coon signify the ending position but that element in that position is excluded. so to include it, add up to the next element.
print(sen[0:15])
jina = "muyani"
print(jina[1:-2])
print(jina[2::-2])
print(sen.split())
sente ="learning more string funtions"
print(sente.join())
print(sente.replace())
print(sente.index())
print(sente.find())
print(sente.center())
print(sente.isalpha())
| true |
7dd6519daded48e31f9c24276fee8f1c51a19623 | GuptaNaman1998/DeepThought | /Python-Tasks/Rock-Paper-Scissors/Code.py | 999 | 4.21875 | 4 | """
0-Rock
1-Paper
2-Scissor
"""
import random
import os
def cls():
os.system('cls' if os.name=='nt' else 'clear')
Options={0:"Rock",1:"Paper",2:"Scissor"}
# Created Dictionary of available choices
poss={(0, 1):1,(0, 2):0,(1, 2):2}
# Dictionary of possibilities and the winner value
# print("Hi User!")
player=int(input("Please enter your choice: 0-Rock | 1-Paper | 2-Scissor : "))
# User input
while player not in Options.keys():
cls()
player=int(input("Please enter your choice: 0-Rock | 1-Paper | 2-Scissor : "))
print("you choose "+Options[player] )
computer=random.randrange(0,3)
# Comuters random choice
print("computer choose "+Options[computer] )
res=[player,computer]
res.sort()
res=tuple(res)
# Below is the if else loop to decide winner
if player==computer:
print(" It is a tie !!...")
elif poss[res]==computer:
print("Computer won the game by choosing "+Options[computer] )
elif poss[res]==player:
print("You won the game by choosing "+Options[player] ) | true |
ce4fe060c3a35b03a49650e8aa385dc68d42715d | alexhohorst/MyExercises | /ex3.py | 844 | 4.28125 | 4 | print "I will now count my chickens:"
print "Hens", 25 + 30 / 6 #adds 25 and 30 and divides this by 6
print "Roosters", 100 - 25 * 3 % 4 #substracts 25 from 100, multiplies with 3 and divides by 4, returning the remainder
print "Now I will count the eggs:"
print 3 + 2 + 1 - 5 + 4 % 2 - 1 / 4 + 6 #adds 3 and 2 and 1, substracts 5, adds 4, divides this by 2, returning the remainder, substracts 1, divides by 4 and adds 6
print "Is it true that 3 + 2 < 5 - 7?"
print 3 + 2 < 5 - 7
print "What is 3 + 2?", 3 + 2 #adds 3 plus 2
print "What is 5 - 7?", 5 - 7 #substracts 5 and 7
print "Oh, that's why it's false."
print "How about some more."
print "Is it greater?", 5 > -2 #any statement that is true
print "Is it greater or equal?", 5 >= -2 #any statement that is true
print "Is it less or equal?", 5 <= -2 #any statement that is false
| true |
8feadece0e5459fa7c9323550be42e5d88c14da1 | sptechguru/python-Core-Interview | /Factorial.py | 257 | 4.25 | 4 | def factorial(n):
if(n<=1):
return 1
else:
return(n*factorial(n-1))
n = int(input("Enter an Number:"))
print("Factorial number is:", factorial(n))
# Output is:
# Enter a Number : 5
# 1x2x3x4x5 =120
# Factorial number is: 120
| false |
f494f59caa548f497bd1d3825fd5448ac3cff339 | MReeds/Classes-Practices | /pizzaPractice/classes.py | 1,021 | 4.4375 | 4 | #Add a method for interacting with a pizza's toppings,
# called add_topping.
#Add a method for outputting a description of the
#pizza (sample output below).
#Make two different instances of a pizza.
#If you have properly defined the class,
#you should be able to do something like the
#following code with your Pizza type.
class Pizza:
def __init__(self):
self.size = ""
self.crust_type = ""
self.toppings = list()
def add_topping(self, item):
self.toppings.append(item)
def print_order(self):
print(f"I would like a {self.size}-inch, {self.crust_type} pizza with {' and '.join(self.toppings)}.")
my_pizza = Pizza()
my_pizza.size = 16
my_pizza.crust_type = "thin crust"
my_pizza.add_topping("mushrooms")
my_pizza.add_topping("bell peppers")
my_pizza.print_order()
his_pizza = Pizza()
his_pizza.size = 12
his_pizza.crust_type = "Deep dish"
his_pizza.add_topping("sausage")
his_pizza.add_topping("onions")
his_pizza.print_order()
| true |
4577573df7b0866f4ee5e4fb46d6b4de38fea7c0 | 11810729/python-programming | /fibonacciseries.py | 272 | 4.125 | 4 | nterms=10
n1=0
n2=1
count=0
if nterms<=0:
print("please enter a positive integer")
elif nterms==1:
print("Fibonacci sequence upto",nterms,":")
print(n1)
else:
print("Fibonacci sequence upto",nterms,":")
while count<nterms:
print(n1,end=',')
nth=n1+n2
n1=n2
n2=nth
count+=1 | false |
bf49ad63a8611cdbcfc34e384f940d47e9eed772 | SethMiller1000/Portfolio | /Foundations of Computer Science/Lab 11- String Contents.py | 1,202 | 4.28125 | 4 | # The String Contents Problem- Lab 11: CIS 1033
# Seth Miller and Kaitlin Coker
# Explains purpose of program to user
print("Hello! This program takes a string that you enter in and tells you what the string contains.")
# Ask user for string
userString = input("Please enter a string ---> ")
# Tests if it contains only letters
if userString.isalpha():
print("This string contains only letters.")
# Tests if it contains only uppercase letters
if userString.isupper():
print("This string contains only uppercase letters.")
# Tests if it contains only lowercase letters
if userString.islower():
print("This string contains only lowercase letters.")
# Tests if it contains only digits
if userString.isdigit():
print("This string contains only digits.")
# Tests if it contains only letters and digits
if userString.isalnum():
print("This string contains only letters and digits.")
# Tests if it starts with an uppercase letter
firstCharacter = userString[0]
if firstCharacter.isupper():
print("This string starts with an uppercase letter.")
# Tests if it ends with a period
if userString.endswith("."):
print("This string ends with a period.")
| true |
74a25f4969bc732424c26c88dc80441e2f4f499d | SethMiller1000/Portfolio | /Foundations of Computer Science/Lab 17- Training Heart Rate.py | 1,034 | 4.21875 | 4 | # The Training Heart Rate Problem
# Lab 17: CIS 1033
# Author: Seth Miller
# function that calculates training heart rate
# based on age and resting heart rate
def trainingHeartRate( age, restingHeartRate ) :
maxHeartRate = 220 - age
result = maxHeartRate - restingHeartRate
result2 = result * 0.60
trainingHeartRate = result2 + restingHeartRate
return trainingHeartRate
# MAIN METHOD #
# Explain purpose of program to user
print(" Hello! This program calculates your training heart rate")
print(" based on your age and resting heart rate.")
print( "" )
# Ask user for age and resting heart rate
ageInput = int(input("Please enter your age: "))
restingRateInput = int(input("Please enter your heart rate when resting: "))
print( "" )
# Call function to calculate training heart rate
userTrainingRate = trainingHeartRate( ageInput, restingRateInput )
# Display training heart rate of user
print("Your training heart rate is " + str(userTrainingRate) + ".")
| true |
bd4bf3185496a137ef716b6188082d27b9f084e8 | SethMiller1000/Portfolio | /Foundations of Computer Science/Lab 9- Electric Bill.py | 1,048 | 4.25 | 4 | # The Electric Bill Problem- Lab 9 CIS 1033
# Author: Seth Miller
# Input: receives the meter reading for the previous
# and current month from the user
prevMonthMeterReading = int(input("Meter reading for previous month: "))
currentMonthMeterReading = int(input("Meter reading for current month: "))
# Input: assigns values to flat monthly fee
# and charge per extra kilowatt hour variable
FLAT_MONTHLY_FEE = 20
CHARGE_PER_EXTRA_KILOWATT_HOUR = 0.03
# Process: calculates usage for the month in kilowatt hours
usageForMonth = currentMonthMeterReading - prevMonthMeterReading
# Process: tests if there is an added fee and calculates total bill
if (usageForMonth > 300):
addedFee = CHARGE_PER_EXTRA_KILOWATT_HOUR * (usageForMonth - 300)
totalBill = FLAT_MONTHLY_FEE + addedFee
else:
totalBill = FLAT_MONTHLY_FEE
# Output: displays the usage and the total bill for the month
print("Usage for the month is " + str(usageForMonth) + " kilowatt hours.")
print("Total bill for the month is $" + str(totalBill) + ".")
| true |
3040a6b355ca4ac3a5a1e2c7c4c5cba7a70c4c58 | phlalx/algorithms | /leetcode/326.power-of-three.python3.py | 706 | 4.15625 | 4 | # TAGS trick
class Solution:
def isPowerOfThree(self, n):
"""
:type n: int
:rtype: bool
"""
return (
n > 0 and 3 ** 20 % n == 0
) # we suppose we know the biggest possible power
# def ispowerof3(n)
# if n < 1:
# return False
# while n % 3 == 0: # divide n by 3 as many times as possible
# n //= 3
# return True if n == 1 else False
# def ispowerof3(n):
# # find the smallest power of 3 just above n
# if n < 1:
# return False
# u = 1
# while u < n:
# u *= 3
# return n == u
| false |
c3050341b766f637b39ba112c5967a9b43d74dfe | MortalKommit/Coffee-Machine | /coffee_machine.py | 2,630 | 4.1875 | 4 |
class CoffeeMachine:
def __init__(self, capacity, menu):
self.capacity = {}
contents = ("water", "milk", "coffee beans", "disposable cups", "money")
for content, cap in zip(contents, capacity):
self.capacity[content] = cap
self.menu = menu
def get_user_input(self):
action = ''
while action != 'exit':
print("Write action (buy, fill, take, remaining, exit):")
action = input()
self.process_action(action)
def process_action(self, action):
if action == "buy":
print("What do you want to buy? 1 - espresso, 2 - latte, 3 - cappuccino, back - to main menu:")
order = input()
if order == 'back':
return
for key in self.capacity.keys():
if key != "money":
if self.capacity[key] - self.menu[order][key] < 0:
print(f"Sorry, not enough {key}!")
break
else:
print("I have enough resources, making you a coffee!")
# Add money
self.capacity["money"] += self.menu[order]["money"]
# Subtract the rest
for key in self.capacity.keys():
if key != "money":
self.capacity[key] -= self.menu[order][key]
elif action == "fill":
print("Write how many ml of water do you want to add:")
self.capacity["water"] += int(input())
print("Write how many ml of milk do you want to add:")
self.capacity["milk"] += int(input())
print("Write how many grams of coffee beans do you want to add:")
self.capacity["coffee beans"] += int(input())
print("Write how many disposable cups do you want to add:")
self.capacity["disposable cups"] += int(input())
elif action == "take":
print(f"I gave you ${self.capacity['money']}")
self.capacity["money"] = 0
elif action == "remaining":
print("The coffee machine has:")
for key, value in self.capacity.items():
print(value, f"of {key}")
cafe_menu = {'1': {"water": 250, "milk": 0, "coffee beans": 16, "disposable cups": 1, "money": 4},
'2': {"water": 350, "milk": 75, "coffee beans": 20, "disposable cups": 1, "money": 7},
'3': {"water": 200, "milk": 100, "coffee beans": 12, "disposable cups": 1, "money": 6}
}
caffe = CoffeeMachine((400, 540, 120, 9, 550), cafe_menu)
caffe.get_user_input() | true |
1702acae637148eee91612d432b6e8fa4d594205 | toddljones/advent_of_code | /2019/1/a.py | 1,013 | 4.4375 | 4 | """
Fuel required to launch a given module is based on its mass. Specifically, to
find the fuel required for a module, take its mass, divide by three, round
down, and subtract 2.
For example:
- For a mass of 12, divide by 3 and round down to get 4, then subtract 2 to get
2.
- For a mass of 14, dividing by 3 and rounding down still yields 4, so the fuel
required is also 2.
- For a mass of 1969, the fuel required is 654.
- For a mass of 100756, the fuel required is 33583.
The Fuel Counter-Upper needs to know the total fuel requirement. To find it,
individually calculate the fuel needed for the mass of each module (your puzzle
input), then add together all the fuel values.
What is the sum of the fuel requirements for all of the modules on your
spacecraft?
"""
from math import floor
modules = []
for modmass in [int(x.strip()) for x in open("input.a").readlines()]:
print(f"modmass={modmass}")
modules.append(floor(modmass / 3) - 2)
ttl_fuel = sum(modules)
print(f"ttl_fuel={ttl_fuel}")
| true |
12cd29f06a3438996e74f627d0fffacbbb3e4b1a | CertifiedErickBaps/Python36 | /Ciclos While/Practica 5/invert.py | 754 | 4.1875 | 4 | # Authors:
# A01379896 Erick Bautista Pérez
#
#Write a program called invert.py. Define in this program a function called invert(n)
#that returns an integer comprised of the same digits contained in n but in reversed order.
#For example, invert(2015) should return the number 5102. Do not use any string operations to
#solve this problem.
# October 7, 2016.
def invert(n):
resultado = 0
while n != 0:
residuo = n % 10
n //= 10
resultado = resultado * 10 + residuo #Se puede dejar asi por el orden de las operaciones
return resultado #Para que regrese el resultado
def main():
print(invert(2015))
print(invert(123456789))
print(invert(1000))
print(invert(9999))
print(invert(1234) + 1)
main() | false |
694ac91eec52f84fdac4581f1cd3be42554925d4 | CertifiedErickBaps/Python36 | /Listas/Practica 7/positives.py | 1,028 | 4.125 | 4 | # Authors:
# A013979896 Erick Bautista Perez
#
#Write a program called positives.py. Define in this program a function called
#positives(x) that takes a list of numbers x as its argument, and returns a new
#list that only contains the positive numbers of x.
#
# October 28, 2016.
def positives(x):
a = []
for c in x:
if c >= 0:
a += [c]
return a
def main():
print(positives([-21, -31]))
print(positives([-48, -2, 0, -47, 45]))
print(positives([-9, -38, 49, -49, 32, 6, 4, 26, -8, 45]))
print(positives([-27, 48, 13, 5, 27, 5, -48, -42, -35, 49,
-41, -24, 11, 29, 33, -8, 45, -44, 12, 46]))
print(positives([-2, 0, 27, 47, -13, -23, 8, -28, 23, 7,
-29, -24, -30, -6, -21, -17, -35, -8, -30,
-7, -48, -18, -2, 1, -1, 18, 35, -32, -42,
-5, 46, 8, 0, -31, -23, -47, -4, 37, -5,
-45, -17, -5, -29, -35, -2, 40, 9, 25, -11,
-32]))
main() | true |
df7911328fd4b62321d98a88f8399978c053c5d0 | CertifiedErickBaps/Python36 | /Manipulacion de textos/Practica 6/username.py | 2,277 | 4.3125 | 4 | # Authors:
# A01379896 Erick Bautista Pérez
#Write a program called username.py. Define in this program a function called username(first, middle, last)
#that takes the first name, middle name, and last name of a person and generates her user name given the above
#rules. You may assume that every first name has at least one letter and every middle name has at least one
#consonant. Use string.lower() to convert string into lower case letters.
#
# October 14, 2016.
#def first(name):
# for c in name:
# if name != "":
# return str.lower(name[:1])
#def middle(name1):
# for a in name1:
# if a not in "AEIOUaeiou":
# return str.lower(a)
#def last(name2):
# if name2 < name2[0:6]:
# return str.lower(last)
# else:
# return str.lower(name2[0:6])
#def main():
# print(first('Scarlett'), middle('Ingrid'), last('Johansson'), sep ="")
# print(first('Donald'), middle('Ervin'), last('Knuth'), sep ="")
# print(first('Alan'), middle('Mathison'), last('Turing'), sep ="")
# print(first('Martin'), middle('Luther'), last('King'), sep ="")
# print(first('Stephen'), middle('William'), last('Hawking'), sep ="")
# print(first('Alejandro'), middle('Gonzalez'), last('Inarritu'), sep ="")
#main()
def primera_consonante(cadena):
for c in cadena.lower(): # .lower() es para regresar el valor en minusculas
if c in "bcdfghjklmnpqrtsvwxyz":
return c #en este return acaba inmediatamente y regresa la consonante
def username(first, middle, last):
resultado = first[0]
resultado += primera_consonante(middle)
resultado += last
if len(resultado) > 8: #El len() me regresa el numero de caracteres
resultado = resultado[:8]
resultado = resultado.lower() #Este resultado esta fuera del if por que es una condicion a llamar con el tamaño
return resultado
def main():
print(username('Scarlett', 'Ingrid', 'Johansson'))
print(username('Donald', 'Ervin', 'Knuth'))
print(username('Alan', 'Mathison', 'Turing'))
print(username('Martin', 'Luther', 'King'))
print(username('Stephen', 'William', 'Hawking'))
print(username('Alejandro', 'Gonzalez', 'Inarritu'))
main()
| true |
5af607504652e3240c32ecfb8a764987e5e58786 | Exclusive1410/practise3 | /pr3-4.py | 231 | 4.34375 | 4 | #Write Python program to find and print factorial of a number
import math
def fact(n):
return (math.factorial(n))
num = int(input('Enter the number:'))
factorial = fact(num)
print('Factorial of', num, 'is', factorial) | true |
f14a298f9b623616b2e81fe80aa2d1860e707bf4 | StephenJonker/python-sample-code | /sort-list/sort-list-of-integer-list-pairs.py | 1,780 | 4.25 | 4 | # uses python3
#
# Written by: Stephen Jonker
# Written on: Tuesday 19 Sept 2017
# Copyright (c) 2017 Stephen Jonker - www.stephenjonker.com
#
# Purpose:
# - basic python program to show sorting a list of number pairs
#
# - Given a list of integer number pairs that will come from STDIN
# - first read in n, the number of lines of input containing input pairs
# - then for 1 to n, read in each integer number pair into a list like structure
# with each number pair also in a list
# - this will create a list whose elements are lists, that contains integer number pairs
# E.g.: [ [1,10], [7,70], [2,20], [4, 40] ]
# - Once read, sort the list based on the first or second list-pair elelment
#
# E.g. input
# 3
# 1 10
# 7 70
# 2 20
# 4 40
#
# Output:
# - the sorted list of list pairs
# E.g. [['1', '10'], ['2', '20'], ['4', '40'], ['7', '70']]
#
# Constraints:
# - the program does not do input validation
if __name__ == "__main__":
debug = False
# get the number of lines to input from STDIN
n = int(input())
if debug: print("Input n: " + str(n) + " Type: " + str(type(n)) )
numberPair = []
theList = []
# Get the lines of input and store in a list of number pairs
# E.g.: [ [1,10], [7,70], [2,20], [4, 40] ]
for i in range(0,n):
numberPair = input().split()
theList.append(numberPair)
if debug: print("The pair list: " + str(theList) + " Type: " + str(type(theList)) )
if debug: print("Length of the list: " + str(len(theList)))
# Function to return the first element of the integer list pair
# Needed to make the "sorted" function work with more complex list elements
def sortKey(item):
return item[0]
newSortedList = sorted(theList, key=sortKey)
if debug: print("newSortedList: " + str(newSortedList))
print(str(newSortedList))
#
# End of file.
# | true |
cf5a25d897a55ed3ffe9cf4b70c7a3f352b16c56 | sylviocesart/Curso_em_Video | /Desafios/Desafio10.py | 1,205 | 4.15625 | 4 | """
Crie um programa que leia quanto dinheiro
uma pessoa tem na carteira e mostre quantos
Dólares ela pode comprar
Considere US$ 1,00 = R$ 3,27
"""
dolar = 3.27
print('\nAtualmente o valor do dólar é: {}\n'.format(dolar))
valor = float(input('Quanto de dinheiro você tem na carteira? '))
qnt_dolar = valor // 3.27
qnt_centavos = valor % 3.27
menor_dolar = valor / 3.27
if valor < 3.27:
print('Valor mínimo para se comprar um dólar é {}'.format(dolar))
print('Com esse valor, você só consegue comprar {:.2f} centavos de dólar.'.format(menor_dolar))
else:
if qnt_dolar == 1:
if qnt_centavos == 0:
print('Com o valor de R$ {}, você consegue comprar {} dólar.'.format(valor, qnt_dolar))
else:
print('Com o valor de R$ {}, você consegue comprar {} dólar e {:.2f} centavos de dólar.'.format(valor, qnt_dolar, qnt_centavos))
elif qnt_dolar > 1:
if qnt_centavos == 0:
print('Com o valor de R$ {}, você consegue comprar {} dólares.'.format(valor, qnt_dolar))
else:
print('Com o valor de R$ {}, você consegue comprar {} dólares e {:.2f} centavos de dólar.'.format(valor, qnt_dolar, qnt_centavos))
| false |
e6b38846ceed488f1334a77279b1220c31a4d21d | jeansabety/learning_python | /frame.py | 608 | 4.25 | 4 | #!/usr/bin/env python3
# Write a program that prints out the position, frame, and letter of the DNA
# Try coding this with a single loop
# Try coding this with nested loops
dna = 'ATGGCCTTT'
for i in range(len(dna)) :
print(i, i%3 , dna[i]) #i%3 -> divide i (which is a number!) by i, and print the remainder
for i in range(0, len(dna), 3) : #i = 0, 3, 6, 9
for j in range(3) : # j = 0,1,2
print(i+j, j, dna[i+j]) #i+j -> number of characters in dna (0+0, 0+1, 0+2, 3+0...) // j -> "frame" // dna[i+j] -> dna[1..9]
"""
python3 frame.py
0 0 A
1 1 T
2 2 G
3 0 G
4 1 C
5 2 C
6 0 T
7 1 T
8 2 T
"""
| true |
632a36b7c686db27cfee436935eecfc9ba74be30 | jeansabety/learning_python | /xcoverage.py | 1,902 | 4.15625 | 4 | #!/usr/bin/env python3
# Write a program that simulates random read coverage over a chromosome
# Report min, max, and average coverage
# Make variables for genome size, read number, read length
# Input values from the command line
# Note that you will not sample the ends of a chromosome very well
# So don't count the first and last parts of a chromsome
#I do not understand what this assignment is asking
#have a genome, fill it up with reads, does some region have 2x as much
#1 sequencing read that cover x amount of base pairs
#repeat and then see how many nt were read more than once
#how much sequencing do you need to do to cover the entire genome
#genome is 100 bp long, read= 10, 1x coverage = 10 reads (enough to go over the genome once) but does this actually happen?
import sys
import random
gen_size = int(sys.argv[1])
rnum = int(sys.argv[2])
rlen = int(sys.argv[3])
#1. empty set of zeros for the genome
genome = [0] * gen_size
#print(genome)
#for every read, pick a random starting point, and then read
for i in range(rnum) : #do this for the number of reads
#print(i)
x = random.randint(0, len(genome) - rlen) #choose a random value in the genome, do not want to sampel anything that "falls off" - last reads last value should be the last value of the list
for j in range(rlen) :
#print(x +j)
genome[x+j] += 1 #j will be every value as long as the read length, will add one to the next value everytime we run through the loop
#print(genome)
#minimum, max, avg:
min = genome[rlen] #don't want to sample ends because they get sampled less
max=genome[rlen]
total = 0
for n in genome[rlen:-rlen]: #-1 = last values, once again you don't want to sample ends
if n<min : min = n
if n>max : max = n
total += n #n will be the number of times the nt was counted
print(min, max, total/(gen_size - 2*rlen))
"""
python3 xcoverage.py 1000 100 100
5 20 10.82375
"""
| true |
7efe190f957eec5b5c7a62adb1e45b520066f33f | bensenberner/ctci | /peaksAndValleys.py | 638 | 4.40625 | 4 | '''
in an array of ints, a peak is an element which is greater than or equal to the adjacent integers.
the opposite for a valley. Given an array of ints, sort it into an alternating sequence of peaks and valleys.
'''
def peakSort(arr):
for i in range(1, len(arr), 2):
# make sure indices don't go out of bounds
if arr[i] < arr[i-1] or arr[i] < arr[i+1]:
if arr[i-1] > arr[i+1]:
arr[i], arr[i-1] = arr[i-1], arr[i]
else:
arr[i], arr[i+1] = arr[i+1], arr[i]
if __name__ == "__main__":
arr = [5, 3, 1, 2, 3, 4]
print(arr)
peakSort(arr)
print(arr)
| true |
3559ace9fe63307597bf924f37bc080da3490e00 | GabyPopolin/Estrutura_Sequencial | /Estrutura_Sequencial_exe_07.py | 278 | 4.125 | 4 | '''Faça um Programa que calcule a área de um quadrado, em seguida mostre o dobro desta área para o usuário.'''
n = float(input('Digiite o valor de um dos lados do quadrado: '))
a = (n**2) * 2
print('')
print('O dobro do valor da área do quadrado é: {}' .format(a)) | false |
f28956d14fb2d0b41b40cda2042d43b28ac500ab | GabyPopolin/Estrutura_Sequencial | /Estrutura_Sequencial_exe_06.py | 231 | 4.125 | 4 | import math
'''Faça um Programa que peça o raio de um círculo, calcule e mostre sua área.'''
r = float(input('Digite o raio do círculo: '))
a = (r**2) * 3.14
print('')
print('Á área do círculo é: {}' .format(a)) | false |
1a5541ac2b3af545ec206ad68986eaf8d6232512 | dheerajps/pythonPractice | /algorithms/unsortedArrayHighestProduct.py | 1,344 | 4.21875 | 4 | # same as highestProduct.py
# but find the maximum product possible by three numbers in an array without sorting it
#so O(N) must be time requirements
def getMaxProductOfThreeNumbers(array):
import sys
#Max product can be 3 maximum numbers or 2 minimum numbers and 1 max
firstMax = -sys.maxsize-1
secondMax = -sys.maxsize-1
thirdMax = -sys.maxsize-1
firstMin = sys.maxsize
secondMin = sys.maxsize
i=0
#loop throught the array and keep updating the values
while i < len(array):
if(array[i]>firstMax):
thirdMax = secondMax
secondMax = firstMax
firstMax = array[i]
elif(array[i]>secondMax):
thirdMax = secondMax
secondMax = array[i]
elif(array[i]>thirdMax):
thirdMax = array[i]
if(array[i]<firstMin):
secondMin = firstMin
firstMin = array[i]
elif(array[i] < secondMin):
secondMin = array[i]
i+=1
#find the maximum possible product and return it
return max(firstMin*secondMin*firstMax , firstMax*secondMax*thirdMax)
inputArray = [-1,-7,-8,3,-1,-5,2,3,8,9]
print " The input array is ",inputArray
maxProduct = getMaxProductOfThreeNumbers(inputArray)
print " The max product from 3 numbers(using O(n) time) is ",maxProduct
| true |
32e8588930e8821ae35ef762dc37c3fa5368fd97 | lyndsiWilliams/cs-module-project-algorithms | /sliding_window_max/sliding_window_max.py | 1,063 | 4.5 | 4 | '''
Input: a List of integers as well as an integer `k` representing the size of the sliding window
Returns: a List of integers
'''
def sliding_window_max(nums, k):
# Your code here
# Check if numbers array exists
if nums:
# Set an empty list for the max numbers to live
max_numbers = []
# Loop through the list of numbers
for i in range(len(nums)):
# If k is <= the length of the numbers list
if k <= len(nums):
# Set the window to start at the current index and
# end 'k' elements over
window = nums[i:k]
# Move the window up one position
k += 1
# Append the max number to the max_numbers array
max_numbers.append(max(window))
return max_numbers
if __name__ == '__main__':
# Use the main function here to test out your implementation
arr = [1, 3, -1, -3, 5, 3, 6, 7]
k = 3
print(f"Output of sliding_window_max function is: {sliding_window_max(arr, k)}")
| true |
a2b4f9b45b1888a518e7db8a687c3bf452aca122 | manu4xever/leet-code-solved | /reverse_single_linked_list.py | 506 | 4.1875 | 4 | Reverse a singly linked list.
Example:
Input: 1->2->3->4->5->NULL
Output: 5->4->3->2->1->NULL
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def reverseList(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
temp=None
while head:
head.next,head,temp=temp,head.next,head
return temp | true |
0d4b6e26e09ea7d90e4d45941f07a4d9046ba1b4 | Hety06/caesar_cipher | /caesar_cipher.py | 878 | 4.1875 | 4 | def shift(letter, shift_amount):
unicode_value = ord(letter) + shift_amount
if unicode_value > 126:
new_letter = chr(unicode_value - 95)
else:
new_letter = chr(unicode_value)
return new_letter
def encrypt(message, shift_amount):
result = ""
for letter in message:
result += shift(letter, shift_amount)
return result
def decrypt(message, shift_amount):
result = ""
for letter in message:
result += shift(letter, -shift_amount + 95)
return result
unencrypted_message = "Apples can taste sour \ sweet, but Timmy says that some apples are both sour and sweet! What do you think?"
encrypted_message = encrypt(unencrypted_message, 10)
decrypted_message = decrypt(encrypted_message, 10)
print(unencrypted_message)
print(encrypted_message)
print(decrypted_message)
| true |
1eb92fd964d785db16d04628b9734810a5460374 | anterra/area-calculator | /area_calculator.py | 1,016 | 4.15625 | 4 | import math
class Rectangle:
def __init__(self, length1, length2):
self.length1 = length1
self.length2 = length2
def area(self):
area = self.length1 * self.length2
return area
class Circle:
def __init__(self, radius):
self.radius = radius
def area(self):
area = math.pi * self.radius ** 2
return area
while True:
shape = input("Area Calculator. Is your shape a rectangle, circle, or triangle? ")
if shape == "rectangle" or "triangle":
length1 = int(input("What is the width/base? "))
length2 = int(input("What is the height? "))
my_shape = Rectangle(length1, length2)
if shape == "rectangle":
print(my_shape.area())
elif shape == "triangle":
print(my_shape.area()/2)
break
elif shape == "circle":
radius = int(input("What is the radius? "))
my_shape = Circle(radius)
print(my_shape.area())
break
else:
break
| true |
f8cb2d4ff4976169893c680ba37018de7e936e34 | dileep208/dileepltecommerce | /test/one.py | 341 | 4.25 | 4 | # This is for printing
print('This is a test')
# This is for finding the length of a string
s = 'Amazing'
print(len(s))
# This for finding the length of hippopotomus
s='hippopotomous'
print(len(s))
# This is for finding the length of string
print('Practice makes man perfect')
# finding the length of your name
s = 'dileep'
print(len(s))
it | true |
46f4ccac098130227ddf177fc99365cbffa31f86 | siva6160/helloworld | /becomde9-3.py | 236 | 4.15625 | 4 | import math as m
def pow(num,p):
res=num**p
return res
num=int(input("enter a number"))
p=int(input("enter a num"))
s=pow(num,p)
print(s)
print(m.pow(num,p))
print(m.sqrt(num))
print(m.ceil(num))
print(m.floor(num))
| false |
580e061bc9d72a90ed2411c6ea7b8393f3b6e0f4 | johnnyferreiradev/python-course-microsoft | /formatting-strings.py | 295 | 4.1875 | 4 | first_name = 'Johnny'
last_name = 'Ferreira'
output = 'Hello, ' + first_name + ' ' + last_name
output = 'Hello, {} {}'.format(first_name, last_name)
output = 'Hello, {1} {0}'.format(first_name, last_name)
# Only available in Python 3
output = f'Hello, {first_name} {last_name}'
print(output) | false |
a7a5cbedf25dc380bfcf6c152cfa4848d32f0c55 | vinaykumar7686/Algorithms | /Data Structures/Binary-Tree/Binary Search Tree/[BST] Validate Binary Search Tree.py | 2,161 | 4.375 | 4 | # Validate Binary Search Tree
'''
Given the root of a binary tree, determine if it is a valid binary search tree (BST).
A valid BST is defined as follows:
The left subtree of a node contains only nodes with keys less than the node's key.
The right subtree of a node contains only nodes with keys greater than the node's key.
Both the left and right subtrees must also be binary search trees.
Example 1:
Input: root = [2,1,3]
Output: true
Example 2:
Input: root = [5,1,4,null,null,3,6]
Output: false
Explanation: The root node's value is 5 but its right child's value is 4.
Constraints:
The number of nodes in the tree is in the range [1, 104].
-231 <= Node.val <= 231 - 1
'''
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def __init__(self):
self.ans = True
def isValidBST(self, root: TreeNode) -> bool:
def func(root, l, r):
if root:
if root.val<=l or root.val>=r:
self.ans = False
return
func(root.left, l, root.val)
func(root.right, root.val, r)
func(root, float("-inf"), float("inf"))
return self.ans
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution1:
def __init__(self):
self.nums = []
def isValidBST(self, root: TreeNode) -> bool:
def inorder(root):
if not root:
return
inorder(root.left)
self.nums.append(root.val)
inorder(root.right)
inorder(root)
# print(self.nums, sorted(self.nums))
return self.nums == sorted(self.nums) and len(self.nums) == len(set(self.nums))
| true |
867ffc604bc02ee32ef1798070530ef9861ef0a1 | vinaykumar7686/Algorithms | /Algorithms/Dynamic_Programming/Nth_Fibonacci_No/fibonacci _basic _sol.py | 1,022 | 4.40625 | 4 | def fibo_i(n):
'''
Accepts integer type value as argument and returns respective number in fibonacci series.
Uses traditional iterative technique
Arguments:
n is an integer type number whose respective fibonacci nyumber is to be found.
Returns:
nth number in fiboacci series
'''
# Simply returning the value if the value of n is 0 or 1
if n in [0,1]:
return n
else:
a = 0
b = 1
c = a+b
while n-2>0:
n-=1
a=b
b=c
c = a+b
return c
def fibo_r(n):
'''
Accepts integer type value as argument and returns respective number in fibonacci series.
Uses traditional recursive technique
Arguments:
n is an integer type number whose respective fibonacci nyumber is to be found.
Returns:
nth number in fiboacci series
'''
if n in [0,1]:
return n
else:
return fibo_r(n-1)+fibo_r(n-2)
n = int(input('Enter the number : '))
print(fibo_r(n)) | true |
f04e1c9e1d991242d1dcce33de00c651125572a7 | ziolkowskid06/Python_Crash_Course | /ch10 - Files and Exceptions/10-03. Guest.py | 222 | 4.4375 | 4 | """
Write a program that prompts the user for their name.
"""
name = input("What's your name? ")
filename = 'guest.txt'
# Save the variable into the .txt file
with open(filename, 'w') as f:
f.write(name)
| true |
daddc2badb17111c59d9406fdeb09dd7871b620e | ziolkowskid06/Python_Crash_Course | /ch05 - IF Statements/5-02. More Conditional Tests.py | 673 | 4.125 | 4 | """
Write more conditional tests.
"""
# Equality and iequality with strings.
motorcycle = 'Ducati'
print("Is motorcycle != 'Ducati'? I predict False.")
print(motorcycle == 'ducati')
print("\nIs motorycle == 'Ducati'? I predict True.")
print(motorcycle == 'Ducati')
# Test using lower() method.
pc = 'DELL'
print("\n\nIs pc == 'dell'? I predict True.")
print(pc.lower() == 'dell')
# Check if item is in a list or not.
names = ['Anna', 'Julia', 'Rachel', 'Elizabeth']
print("\n\nCheck, if 'Samantha' is not in the list. I predict True.")
print('Samantha' not in names)
print("\nCheck, if 'Julia' is in the list. I preduct True.")
print('Julia' in names)
| true |
58ca8613f51031792f48d896a3f5c3d6a4cfc565 | ziolkowskid06/Python_Crash_Course | /ch05 - IF Statements/5-08. Hello Admin.py | 473 | 4.4375 | 4 | """
Make a list of five or more usernames, including the name'admin'.
Imagine you are writing code that will print a greeting to each user after they log in to a website and the question for admin.
"""
names = ['anna', 'elizabeth', 'julia', 'kim', 'admin', 'rachel']
for name in names:
if name == 'admin':
print('Hello admin, would you like to see a status report?')
else:
print(f"Hello {name.title()}, thank you for logging in again.")
| true |
d90c7e345eb4fe782187b003523f9caa1909447c | ziolkowskid06/Python_Crash_Course | /ch07 - User Input and WHILE Loops/7-10. Dream Vacation.py | 494 | 4.15625 | 4 | """
Write a program that polls users about their dream vacation.
"""
poll = {}
while True:
name = input("What's your name? ")
vacation = input("If you could visit one place in the world, "
"where would you go? ")
poll[name] = vacation
quit = input("Stop asking? (yes/no) ")
if quit == 'yes':
break
print("\n---- Poll Result ----")
for name, vacation in poll.items():
print(f"{name.title()} would go to {vacation.title()}.")
| true |
b9014e87d1d5167c8cdcd0f0837609b7d61e240e | ziolkowskid06/Python_Crash_Course | /ch03 - Introducing Lists/3-09. Dinner Guests.py | 319 | 4.21875 | 4 | """
Working with one of the programs from Exercises 3-4 through 3-7 (page 42),
use len() to print a message indicating the number of people you are inviting to dinner.
"""
# Print a number of elements
guest_list = ['mary jane', 'elizabeth hurtley', 'salma hayek']
print(f" There are {len(guest_list)} people invited to dinner.")
| true |
30176a4c40a0682963e4d0d9de8d27004b191ff1 | ziolkowskid06/Python_Crash_Course | /ch07 - User Input and WHILE Loops/7-02. Restaurant Seating.py | 277 | 4.21875 | 4 | """
Write a program that asks the user how many people are in their dinner group.
"""
seating = input('How many people are in your dinner group?\n')
seating = int(seating)
if seating > 8:
print("You need to wait for a table.")
else:
print("Table is ready!")
| true |
d8bf5c776f3d205b611959efb6af840f3c55d1e6 | mysqlplus163/aboutPython | /20170626/demo1.py | 366 | 4.1875 | 4 | #! /usr/bin/env python
# -*- coding: utf-8 -*-
# Python中的迭代
list1 = [1, 2, 3, 4, 5]
# index = 0
# while index < len(list1):
# print(list1[index])
# index =index + 1
# for循环
for index in range(len(list1)): # rang(3) -> 0, 1, 2
print(list1[index])
# # 区别于简单的重复
# while True:
# print("老男孩教育暑期实训")
| false |
c41f4dcd82e4b041185764f8646f5de6dc5b1ab6 | Alex-Angelico/math-series | /math_series/series.py | 1,337 | 4.3125 | 4 | def fibonacci(num):
"""
Arguments:
num - user-selected sequence value from the Fibonacci sequence to be calculated by the funciton
Returns:
Calculated value from the sequence
"""
if num <= 0:
print('Value too small.')
elif num == 1:
return 0
elif num == 2:
return 1
else:
return fibonacci(num-1) + fibonacci(num-2)
def lucas(num):
"""
Arguments:
num - user-selected sequence value from the Lucas sequence to be calculated by the funciton
Returns:
Calculated value from the sequence
"""
if num == 0:
return 2
if num == 1:
return 1
return lucas(num-1) + lucas(num-2)
def sum_series(num, x=0, y=1):
"""
Arguments:
num - user-selected sequence value from the special number sequence (e.g. Fibonacci, Lucas) to be calculated by the funciton
x - the lower bound number calculating the progression of the special number sequence
y - the upper bound number calculating the progression of the special number sequence
Returns:
Calculated value from the sequence
"""
if x == 0 and y == 1:
if num - 1 == 0:
return x
if num - 1 == 1:
return y
return sum_series(num - 1, x, y) + sum_series(num - 2, x, y)
else:
if num == 1:
return x
if num == 2:
return y
return sum_series(num - 1, x, y) + sum_series(num - 2, x, y) | true |
cddc10f2fb3571e8d55ac0bc8393f5fe1aabd2cb | Priyojeet/man_at_work | /python_100/string_manipulation1.py | 322 | 4.34375 | 4 | # Write a Python program to remove the nth index character from a nonempty string.
def remove_char(str, n):
slice1 = str[:n]
slice2 = str[n + 1:]
#print(slice1)
#print(slice2)
return slice1 + slice2
l = str(input("enter a string:-"))
no = int(input("enter a number:-"))
print(remove_char(l, no))
| true |
97a822a515d3434b42b402aebbcb5513b01334f4 | Priyojeet/man_at_work | /python_100/decision_making_nested_if_else.py | 562 | 4.125 | 4 | # check prime number with nested loop
number = eval(input("enter the number you want:-"))
if(isinstance(number,str)):
print(" please enter an integer value")
elif(type(number) == float):
print("you enter a float number")
else:
if (number <= 0):
print("enter an integer grater then 0")
elif (number == 1):
print("you have enter 1")
else:
for i in range(2, number):
if ((number % i) == 0):
print("number is not prime")
break
else:
print("number is prime") | true |
0862a345a5b5422d0e062f977015a95ef4ad3f3b | dipsuji/coding_pyhton | /coding/flatten_tree.py | 1,266 | 4.1875 | 4 | class Node:
"""
create node with lest and right attribute
"""
def __init__(self, key):
self.left = None
self.right = None
self.val = key
def print_pre_order(root):
"""
this is pre order traversal
"""
if root:
# First print the data of root
print(root.val),
# Recursion function call left tree
print_pre_order(root.left)
# Recursion function call right tree
print_pre_order(root.right)
def find(root, item):
"""
search the given element in tree
"""
if root:
# check the element if it is in root
if root.val == item:
print("Tree " + str(root.val))
if root.left is not None:
print(" Left " + str(root.left.val))
if root.right is not None:
print(" Right " + str(root.right.val))
return
# Recursion function call left tree
find(root.left, item)
# Recursion function call right tree
find(root.right, item)
tree_root = Node(1)
tree_root.left = Node(13)
tree_root.right = Node(10)
tree_root.left.left = Node(8)
tree_root.right.left = Node(1)
print("Pre order traversal:")
print_pre_order(tree_root)
find(tree_root, 1) | true |
44e6ef8dd8212448ed8684262c52fcc71da35d4e | dipsuji/coding_pyhton | /udemy_leetcode/Hash Map Facebook Interview Questions solutions/majority_element.py | 846 | 4.1875 | 4 | """
- https://leetcode.com/problems/majority-element/
Given an array nums of size n, return the majority element.
The majority element is the element that appears more than ⌊n / 2⌋ times. You may assume that the majority element always exists in the array.
Example 1:
Input: nums = [3,2,3]
Output: 3
Example 2:
Input: nums = [2,2,1,1,1,2,2]
Output: 2
"""
from typing import List
class Solution:
def majorityElement(self, nums: List[int]) -> int:
m = {}
for num in nums:
m[num] = m.get(num, 0)+1
for num in nums:
if(m[num]>len(nums)//2):
return num
num1 = [2, 11, 11, 7, 11] # list length = 5, half = 2.5, ans - element have more than 2 times.
# num1 = [2, 11, 7, 15]
s = Solution()
answer = s.majorityElement(num1)
print(answer)
| true |
0045f7f9c3c0e13656f0b5f5c815f7cb17ac13bc | dipsuji/coding_pyhton | /udemy_leetcode/Microsoft Interview Questions solutions/missing_number.py | 1,121 | 4.15625 | 4 | from typing import List
"""
Given an array nums containing n distinct numbers in the range [0, n], return the only number in the range that is
missing from the array.
Example 1:
Input: nums = [3,0,1]
Output: 2
Explanation: n = 3 since there are 3 numbers, so all numbers are in the range [0,3]. 2 is the missing number in the
range since it does not appear in nums.
Example 2:
Input: nums = [0,1]
Output: 2
Explanation: n = 2 since there are 2 numbers, so all numbers are in the range [0,2]. 2 is the missing number in the
range since it does not appear in nums.
Example 3:
Input: nums = [9,6,4,2,3,5,7,0,1]
Output: 8
Explanation: n = 9 since there are 9 numbers, so all numbers are in the range [0,9]. 8 is the missing number in the
range since it does not appear in nums.
"""
class Solution:
def missing_number(self, nums: List[int]) -> int:
currentSum = sum(nums)
n = len(nums)
intendedSum = n * (n + 1) / 2
return int(intendedSum - currentSum)
s = Solution()
answer = s.missing_number([9, 6, 4, 2, 3, 5, 7, 0, 1])
print(answer)
| true |
77e3b9062540fd72f2a1deb8f3ccf652d982ad0d | lehmanwics/programming-interview-questions | /src/general/Python/4_fibonachi_numbers.py | 1,402 | 4.28125 | 4 | """
4. Write fibonacci iteratively and recursively (bonus: use dynamic programming)
"""
# Fibonachi recursively (function calls itself)
def fib(nth_number):
if nth_number == 0:
return 0
elif nth_number == 1:
return 1
else:
return fib(nth_number-1) + fib(nth_number - 2)
# Fibonachi iteratively (use a loop)
def fib_iter(nth_number):
if nth_number == 0:
return 0
if nth_number == 1:
return 1
else:
"""
we have to keep track of the previous 2 numbers
(assuming we are in the 2nd fibonacci number)
"""
prev_previous = 0
prev = 1
result = 0
for x in range(2, nth_number+1): # range stop parameter is non-inclusive
result = prev_previous + prev
# update the previous 2 numbers
prev_previous = prev
prev = result
return result
if __name__ == '__main__':
""" create a list of the first 10 fibonacci numbers and store them in a list"""
print("Generating the first 10 fibonacci numbers iteratively and recursively")
fib_numbers = [fib(x) for x in range(1, 11)]
fib_iter_numbers = [fib_iter(x) for x in range(1,11)]
print("Recursive list of fibonacci numbers: "+str(fib_numbers))
print("Iterative list of fibonacci numbers: "+str(fib_iter_numbers))
| true |
935726112481fa8173f8e4bc7a817225d123d126 | sarma5233/pythonpract | /python/operators.py | 2,108 | 4.40625 | 4 | a = 10
b = 8
print("ARITHMETIC operators")
print('1.Addition')
print(a+b)
print()
print('2.subtraction')
print(a-b)
print('3.Multiplication')
print(a*b)
print('4.Division')
print(a/b)
print('5.Modulus')
print(a%b)
print('6.Exponentiation')
print(a**b)
print('7.floor Division')
print(a//b)
print("Comparision Operators")
print('1.Equal')
print(a == b)
print('2.Not Equal')
print(a != b)
print('3.Greater than')
print(a > b)
print('4.Lessthan')
print(a < b)
print('5.Greaterthan or Equal to')
print(a >= b)
print('6.Lessthan or Equal to')
print(a <= b)
print("Logical Operators")
print('1.AND...,Returns True if both statements are true')
print(a > 5 and a < 20)
print('2.OR...,Returns True if one of the statements is true')
print(a < 20 or a > 15)
print('3.NOT...,Reverse the result, returns False if the result is true')
print(not(a < 20 or a > 15))
print("ASSIGNMENT Operators")
import math
x = 10
print('1.=')
print(x)
print('2.+=')
x += 5
print(x)
print('3.-=')
x -= 5
print(x)
print('4.*=')
x *= 5
print(x)
print('5./=')
x /= 5
print(x)
print('6.%=')
x %= 5
print(x)
print('7.//=')
x //= 5
print(x)
print('8.**=')
x **= 5
print(x)
'''print('9.&=')
x &= 5
print(x)
print('10.|=')
x |= 5
print(x)
print('11.^=')
x ^= 5
print(x)
print('12.>>=')
x >>= 3
print(x)
print('13.<<=')
x <<= 5
print(x)'''
print("IDENTITY Operators")
M=10
N=10.35
print(id(M))
print(id(N))
print('1.IS')
print(type(M) is int)
print('2.IS NOT')
print(type(M) is not float)
print('1.IS')
print(type(N) is int)
print('2.IS NOT')
print(type(N) is float)
print("MEMBERSHIP Operators")
print('1.IN')
vowels = ['a', 'e', 'i', 'o', 'u','A', 'E', 'I', 'O', 'U']
ch = input('Please Enter a Letter:\n')
if ch in vowels:
print('You entered a vowel character')
else:
print('You entered a consonants character')
print('2.NOT IN')
primes=(2,3,5,7,11)
print(1 not in primes)
print(3 not in primes)
print("UNARY MINUS OPERATOR(-)")
s=-50
print(s)
print(-s)
print()
print("Ternary Operator")
i, j = 10, 20
# Copy value of i in min if i < j else copy j
min = i if i > j else j
print(min) | true |
8fb2558f6f9bed68720ee257727e9be5840cbe0d | sarma5233/pythonpract | /flow_controls/while.py | 210 | 4.15625 | 4 | n = int(input("enter a number:"))
sum = 0
total_numbers = 1
while total_numbers <= n:
sum += total_numbers
total_numbers += 1
print("sum =", sum)
average = sum/n
print("Average = ", average) | true |
c8ff41d4b83e1b1285f1acde17504d2236b453c6 | sarmabhamidipati/UCD | /Specialist Certificate in Data Analytics Essentials/DataCamp/04-regular_expression_in_python/e32_flying_home.py | 1,297 | 4.15625 | 4 | """
Flying home
The variable flight containing one email subject was loaded in your session. You can use print() to view it in the IPython Shell.
Import the re module.
Complete the regular expression to match and capture all the flight information required.
Only the first parenthesis were placed for you.
Find all the matches corresponding to each piece of information about the flight. Assign it to flight_matches.
Complete the format method with the elements contained in flight_matches.
In the first line print the airline,and the flight number.
In the second line, the departure and destination.
In the third line, the date.
"""
# Import re
import re
flight = "Subject: You are now ready to fly. Here you have your boarding pass IB3723 AMS-MAD 06OCT"
# Write regex to capture information of the flight
regex = r"([A-Z]{2})(\d{4})\s([A-Z]{3})-([A-Z]{3})\s(\d{2}[A-Z]{3})"
#print(re.findall(regex,flight))
# Find all matches of the flight information
flight_matches = re.findall(regex,flight)
print(flight_matches)
print(flight_matches[0][0])
#Print the matches
print("Airline: {} Flight number: {}".format(flight_matches[0][0], flight_matches[0][1]))
print("Departure: {} Destination: {}".format(flight_matches[0][2], flight_matches[0][3]))
print("Date: {}".format(flight_matches[0][4])) | true |
fa7afe7b83e2d11110183c186ed9019e7043d306 | sarmabhamidipati/UCD | /Specialist Certificate in Data Analytics Essentials/DataCamp/05-Working_with_Dates_and_Times/e22_how_many_hours_elapsed_around_daylight_saving.py | 1,348 | 4.5625 | 5 | """
How many hours elapsed around daylight saving?
Let's look at March 12, 2017, in the Eastern United States, when Daylight Saving kicked in at 2 AM.
If you create a datetime for midnight that night, and add 6 hours to it, how much time will have elapsed?
You already have a datetime called start, set for March 12, 2017 at midnight, set to the timezone 'America/New_York'.
Add six hours to start and assign it to end. Look at the UTC offset for the two results.
You added 6 hours, and got 6 AM, despite the fact that the clocks springing forward means only 5 hours
would have actually elapsed!
Calculate the time between start and end. How much time does Python think has elapsed?
Move your datetime objects into UTC and calculate the elapsed time again.
Once you're in UTC, what result do you get?
"""
# Import datetime, timedelta, tz, timezone
from datetime import datetime, timedelta, timezone
from dateutil import tz
# Start on March 12, 2017, midnight, then add 6 hours
start = datetime(2017, 3, 12, tzinfo=tz.gettz('America/New_York'))
end = start + timedelta(hours=6)
print(start.isoformat() + " to " + end.isoformat())
# How many hours have elapsed?
print((end - start).total_seconds() / (60 * 60))
# What if we move to UTC?
print((end.astimezone(timezone.utc) - start.astimezone(timezone.utc)) \
.total_seconds() / (60 * 60))
| true |
afb5a251bfa0ba326669aa7ae14f0004c54d914e | sarmabhamidipati/UCD | /Specialist Certificate in Data Analytics Essentials/DataCamp/12-Introduction_to_Deep_Learning_in_Python/e1_coding_the_forward_propagation_algorithm.py | 1,574 | 4.375 | 4 | """
Coding the forward propagation algorithm
The input data has been pre-loaded as input_data, and the weights are available in a dictionary called weights.
The array of weights for the first node in the hidden layer are in weights['node_0'], and the array of weights
for the second node in the hidden layer are in weights['node_1'].
The weights feeding into the output node are available in weights['output'].
NumPy will be pre-imported for you as np in all exercises.
Instructions
100 XP
Calculate the value in node 0 by multiplying input_data by its weights weights['node_0'] and computing their sum.
This is the 1st node in the hidden layer.
Calculate the value in node 1 using input_data and weights['node_1']. This is the 2nd node in the hidden layer.
Put the hidden layer values into an array. This has been done for you.
Generate the prediction by multiplying hidden_layer_outputs by weights['output'] and computing their sum.
Hit 'Submit Answer' to print the output!
"""
import numpy as np
input_data = np.array([3, 5])
weights = {'node_0': np.array([2, 4]), 'node_1': np.array([4, -5]), 'output': np.array([2, 7])}
# Calculate node 0 value: node_0_value
node_0_value = (input_data * weights['node_0']).sum()
# Calculate node 1 value: node_1_value
node_1_value = (input_data * weights['node_1']).sum()
# Put node values into array: hidden_layer_outputs
hidden_layer_outputs = np.array([node_0_value, node_1_value])
# Calculate output: output
output = (hidden_layer_outputs * weights['output']).sum()
# Print output
print(output)
| true |
a5437c79e37d03fd36f379c41ee2f84ea191bb79 | sarmabhamidipati/UCD | /Specialist Certificate in Data Analytics Essentials/DataCamp/02-python-data-science-toolbox-part-2/e33_writing_an_iterator_to_load_data_in_chunks3.py | 1,534 | 4.15625 | 4 | """
Writing an iterator to load data in chunks (3)
The packages pandas and matplotlib.pyplot have been imported as pd and plt respectively for your use.
Instructions
100 XP
Write a list comprehension to generate a list of values from pops_list for the new column 'Total Urban Population'.
The output expression should be the product of the first and second element in each tuple in pops_list.
Because the 2nd element is a percentage, you also need to either multiply the result by 0.01 or divide it by 100.
In addition, note that the column 'Total Urban Population' should only be able to take on integer values.
To ensure this, make sure you cast the output expression to an integer with int().
Create a scatter plot where the x-axis are values from the 'Year' column and
the y-axis are values from the 'Total Urban Population' column.
"""
import pandas as pd
import matplotlib.pyplot as plt
# Code from previous exercise
urb_pop_reader = pd.read_csv('ind_pop_data.csv', chunksize=1000)
df_urb_pop = next(urb_pop_reader)
df_pop_ceb = df_urb_pop[df_urb_pop['CountryCode'] == 'CEB']
pops = zip(df_pop_ceb['Total Population'],
df_pop_ceb['Urban population (% of total)'])
pops_list = list(pops)
print(pops_list)
# Use list comprehension to create new DataFrame column 'Total Urban Population'
df_pop_ceb['Total Urban Population'] = [int(tup[0] * tup[1] * 0.01) for tup in pops_list]
# Plot urban population data
df_pop_ceb.plot(kind='scatter', x='Year', y='Total Urban Population')
plt.show()
| true |
c1a72827d922ed8468dd66d50a7c0d2d4c897ce8 | sarmabhamidipati/UCD | /Specialist Certificate in Data Analytics Essentials/DataCamp/02-python-data-science-toolbox-part-2/e18_list_comprehensions_vs_generators.py | 1,679 | 4.5 | 4 | """
List comprehensions vs generators
generators does not store data in memnory like list
if there a very large list then use generators.
There is no point in using large list instead use generators
In this exercise, you will recall the difference between list comprehensions and generators. To help with that task,
the following code has been pre-loaded in the environment:
# List of strings
fellowship = ['frodo', 'samwise', 'merry', 'aragorn', 'legolas', 'boromir', 'gimli']
# List comprehension
fellow1 = [member for member in fellowship if len(member) >= 7]
# Generator expression
fellow2 = (member for member in fellowship if len(member) >= 7)
Try to play around with fellow1 and fellow2 by figuring out their types and printing out their values. Based on your
observations and what you can recall from the video, select from the options below the best description for the
difference between list comprehensions and generators.
Instructions
Possible Answers
1.List comprehensions and generators are not different at all; they are just different ways of
writing the same thing.
2.A list comprehension produces a list as output, a generator produces a generator object.
3.A list comprehension produces a list as output that can be iterated over, a generator produces a generator object
that can't be iterated over.
Answer : 2
"""
# List of strings
fellowship = ['frodo', 'samwise', 'merry', 'aragorn', 'legolas', 'boromir', 'gimli']
# List comprehension
fellow1 = [member for member in fellowship if len(member) >= 7]
# Generator expression
fellow2 = (member for member in fellowship if len(member) >= 7)
print(fellow1)
print(fellow2) | true |
7278153d5148595cd0bc4cfb92ccef72cd4706c7 | sarmabhamidipati/UCD | /Specialist Certificate in Data Analytics Essentials/DataCamp/10-Supervised_Learning_with_scikit-learn/e28_centering_and_scaling_your_data.py | 1,912 | 4.28125 | 4 | """
Centering and scaling your data
You will now explore scaling for yourself on a new dataset - White Wine Quality! Hugo used the Red Wine Quality
dataset in the video. We have used the 'quality' feature of the wine to create a binary target variable: If 'quality'
is less than 5, the target variable is 1, and otherwise, it is 0.
The DataFrame has been pre-loaded as df, along with the feature and target variable arrays X and y.
Explore it in the IPython Shell. Notice how some features seem to have different units of measurement.
'density', for instance, takes values between 0.98 and 1.04, while 'total sulfur dioxide' ranges from 9 to 440.
As a result, it may be worth scaling the features here. Your job in this exercise is to scale the features and
compute the mean and standard deviation of the unscaled features compared to the scaled features.
Instructions
Import scale from sklearn.preprocessing.
Scale the features X using scale().
Print the mean and standard deviation of the unscaled features X, and then the scaled features X_scaled.
Use the numpy functions np.mean() and np.std() to compute the mean and standard deviations.
"""
import pandas as pd
import numpy as np
# Import scale
from sklearn.preprocessing import scale
df = pd.read_csv('white-wine.csv')
X = df.drop('quality', axis=1).values
# if quality less than 5 then True else False
y = df['quality'].apply(lambda x: 'True' if x < 5 else 'False').to_numpy()
# Scale the features: X_scaled
X_scaled = scale(X)
# Print the mean and standard deviation of the unscaled features
print("Mean of Unscaled Features: {}".format(np.mean(X)))
print("Standard Deviation of Unscaled Features: {}".format(np.std(X)))
# Print the mean and standard deviation of the scaled features
print("Mean of Scaled Features: {}".format(np.mean(X_scaled)))
print("Standard Deviation of Scaled Features: {}".format(np.std(X_scaled)))
| true |
246c365f2c3f7f10c249933ead07532244770291 | sarmabhamidipati/UCD | /Specialist Certificate in Data Analytics Essentials/DataCamp/03-cleaning_data_in_python/e36_pairs_of_restaurants.py | 1,325 | 4.125 | 4 | """
in this exercise, you will perform the first step in record linkage and generate possible pairs of rows between
restaurants and restaurants_new. Both DataFrames, pandas and recordlinkage are in your environment.
Instructions
Instantiate an indexing object by using the Index() function from recordlinkage.
Block your pairing on cuisine_type by using indexer's' .block() method.
Generate pairs by indexing restaurants and restaurants_new in that order.
Now that you've generated your pairs, you've achieved the first step of record linkage.
What are the steps remaining to link both restaurants DataFrames, and in what order?
"""
import pandas as pd
import recordlinkage
restaurants = pd.read_csv('restaurant.csv')
restaurants_new = pd.read_csv('restaurant_new.csv')
# Create an indexer and object and find possible pairs
indexer = recordlinkage.Index()
# Block pairing on cuisine_type
indexer.block('cuisine_type')
# Generate pairs
pairs = indexer.index(restaurants, restaurants_new)
print(pairs)
"""
Possible Answers
A.Compare between columns, score the comparison, then link the DataFrames.
B.Clean the data, compare between columns, link the DataFrames, then score the comparison.
C.Clean the data, compare between columns, score the comparison, then link the DataFrames.
Answer A
"""
| true |
5b718cdb7f238284afaa3e3a5080213062c4bf15 | sarmabhamidipati/UCD | /Specialist Certificate in Data Analytics Essentials/DataCamp/04-regular_expression_in_python/e3_palindromes.py | 782 | 4.28125 | 4 | """
The text of a movie review for one example has been already saved in the variable movie.
You can use print(movie) to view the variable in the IPython Shell.
Instructions
100 XP
Extract the substring from the 12th to the 30th character from the variable movie which corresponds
to the movie title. Store it in the variable movie_title.
Get the palindrome by reversing the string contained in movie_title.
Complete the code to print out the movie_title if it is a palindrome.
"""
movie = "oh my God! desserts I stressed was an ugly movie"
# Get the word
movie_title = movie[11:30]
print(movie_title)
# Obtain the palindrome
palindrome = movie_title[::-1]
print(palindrome)
# Print the word if it's a palindrome
if movie_title == palindrome:
print(movie_title) | true |
d4cf7f2383afe7107d2218d684df69e3f9e4c9e8 | sarmabhamidipati/UCD | /Specialist Certificate in Data Analytics Essentials/DataCamp/05-Working_with_Dates_and_Times/e16_the_long_and_the_short_of_why_time_is_hard.py | 1,779 | 4.46875 | 4 | """
The long and the short of why time is hard
As before, data has been loaded as onebike_durations.
Calculate shortest_trip from onebike_durations.
Calculate longest_trip from onebike_durations.
Print the results, turning shortest_trip and longest_trip into strings so they can print.
"""
from datetime import datetime, timedelta
onebike_datetimes = [
{'start': datetime(2017, 10, 1, 15, 23, 25), 'end': datetime(2017, 10, 1, 15, 26, 26)},
{'start': datetime(2017, 10, 1, 15, 42, 57), 'end': datetime(2017, 10, 1, 17, 49, 59)},
{'start': datetime(2017, 10, 2, 6, 37, 10), 'end': datetime(2017, 10, 2, 6, 42, 53)},
{'start': datetime(2017, 10, 2, 8, 56, 45), 'end': datetime(2017, 10, 2, 9, 18, 3)}]
# Initialize a list for all the trip durations
onebike_durations = []
for trip in onebike_datetimes:
#print(trip)
# Create a timedelta object corresponding to the length of the trip
trip_duration = trip['end'] - trip['start']
print(trip_duration)
# Get the total elapsed seconds in trip_duration
trip_length_seconds = trip_duration.total_seconds()
# Append the results to our list
onebike_durations.append(trip_length_seconds)
# What was the total duration of all trips?
total_elapsed_time = sum(onebike_durations)
print(total_elapsed_time)
# What was the total number of trips?
number_of_trips = len(onebike_durations)
print(number_of_trips)
# Divide the total duration by the number of trips
print(total_elapsed_time / number_of_trips)
# Calculate shortest and longest trips
shortest_trip = min(onebike_durations)
longest_trip = max(onebike_durations)
# Print out the results
print("The shortest trip was " + str(shortest_trip) + " seconds")
print("The longest trip was " + str(longest_trip) + " seconds") | true |
9aa4a68742400f5dff59647d53bfb1e0e7d91a14 | sarmabhamidipati/UCD | /Specialist Certificate in Data Analytics Essentials/DataCamp/07-Exploratory_Data_Analysis_in_Python/e32_making_predictions.py | 1,169 | 4.21875 | 4 | """
Making predictions
At this point, we have a model that predicts income using age, education, and sex.
Let's see what it predicts for different levels of education, holding age constant.
Using np.linspace(), add a variable named 'educ' to df with a range of values from 0 to 20.
Add a variable named 'age' with the constant value 30.
Use df to generate predicted income as a function of education.
"""
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from scipy import stats
from empiricaldist import Pmf
from scipy.stats import norm
from scipy.stats import linregress
import seaborn as sns
import statsmodels.formula.api as smf
gss = pd.read_hdf('gss.hdf5', 'gss')
# Add a new column with educ squared
gss['educ2'] = gss['educ'] ** 2
gss['age2'] = gss['age'] ** 2
# Run a regression model with educ, educ2, age, and age2
results = smf.ols('realinc ~ educ + educ2 + age + age2', data=gss).fit()
# Make the DataFrame
df = pd.DataFrame()
df['educ'] = np.linspace(0, 20)
df['age'] = 30
df['educ2'] = df['educ'] ** 2
df['age2'] = df['age'] ** 2
# Generate and plot the predictions
pred = results.predict(df)
print(pred.head())
| true |
7e486404b32bb6b34085ee5fc263fbb2437cd3b6 | sarmabhamidipati/UCD | /Specialist Certificate in Data Analytics Essentials/DataCamp/09-Statistical_Thinking_in_Python_Part2/e7_linear_regression_on_appropriate_anscombe_data.py | 1,403 | 4.125 | 4 | """
Linear regression on appropriate Anscombe data
Compute the parameters for the slope and intercept using np.polyfit().
The Anscombe data are stored in the arrays x and y. Print the slope a and intercept b.
Generate theoretical
and data from the linear regression. Your array, which you can create with np.array(), should consist of 3 and 15.
To generate the data, multiply the slope by x_theor and add the intercept.
Plot the Anscombe data as a scatter plot and then plot the theoretical line.
Remember to include the marker='.' and linestyle='none' keyword arguments in addition to x and y
when to plot the Anscombe data as a scatter plot. You do not need these arguments when plotting the theoretical line.
Hit 'Submit Answer' to see the plot!
"""
import numpy as np
import matplotlib.pyplot as plt
# Perform linear regression: a, b
x = np.array([10., 8., 13., 9., 11., 14., 6., 4., 12., 7., 5.])
y = np.array([8.04, 6.95, 7.58, 8.81, 8.33, 9.96, 7.24, 4.26, 10.84, 4.82, 5.68])
a, b = np.polyfit(x, y, 1)
# Print the slope and intercept
print(a, b)
# Generate theoretical x and y data: x_theor, y_theor
x_theor = np.array([3, 15])
y_theor = a * x_theor + b
# Plot the Anscombe data and theoretical line
_ = plt.plot(x, y, marker='.', linestyle='none')
_ = plt.plot(x_theor, y_theor, marker='.', linestyle='none')
# Label the axes
plt.xlabel('x')
plt.ylabel('y')
# Show the plot
plt.show()
| true |
dab0d9344df34e3f0730c2b87683c050d701e011 | sarmabhamidipati/UCD | /Specialist Certificate in Data Analytics Essentials/DataCamp/04-regular_expression_in_python/e2_artificial_reviews.py | 1,271 | 4.15625 | 4 | """
The text of two movie reviews has been already saved in the variables movie1 and movie2.
You can use the print() function to view the variables in the IPython Shell.
Remember: The 1st character of a string has index 0.
Instructions
Select the first 32 characters of the variable movie1 and assign it to the variable first_part.
Select the substring going from the 43rd character to the end of movie1. Assign it to the variable last_part.
Select the substring going from the 33rd to the 42nd character of movie2. Assign it to the variable middle_part.
Print the concatenation of the variables first_part, middle_part and last_part in that order.
Print the variable movie2 and compare them.
"""
movie1 = "the most significant tension of _election_ is the potential relationship between a teacher and his student ."
movie2 = "the most significant tension of _rushmore_ is the potential relationship between a teacher and his student ."
first_part = movie1[:32]
print(first_part)
# Select from 43rd character to the end of movie1
last_part = movie1[42:]
print(last_part)
# Select from 33rd to the 42nd character of movie2
middle_part = movie2[32:42]
print(middle_part)
# Print concatenation and movie2 variable
print(first_part+middle_part+last_part)
print(movie2) | true |
b6eb4dde3b6ef947df4922a52e971102397f01e9 | sarmabhamidipati/UCD | /Specialist Certificate in Data Analytics Essentials/DataCamp/07-Exploratory_Data_Analysis_in_Python/e7_compute_birth_weight.py | 818 | 4.3125 | 4 | """
Compute birth weight
Make a Boolean Series called full_term that is true for babies with 'prglngth' greater than or equal to 37 weeks.
Use full_term and birth_weight to select birth weight in pounds for full-term babies.
Store the result in full_term_weight.
Compute the mean weight of full-term babies.
"""
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
pd.options.display.max_columns = None
nsfg = pd.read_hdf('nsfg.hdf5', 'nsfg')
agecon = nsfg["agecon"]/100
# Plot the histogram
plt.hist(agecon, bins=20, histtype='step')
# Create a Boolean Series for full-term babies
full_term = nsfg['prglngth'] >= 37
# Select the weights of full-term babies
full_term_weight = birth_weight[full_term]
# Compute the mean weight of full-term babies
print(full_term_weight.mean()) | true |
fef3d8a8eb810bfeebd65a7951b14f2f55c514c8 | DiniH1/python_concatenation_task | /python_concactination_task.py | 507 | 4.21875 | 4 |
# Task 1
name = ""
name = input("What is your name? ")
name_capitalize = name.capitalize()
print(name_capitalize + " Welcome to this task!")
# Task 2
full_name = ""
full_name = input('What is your full name? ')
first_name = (full_name.split()[0])
first_name_capitalize = first_name.capitalize()
last_name = (full_name.split()[1])
last_name_capitalize = last_name.capitalize()
full_name_capitalize = first_name_capitalize + " " + last_name_capitalize
print(full_name_capitalize + " Welcome to this task!")
| true |
2ae3f62714952207aaf401db24a148f92a9871d1 | AtxTom/Election_Analysis | /PyPoll.py | 1,017 | 4.125 | 4 | # The data we need to retrieve.
# 1. The total number of votes cast
# 2. A complete list of candidates who received votes
# 3. The percentage of votes each candidate won
# 4. The total number of votes each candidate won
# 5. The winner of the election based on popular vote.
# Add our dependencies.
import csv
import os
# Add a variable to load a file from a path.
file_to_load = os.path.join("Resources/election_results.csv")
# Add a variable to save the file to a path.
file_to_save = os.path.join("analysis", "election_analysis.txt")
# 1. Initialize a total vote counter.
total_votes = 0
# Open the election results and read the file
with open(file_to_load) as election_data:
print(election_data)
# file_reader = csv.reader(election_data)
# # Read the header row.
# headers = (next(file_reader))
# # Print each row in the CSV file.
# for row in election_data:
# # 2. Add to the total vote count.
# total_votes += 1
# # 3. Print the total votes.
# print(total_votes)
| true |
fceebe8dfa503b1bfe1925f59e1a06c7f14a3851 | lengfc09/Financial_Models | /NLP/Codes/code-sklearn-k-means-clustering.py | 792 | 4.3125 | 4 | # This script illustrates how to use k-means clustering in
# SciKit-Learn.
from sklearn.cluster import KMeans
import numpy as np
# We create a numpy array with some data. Each row corresponds to an
# observation.
X = \
np.array(
[[1, 2],
[1, 4],
[1, 0],
[10, 2],
[10, 4],
[10, 0]])
# Perform k-means clustering of the data into two clusters.
kmeans = KMeans(n_clusters=2, random_state=0).fit(X)
# Show the labels, i.e. for each observation indicate the group
# membership.
kmeans.labels_
# Ifyou have two new observations (i.e. previously unseen by the
# algorithm), to which group would they be assigned?
kmeans.predict(
[[0, 0],
[12, 3]])
# Show the centers of the clusters as determined by k-means.
kmeans.cluster_centers_
| true |
ac7d5491c2ed052cbc296be4e0b00ea7f4a7554c | Asana-sama/Learn5 | /Task1.py | 799 | 4.1875 | 4 | # Создать программно файл в текстовом формате, записать в него построчно данные,
# вводимые пользователем. Об окончании ввода данных свидетельствует пустая строка.
def file_input(name="task1.txt"):
file = open(name, "w")
input_string = input("Введите строку:")
while (input_string != ""):
file.write(input_string + "\n")
input_string = input("Введите следующую строку:")
file.close()
pass
def main():
filename = input("Введите имя файла:")
if filename != "":
file_input(filename)
else:
file_input()
pass
if __name__ == "__main__":
main() | false |
302334f9a7cd8ac3ae4ff61777bc7926899baca4 | sanraj99/practice_python | /prime_number.py | 509 | 4.15625 | 4 | # A Prime number can only divided by 1 and itself
def is_prime(num):
for i in range(2, num):
if (num % i) == 0:
return False
return True
def getPrimes(max_number):
list_of_primes = []
for num1 in range(2, max_number):
if is_prime(num1):
list_of_primes.append(num1)
return list_of_primes
max_num_to_check = int(input("Search for Primes up to : "))
list_of_prime = getPrimes(max_num_to_check)
for prime in list_of_prime:
print(prime) | true |
4f97b96ca9683d7dea5defd2201e10d4408b169b | sourav-gomes/Python | /Part - I/Chapter 3 - Strings/03_string_functions.py | 854 | 4.28125 | 4 | story = "once upon a time there was a boy named Joseph who was good but very lazy fellow and never completed any job"
# String Functions
# print(len(story)) # gives length of the string
# print(story.endswith("job")) # returns True or false. In this case True.
# print(story.count("a")) # returns how many times a character 'a' has occurred
# print(story.count("was")) # returns how many times a string 'was' has occurred, in this case 2
# print(story.capitalize()) # Capitalizes first word of the string
print(story.find("was")) # Finds the first occurrence of the word in the string (only first) and returns their position
# print(story.replace("was", "WOULD BE")) # Finds & replaces old word with new in the string (all occurrences)
year = '1700'
print(int(year[:2])+1)
print(year[2:])
print(int(float('1.07'))) | true |
b79a137c9f02c076e43d751bbaec2b0ede6f6603 | sourav-gomes/Python | /Part - I/Chapter 5 - Dictionary & Sets/03_Sets_in_python_and methods.py | 1,726 | 4.375 | 4 | '''
a = (1, 2, 3) # () means --> tuple
print(type(a)) # prints type --> <class 'tuple'>
a = [1, 2, 3] # [] means --> list
print(type(a)) # prints type --> <class 'list'>
a = {1, 2, 3} # {x, y,....} means --> set
print(type(a)) # prints type --> <class 'set'>
a = {1:3} # {x:y} means --> dictionary
print(type(a)) # prints type --> <class 'dict'>
a = {}
print(type(a)) # Important this syntax will create an empty dictionary, NOT an empty set
# To create an empty set you use the following command
b = set()
print(type(b))
# Methods in Sets
b.add(4) # add() to add value to the set
b.add(10)
# An object is hashable if it has a hash value that DOES NOT change during its entire lifetime
# b.add([1,3,6]) # cannot add a list to a set since a list is not hashable
# b.add((1,3,6)) # But you can add a tuple to a set
# b.add({5:8}) # cannot add a list to a set since a dictionar is not hashable
# Only HASHABLE datatypes can exist inside a set
print(b)
s = {1,4,4,1,6,1,6}
print(s) # will print only {1, 4, 6} since a set can have only unique values
print(len(s)) # prints length of set, in this case 3
s.remove(6) # removes 6 from the above set of {1, 4, 6}
# s.remove(5) # Throws error as 5 is not an element of the set above set of {1, 4, 6}
print(s)
print(s.pop()) # Randomly removed a value from the set and returns the remaining
print(s.clear()) # Clears/Empties the set and returns None
'''
set1 = {2, 5, 6, 8}
set2 = {6, 3, 0, 1}
print(set1.union(set2)) # Eg. of set1 & set2 union
print(set1.intersection(set2)) # Eg. of set1 & set2 intersection (only 6 is common)
| true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.