blob_id
string | repo_name
string | path
string | length_bytes
int64 | score
float64 | int_score
int64 | text
string | is_english
bool |
|---|---|---|---|---|---|---|---|
efa5b93f22db52d9dfe98f8a95f3c8da4866aa24
|
VictorSHJ/fundamentos-python
|
/palindroma.py
| 1,116
| 4.125
| 4
|
# GRUPO 2:
# Crea una funcion que dado una palabra diga si es palindroma o no.
def palindroma(palabra):
print(f"Palabra Normal: {palabra}, Palabra Invertida: {palabra[::-1]}")
if palabra == palabra[::-1]:
print("Es palindroma")
else:
print("No es palindroma")
print("Ingrese una palabra :")
palabra=input()
palindroma(palabra)
palabra="CursodePython"
print(palabra[0:3])
print(palabra[2:5])
# OTRO:
# - Crea una función que tome una lista y devuelva el primer y el último valor de la lista.
# Si la longitud de la lista es menor que 2, haga que devuelva False.
def recorrerlista(lista):
if len(lista)<2:
return False
else:
print(lista[0])
print(lista[len(lista)-1])
print(recorrerlista([7]))
print(recorrerlista([7,2,4,6,8]))
# - Crea una función que tome una lista y devuelva un diccionario con su mínimo, máximo, promedio y suma.
def devuelvedic(lista):
dic={"Minimo":min(lista),"Maximo":max(lista),"Promedio":sum(lista)/len(lista),"Suma":sum(lista)}
return dic
lista=[1,21,3,44,-15,6]
print("Diccionario:", devuelvedic(lista))
| false
|
20bb2a14fbb695fa1d1868147e8e2afc147cecc3
|
fatychang/pyimageresearch_examples
|
/ch10 Neural Network Basics/perceptron_example.py
| 1,157
| 4.25
| 4
|
# -*- coding: utf-8 -*-
"""
Created on Mon Dec 9 12:56:47 2019
This is an example for runing percenptron structure to predict bitwise dataset
You may use AND, OR and XOR in as the dataset.
A preceptron class is called in this example.
An example from book deep learning for computer vision with Python ch10
@author: fatyc
"""
from perceptron import Perceptron
import numpy as np
# construct the dataset
dataset_OR = np.asanyarray([[0, 0, 0], [0, 1, 1], [1, 0, 1], [1, 1, 1]])
dataset_AND = np.asanyarray([[0, 0, 0], [0, 1, 0], [1, 0, 0], [1, 1, 1]])
dataset_XOR = np.asanyarray([[0, 0, 0], [0, 1, 1], [1, 0, 1], [1, 1, 0]])
# extract the input and output
dataset = dataset_XOR
x = dataset[:,0:2]
y = dataset[:,-1]
# define the preceptron
print("[INFO] training preceptron...")
p = Perceptron(x.shape[1], alpha = 0.1)
p.fit(x, y, epochs=20)
# test the preceptron
print("[INFO] testing preceptron...")
# loop over the data point
for(x, target) in zip(x, y):
# make the prediction on the data point
pred = p.predict(x)
# print out the result
print("[INFO] data={}, ground-trut={}, pred={}".format(
x, target, pred))
| true
|
847ace6bebef81ef053d6a0268fa54e36072dd72
|
chenshaobin/python_100
|
/ex2.py
| 1,113
| 4.1875
| 4
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
# Write a program which can compute the factorial of a given numbers.
# The results should be printed in a comma-separated sequence on a single line.Suppose the following input is supplied to the program: 8 Then, the output should be:40320
"""
# 使用while
"""
n = int(input())
fact = 1
i = 1
while i <= n:
fact = fact * i
i = i + 1
print(fact)
print("------")
"""
# 使用for
"""
n = int(input())
fact = 1
for i in range(1, n+1):
fact = fact * i
print(fact)
print("------")
"""
# 使用 Lambda函数
"""
n = int(input())
def shortFact(x): return 1 if x <= 1 else x * shortFact(x)
print(shortFact(n))
"""
# solution 4
"""
while True:
try:
num = int(input("Please enter a number:"))
break
except ValueError as err:
print(err)
n = num
fact = 1
while num:
fact = num * fact
num = num - 1
print(f'the factorial of {n} is {fact}')
"""
# solution 5
from functools import reduce
def fuc(acc, item):
return acc * item
num = int(input("Please enter one number:"))
print(reduce(fuc, range(1, num + 1), 1))
| true
|
baa5ff5f08103e624b90c7a754f0f5cc60429f0e
|
chenshaobin/python_100
|
/ex9.py
| 581
| 4.15625
| 4
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
# Write a program that accepts sequence of lines as input
# and prints the lines after making all characters in the sentence capitalized.
"""
# solution1
"""
lst = []
while True:
x = input("Please enter one word:")
if len(x) == 0:
break
lst.append(x.upper())
for line in lst:
print(line)
"""
# solution2
def userInput():
while True:
s = input("Please enter one word:")
if not s:
return
yield s
for line in map(lambda x: x.upper(), userInput()):
print(line)
| true
|
eaeed21766f75657270303ddac34c8dcae8f4f01
|
Scientific-Computing-at-Temple-Physics/prime-number-finder-gt8mar
|
/Forst_prime.py
| 605
| 4.375
| 4
|
# Marcus Forst
# Scientific Computing I
# Prime Number Selector
# This function prints all of the prime numbers between two entered values.
import math as ma
# These functions ask for the number range, and assign them to 'x1' and 'x2'
x1 = int(input('smallest number to check: '))
x2 = int(input('largest number to check: '))
print ('The Prime numbers between', x1, 'and', x2, 'are:')
for i in range(x1, x2+1):
if i<=0:
continue
if i==1:
continue
for j in range (2, int(ma.sqrt(i))+1):
if i%j == 0:
break
else:
print (i)
#print ('There are no Prime numbers between', x1, 'and', x2, '.')
| true
|
4845e44fa0afcea9f4293f45778f6b4ea0da52b0
|
jamiegowing/jamiesprojects
|
/character.py
| 402
| 4.28125
| 4
|
print("Create your character")
name = input("what is your character's name")
age = int(input("how old is your character"))
strengths = input("what are your character's strengths")
weaknesses = input("what are your character's weaknesses")
print(f"""You'r charicters name is {name}
Your charicter is {age} years old
strengths:{strengths}
weaknesses:{weaknesses}
{name}says,'thanks for creating me.'
""")
| true
|
142ecec208f83818157ce4c8dff7495892e5d5d2
|
yagizhan/project-euler
|
/python/problem_9.py
| 450
| 4.15625
| 4
|
# A Pythagorean triplet is a set of three natural numbers, a < b < c, for which,
# a2 + b2 = c2
# For example, 32 + 42 = 9 + 16 = 25 = 52.
# There exists exactly one Pythagorean triplet for which a + b + c = 1000.
# Find the product abc.
def abc():
for c in range(1, 1000):
for b in range(1, c):
for a in range(1, b):
if(a*a + b*b == c*c and a + b + c == 1000):
return(a*b*c)
print(abc())
| true
|
7d45513f6cb612b73473be6dcefaf0d2646bc629
|
AlvisonHunterArnuero/EinstiegPythonProgrammierung-
|
/decorators.py
| 1,146
| 4.96875
| 5
|
# INTRODUCTION TO BASIC DECORATORS USING PYTHON 3
# Decorators provide a way to modify functions using other functions.
# This is ideal when you need to extend the functionality of functions
# that you don't want to modify. Let's take a look at this example:
# Made with ❤️ in Python 3 by Alvison Hunter - June 15th, 2021
# Website: https://alvisonhunter.com/
def my_decorator(func, caption):
LINE = "━"
TOP_LEFT = "┏"
TOP_RIGHT = "┓"
BOTTOM_LEFT = "┗"
BOTTOM_RIGHT = "┛"
# This will be the wrapper for the function passed as params [func]
# Additionally, We will use the caption param to feed the text on the box
def box():
print(f"{TOP_LEFT}{LINE*(len(caption)+2)}{TOP_RIGHT}")
func(caption)
print(f"{BOTTOM_LEFT}{LINE*(len(caption)+2)}{BOTTOM_RIGHT}")
return box
# This is the function that we will pass to the decorator
# This will receive a param msg containing the text for the box
def boxed_header(msg):
vline = "┃"
title = msg.center(len(msg)+2, ' ')
print(f"{vline}{title}{vline}")
decorated = my_decorator(boxed_header, "I bloody love Python")
decorated()
| true
|
ef45a2be2134cdf0754d5f41a9245f4a242fdb0e
|
AlvisonHunterArnuero/EinstiegPythonProgrammierung-
|
/updating_dicts_lst.py
| 1,327
| 4.40625
| 4
|
# -------------------------------------------------------------------------
# Basic operations with colletion types | Python exercises | Beginner level
# Generate list with random elements, find the first odd number and its index
# Create empty dict, fill up an empty list with user input & update dictionary
# Made with ❤️ in Python 3 by Alvison Hunter Arnuero - May 30th, 2021
# JavaScript, Python and Web Development tips at: https://bit.ly/3p9hpqj
# -------------------------------------------------------------------------
import random
# lista aleatoria
lst = []
name_lst = []
empty_dict = {}
# llenar lista aleatoria
for el in range(10):
lst.append(random.randrange(10))
# mostrar la lista genarada
print(lst)
# encontrar el primer numero impar
for ind, num in enumerate(lst):
if num % 2 == 0:
pass
else:
print(f"El número {num} es impar y esta en la posicion {ind}.")
break
# llenar lista vacia de nombres con user input
amnt = int(input("Escriba Cuantos nombres ingresaras? \n"))
[name_lst.append(
input(f"Escriba Nombre #{elem+1}: ").title()) for elem in range(amnt)]
# llenar diccionario vacio con datos de la lista llenada
for indx, name in enumerate(name_lst):
empty_dict[str(indx+1)] = name_lst[indx]
# Imprimimos dictionary ya con los datos listos
print(f"{empty_dict}")
| false
|
a2a6348689cab9d87349099ae927cecad07ade1a
|
AlvisonHunterArnuero/EinstiegPythonProgrammierung-
|
/intro_to_classes_employee.py
| 1,839
| 4.65625
| 5
|
# --------------------------------------------------------------------------------
# Introduction to classes using getters & setters with an employee details example.
# Made with ❤️ in Python 3 by Alvison Hunter - March 16th, 2021
# JavaScript, Python and Web Development tips at: https://bit.ly/3p9hpqj
# --------------------------------------------------------------------------------
class Employee:
# Constructor and Class Attributes
def __init__(self, first, last, title, department):
self.first = first
self.last = last
self.title = title
self.department = department
self.email = first.lower()+"."+last.lower()+"@email.com"
# REGULAR METHODS
def display_divider(self, arg_char = "-", line_length=100):
print(arg_char*line_length)
def display_information(self):
self.display_divider("-",45)
print(f"Employee Information | {self.first} {self.last}".center(45, ' '))
self.display_divider("-",45)
print(f"Title: {self.title} | Department: {self.department}")
print(f"Email Address: {self.email}")
print("\n")
# GETTERS
@property
def fullname(self):
print(f"{self.first} {self.last}")
# SETTERS
@fullname.setter
def fullname(self,name):
first, last = name.split(" ")
self.first = first
self.last = last
self.email = first.lower()+"."+last.lower()+"@email.com"
# DELETERS
@fullname.deleter
def fullname(self):
print("Name & Last name has been successfully deleted.")
self.first = None
self.last = None
# CREATE INSTANCES NOW
employee_01 = Employee("Alvison","Hunter","Web Developer","Tiger Team")
employee_01.display_information()
employee_01.fullname = "Lucas Arnuero"
employee_01.display_information()
del employee_01.fullname
| true
|
a1f5c161202227c1c43886a0efac0c18be4b2894
|
AlvisonHunterArnuero/EinstiegPythonProgrammierung-
|
/population_growth.py
| 1,199
| 4.375
| 4
|
# In a small town the population is p0 = 1000 at the beginning of a year.
# The population regularly increases by 2 percent per year and moreover
# 50 new inhabitants per year come to live in the town. How many years
# does the town need to see its population greater or equal to p = 1200 inhabitants?
# -------------------------------------------------------
# At the end of the first year there will be:
# 1000 + 1000 * 0.02 + 50 => 1070 inhabitants
# At the end of the 2nd year there will be:
# 1070 + 1070 * 0.02 + 50 => 1141 inhabitants (number of inhabitants is an integer)
# At the end of the 3rd year there will be:
# 1141 + 1141 * 0.02 + 50 => 1213
# It will need 3 entire years.
# Note:
# Don't forget to convert the percent parameter as a percentage in the body
# of your function: if the parameter percent is 2 you have to convert it to 0.02.
# Made with ❤️ in Python 3 by Alvison Hunter - January 27th, 2021
# Website: https://alvisonhunter.com/
def nb_year(p0, percent, aug, p):
growth = (p0 + 1000) * percent
return(growth)
# Examples:
print(nb_year(1000, 5, 100, 5000)) # -> 15
print(nb_year(1500, 5, 100, 5000))# -> 15
print(nb_year(1500000, 2.5, 10000, 2000000)) # -> 10
| true
|
fd287a7a3dad56ef140e053eba439de50cdfd9b6
|
AlvisonHunterArnuero/EinstiegPythonProgrammierung-
|
/dice.py
| 983
| 4.40625
| 4
|
#First, you only need the random function to get the results you need :)
import random
#Let us start by getting the response from the user to begin
repeat = input('Would you like to roll the dice [y/n]?\n')
#As long as the user keeps saying yes, we will keep the loop
while repeat != 'n':
# How many dices does the user wants to roll, 2 ,3 ,4 ,5 who knows. let's ask!
amount = int(input('How many dices would you like to roll? \n'))
# Now let's roll each of those dices and get their results printed on the screen
for i in range(0, amount):
diceValue = random.randint(1, 6)
print(f"Dice {i+1} got a [{diceValue}] on this turn.")
#Now, let's confirm if the user still wants to continue playing.
repeat = input('\nWould you like to roll the dice [y/n]?\n')
# Now that the user quit the game, let' say thank you for playing
print('Thank you for playing this game, come back soon!')
# Happy Python Coding, buddy! I hope this answers your question.
| true
|
d94493c20365c14ac8393ed9384ec6013cf553d4
|
AlvisonHunterArnuero/EinstiegPythonProgrammierung-
|
/interest_calc.py
| 2,781
| 4.1875
| 4
|
# Ok, Let's Suppose you have $100, which you can invest with a 10% return each year.
#After one year, it's 100×1.1=110 dollars, and after two years it's 100×1.1×1.1=121.
#Add code to calculate how much money you end up with after 7 years, and print the result.
# Made with ❤️ in Python 3 by Alvison Hunter - September 4th, 2020
# note: this can also be simply done by doing the following: print(100 * 1.1 ** 7)
import sys
def user_input(args_lbl_caption, args_input_caption):
"""This function sets a Label above an input and returns the captured value."""
try:
print(args_lbl_caption.upper())
res = int(input(args_input_caption+": \n"))
return res
except ValueError:
sys.exit("Oops! That was no valid number. Try again...")
exit
def calculate_investment():
"""This function calculates the yearly earnings based on user input from cust_input function."""
#this tuple will contain all of my captions for the user input function that I am using on this routine
input_captions_tuple = (
"Initial Investment:",
"Amount of money that you have available to invest initially",
"Estimated Interest Rate:",
"Your estimated annual interest rate[10,15,20 etc]",
"Length of Time in Years:",
"Length of time, in years that you are planning to invest"
)
#This will serve as an accumulator to store the interest per year
acc_interest = 0
#let's get the information using a called function to get and validate this data
initial_investment=user_input(input_captions_tuple[0],input_captions_tuple[1])
interest_rate_per_year=user_input(input_captions_tuple[2],input_captions_tuple[3])
length_of_time_in_years=user_input(input_captions_tuple[4],input_captions_tuple[5])
# if the called function returns an empty object or value, we will inform about this error & exit this out
if initial_investment == None or interest_rate_per_year == None or length_of_time_in_years == None:
sys.exit("These values should be numbers: You entered invalid characters!")
#If everything goes well with the user input, let us proceed to make this calculation
for year in range(length_of_time_in_years):
acc_interest = initial_investment *(interest_rate_per_year/100)
initial_investment = initial_investment + acc_interest
# print the results on the screen to let the user know the results
print("The invested amount plus the yearly interest for {} years will be $ {:.2f} dollars.".format(year+1, initial_investment))
#let's call the function to put it into action now, cheers, folks!
calculate_investment()
#This could also be done by using python simplicity by doing the following:
print(f'a simpler version: {100 * 1.1 ** 7}')
| true
|
00575e9b32db9476ffc7078e85c58b06d4ed98f2
|
AlvisonHunterArnuero/EinstiegPythonProgrammierung-
|
/format_phone_number.py
| 1,248
| 4.1875
| 4
|
# --------------------------------------------------------------------------------
# A simple Phone Number formatter routine for nicaraguan area codes
# Made with ❤️ in Python 3 by Alvison Hunter - April 4th, 2021
# JavaScript, Python and Web Development tips at: https://bit.ly/3p9hpqj
# --------------------------------------------------------------------------------
def format_phone_number(ind, lst_numb):
# Create a whole string with the elements of the given list
lst_to_str_num = ''.join(str(el) for el in lst_numb)
# Format the string we just built with the appropiate characters
fmt_numb = f"{ind+1} - ({''.join(lst_to_str_num[:3])}) {''.join(lst_to_str_num[3:7])}-{''.join(lst_to_str_num[7:11])}"
# print a line as a divider
print("-"*20)
# print the formatted string
print(fmt_numb)
# list of lists to make these formatting as our driver's code
phone_lst = [
[5, 0, 5, 8, 8, 6, 3, 8, 7, 5, 1],
[5, 0, 5, 8, 1, 0, 1, 3, 2, 3, 4],
[5, 0, 5, 8, 3, 7, 6, 1, 7, 2, 9],
[5, 0, 5, 8, 5, 4, 7, 2, 7, 1, 6]
]
# List comprehension now to iterate the list of lists
# and to apply the function to each of the list elements
[format_phone_number(i, el) for i, el in enumerate(phone_lst)]
print("-"*20)
| true
|
1c03ec92c1c0b26a9549bf8fd609a8637c1e0918
|
AlvisonHunterArnuero/EinstiegPythonProgrammierung-
|
/weird_not_weird_variation.py
| 960
| 4.34375
| 4
|
# -------------------------------------------------------------------------
# Given an integer,n, perform the following conditional actions:
# If n is odd, print Weird
# If n is even and in the inclusive range of 2 to 5, print Not Weird
# If n is even and in the inclusive range of 6 to 20, print Weird
# If n is even and greater than 20, print Not Weird
# Input Format: A single line containing a positive integer, n.
# -------------------------------------------------------------------------
# Made with ❤️ in Python 3 by Alvison Hunter - August 12th, 2022
# JavaScript, Python and Web Development tips at: https://bit.ly/3p9hpqj
# -------------------------------------------------------------------------
n = 24
is_even = n % 2 == 0
is_weird = False if n > 20 else True
if not is_even: is_weird = True
elif is_even and (2 <= n <= 5) or (n >20): is_weird = False
elif is_even and (6 <= n <= 20): is_weird = True
print("Weird" if is_weird else "Not Weird")
| true
|
1e8270231129139869e687fbab776af985abdacb
|
AlvisonHunterArnuero/EinstiegPythonProgrammierung-
|
/guess_random_num.py
| 871
| 4.34375
| 4
|
# -------------------------------------------------------------------------
# Basic operations with Python 3 | Python exercises | Beginner level
# Generate a random number, request user to guess the number
# Made with ❤️ in Python 3 by Alvison Hunter Arnuero - June 4th, 2021
# JavaScript, Python and Web Development tips at: https://bit.ly/3p9hpqj
# -------------------------------------------------------------------------
import random
attempts = 0
rnd_num = random.randint(1, 10)
player = input("Please Enter Your Name: ")
while True:
attempts += 1
num = int(input("Enter the number: \n"))
print(f"Attempts: {attempts}")
if (num == rnd_num):
print(
f"Well done {player}, you won! {rnd_num} was the correct number!")
print(
f" You got this in {attempts} Attempts.")
break
else:
pass
print("End of Game")
| true
|
5c92d100afaeff3c941bb94bd906213b11cbd0bd
|
AlvisonHunterArnuero/EinstiegPythonProgrammierung-
|
/tower_builder.py
| 644
| 4.3125
| 4
|
# Build Tower by the following given argument:
# number of floors (integer and always greater than 0).
# Tower block is represented as * | Python: return a list;
# Made with ❤️ in Python 3 by Alvison Hunter - Friday, October 16th, 2020
def tower_builder(n_floor):
lst_tower = []
pattern = '*'
width = (n_floor * 2) - 1
for items in range(1, 2 * n_floor, 2):
asterisks = items * pattern
ln = asterisks.center(width)
lst_tower.append(ln)
print(lst_tower)
return lst_tower
#let's test it out!
tower_builder(1)# ['*', ])
tower_builder(2)# [' * ', '***'])
tower_builder(3)# [' * ', ' *** ', '*****'])
| true
|
9030b8aa3ca6e00f598526efe02f28e3cc8c8fca
|
AlvisonHunterArnuero/EinstiegPythonProgrammierung-
|
/user_details_cls.py
| 2,565
| 4.28125
| 4
|
# --------------------------------------------------------------------------------
# Introduction to classes using a basic grading score for an student
# Made with ❤️ in Python 3 by Alvison Hunter - March 16th, 2021
# JavaScript, Python and Web Development tips at: https://bit.ly/3p9hpqj
# --------------------------------------------------------------------------------
class UserDetails:
user_details = {
'name':None,
'age': None,
'phone':None,
'post':None
}
# Constructor and Class Attributes
def __init__(self):
self.name = None
self.age = None
self.phone = None
self.post = None
# Regular Methods
def display_divider(self, arg_char = "-", line_length=100):
print(arg_char*line_length)
def fill_user_details(self):
self.user_details['name'] = self.name
self.user_details['age'] = self.age
self.user_details['phone'] = self.phone
self.user_details['post'] = self.post
# GETTER METHODS
# a getter function, linked to parent level properties
@property
def name(self):
print("getting the name")
return self.__name
# a getter to obtain all of the properties in a whole method
def get_user_details(self):
self.fill_user_details()
self.display_divider()
print(self.user_details)
# SETTER METHODS
# a setter function, linked to parent level properties
@name.setter
def name(self, name):
self.__name = name
# a setter to change all the properties in a whole method
def set_user_details(self,name, age, phone, post):
if(name==None or age==None or phone==None or post==None):
print("There are missing or empty parameters on this method.")
else:
self.name = name
self.age = age
self.phone = phone
self.post = post
self.display_divider()
print(f"We've successfully register the user details for {self.name}.")
# Let us create the instances now
new_user_01 = UserDetails()
new_user_01.set_user_details('Alvison Hunter',40,'8863-8751','The Life of a Web Developer')
new_user_01.get_user_details()
# Using the setter to update one property from parent, in this case the name
new_user_01.name = "Lucas Arnuero"
new_user_01.get_user_details()
# Another instance only working with the entire set of properties
new_user_02 = UserDetails()
new_user_02.set_user_details('Onice Acevedo',29,'8800-0088','Working From Home Stories')
new_user_02.get_user_details()
| true
|
ea028ebf1fdb4f74028315e52ebf4e8658ceb927
|
AlvisonHunterArnuero/EinstiegPythonProgrammierung-
|
/people_in_your_life.py
| 655
| 4.4375
| 4
|
# --------------------------------------------------------------------------------
# Introduction to classes using a basic grading score for an student
# Made with ❤️ in Python 3 by Alvison Hunter - March 6th, 2021
# JavaScript, Python and Web Development tips at: https://bit.ly/3p9hpqj
# --------------------------------------------------------------------------------
people_dict = {12:"Critican", 10:"Chismosos", 6:"Creen En Ti", 3:"Te Motivan", 1:"Ayudan"}
def display_people_in_your_life():
print("Asi Son Las Personas En Tu Vida:")
for key, value in people_dict.items():
print(f"Los que {value}: {'🏃'*key}")
display_people_in_your_life()
| false
|
9a79519d12b3d7dbdbb68c14cc8f764b40db1511
|
ChristianECG/30-Days-of-Code_HackerRank
|
/09.py
| 1,451
| 4.40625
| 4
|
# ||-------------------------------------------------------||
# ||----------------- Day 9: Recursion 3 ------------------||
# ||-------------------------------------------------------||
# Objective
# Today, we're learning and practicing an algorithmic concept
# called Recursion. Check out the Tutorial tab for learning
# materials and an instructional video!
# Recursive Method for Calculating Factorial
# / 1 N ≤ 1
# factorial(N) |
# \ N x factorial( N - 1 ) otherwise
# Task
# Write a factorial function that takes a positive integer, N
# as a parameter and prints the result of N! (N factorial).
# Note: If you fail to use recursion or fail to name your
# recursive function factorial or Factorial, you will get a
# score of 0.
# Input Format
# A single integer, N (the argument to pass to factorial).
# Constraints
# 2 ≤ N ≤ 12
# Your submission must contain a recursive function named
# factorial.
# Output Format
# Print a single integer denoting N!.
# --------------------------------------------------------------
import math
import os
import random
import re
import sys
# Complete the factorial function below.
def factorial(n):
if (n == 1 or n == 0):
return 1
else:
return n * factorial(n-1)
if __name__ == '__main__':
fptr = open(os.environ['OUTPUT_PATH'], 'w')
n = int(input())
result = factorial(n)
fptr.write(str(result) + '\n')
fptr.close()
| true
|
7405e9613731ccfdc5da27bf26cf12059e8b4899
|
ChristianECG/30-Days-of-Code_HackerRank
|
/11.py
| 1,745
| 4.28125
| 4
|
# ||-------------------------------------------------------||
# ||---------------- Day 11: 2D Arrays --------------------||
# ||-------------------------------------------------------||
# Objective
# Today, we're building on our knowledge of Arrays by adding
# another dimension. Check out the Tutorial tab for learning
# materials and an instructional video!
# Context
# Given a 6 x 6 2D Array, A:
# 1 1 1 0 0 0
# 0 1 0 0 0 0
# 1 1 1 0 0 0
# 0 0 0 0 0 0
# 0 0 0 0 0 0
# 0 0 0 0 0 0
# We define an hourglass in A to be a subset of values with
# indices falling in this pattern in A's graphical
# representation:
# a b c
# d
# e f g
# There are 16 hourglasses in A, and an hourglass sum is the
# sum of an hourglass' values.
# Task
# Calculate the hourglass sum for every hourglass in A, then
# print the maximum hourglass sum.
# Input Format
# There are 6 lines of input, where each line contains 6
# space-separated integers describing 2D Array A; every value
# in will be in the inclusive range of to -9 to 9.
# Constraints
# -9 ≤ A[i][j] ≤ 9
# 0 ≤ i,j ≤ 5
# Output Format
# Print the largest(maximum) hourglass sum found in A.
# -------------------------------------------------------------
import math
import os
import random
import re
import sys
if __name__ == '__main__':
arr = []
for _ in range(6):
arr.append(list(map(int, input().rstrip().split())))
max_reloj_sum = -math.inf
for i in range(4):
for j in range(4):
reloj_sum = arr[i][j] + arr[i][j+1] + arr[i][j+2]
reloj_sum += arr[i+1][j+1]
reloj_sum += arr[i+2][j] + arr[i+2][j+1] + arr[i+2][j+2]
max_reloj_sum = max(max_reloj_sum, reloj_sum)
print(max_reloj_sum)
| true
|
7af39c66eba7f0299a47f3674f199233923b4ba9
|
abasired/Data_struct_algos
|
/DSA_Project_2/file_recursion_problem2.py
| 1,545
| 4.15625
| 4
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Apr 28 19:21:50 2020
@author: ashishbasireddy
"""
import os
def find_files(suffix, path):
"""
Find all files beneath path with file name suffix.
Note that a path may contain further subdirectories
and those subdirectories may also contain further subdirectories.
There are no limit to the depth of the subdirectories can be.
Args:
suffix(str): suffix if the file name to be found
path(str): path of the file system
Returns:
a list of paths
"""
file_name = os.listdir(path)
path_list = []
for name in file_name:
if os.path.isdir(os.path.join(path, name)):
temp_list = find_files(suffix ,os.path.join(path, name))
path_list = path_list + temp_list
elif os.path.isfile(os.path.join(path, name)):
if suffix in name:
path_list.append(os.path.join(path, name))
return path_list
#use appropiate path while verifying this code. This path is local path
path = os.environ['HOME'] + "/testdir"
#recursion based search
#print(find_files(".c", path)) # search for .c files
#print(find_files(".py", path)) # search for .py files
print(find_files(".h", path)) # search for .h files
#loops to implement a simialr search.
os.chdir(path)
for root, dirs, files in os.walk(".", topdown = False):
for name in files:
if '.h' in name:
print(os.path.join(root, name))
| true
|
782b07d8fc6ca8ee98695353aa91f9d6794ea9ca
|
Delrorak/python_stack
|
/python/fundamentals/function_basic2.py
| 2,351
| 4.34375
| 4
|
#Countdown - Create a function that accepts a number as an input. Return a new list that counts down by one, from the number (as the 0th element) down to 0 (as the last element).
#Example: countdown(5) should return [5,4,3,2,1,0]
def add(i):
my_list = []
for i in range(i, 0-1, -1):
my_list.append(i)
return my_list
print(add(5))
#Print and Return - Create a function that will receive a list with two numbers. Print the first value and return the second.
#Example: print_and_return([1,2]) should print 1 and return 2
my_list = [6,10]
def print_return(x,y):
print(x)
return y
print("returned: ",print_return(my_list[0],my_list[1]))
#First Plus Length - Create a function that accepts a list and returns the sum of the first value in the list plus the list's length.
#Example: first_plus_length([1,2,3,4,5]) should return 6 (first value: 1 + length: 5)
def first_plus_length(list):
return list[0] + len(list)
print (first_plus_length([1,2,3,4,5]))
#Values Greater than Second - Write a function that accepts a list and creates a new list containing only the values from the original list that are greater than its 2nd value. Print how many values this is and then return the new list. If the list has less than 2 elements, have the function return False
#Example: values_greater_than_second([5,2,3,2,1,4]) should print 3 and return [5,3,4]
#Example: values_greater_than_second([3]) should return False
def values_greater_than_second(list):
new_list=[]
for i in range(0,len(list), 1):
if list[i] >= list[2]:
new_list.append(list[i])
if len(new_list) < 2:
return False
else:
return ("length of new list: " + str(len(new_list))), ("new list values: " + str(new_list))
print(values_greater_than_second([5,2,3,2,1,4]))
print(values_greater_than_second([5,2,6,2,1,4]))
#This Length, That Value - Write a function that accepts two integers as parameters: size and value. The function should create and return a list whose length is equal to the given size, and whose values are all the given value.
#Example: length_and_value(4,7) should return [7,7,7,7]
#Example: length_and_value(6,2) should return [2,2,2,2,2,2]
def L_V(size,value):
my_list = []
for size in range(size):
my_list.append(value)
return my_list
print(L_V(4,7))
print(L_V(6,2))
| true
|
886c8f7719475fdf6723610d3fb07b1a6566e825
|
Chahbouni-Chaimae/Atelier1-2
|
/python/invr_chaine.py
| 323
| 4.4375
| 4
|
def reverse_string(string):
if len(string) == 0:
return string
else:
return reverse_string(string[1:]) + string[0]
string = "is reverse"
print ("The original string is : ",end="")
print (string)
print ("The reversed string is : ",end="")
print (reverse_string(string))
| true
|
828b7b647572c21ef035b7fe77764ed99ca775a5
|
drbuche/HackerRank
|
/Python/03_Strings/005_String_Validators.py
| 1,313
| 4.1875
| 4
|
# Problem : https://www.hackerrank.com/challenges/string-validators/problem
# Score : 10 points(MAX)
# O método .isalnum() retorna True caso haja apenas caracteres alfabéticos e numéricos na string.
# O método .isalpha() retorna True caso todos os caracteres sejam caracteres alfabéticos.
# O método .isdigit() retorna True caso todos os caracteres sejam numéricos alfabéticos.
# O método .islower() retorna True caso todos os caracteres sejam caracteres alfabéticos minúsculos.
# O método .isupper() retorna True caso todos os caracteres sejam caracteres alfabéticos maiúsculos.
# Leia a palavra e retorne True caso qualquer letra que ela possua retorne True nos métodos acima.
if __name__ == '__main__':
s = input()
[print(any(eval('letra.' + metodo) for letra in s)) for metodo in ('isalnum()', 'isalpha()', 'isdigit()', 'islower()', 'isupper()')]
# imprima na tela True or False utilizando os métodos da lista em cada letra da palavra digitada
# Método any retorna True caso algum elemento seja True.
# [print(list(eval('letra.' + metodo) for letra in s)) for metodo in ('isalnum()', 'isalpha()', 'isdigit()', 'islower()', 'isupper()')]
# Caso troque o any por list(), notará que as listas que possuem ao menos 1 True foram retornadas como True pelo any()
| false
|
207404ca1e3a25f6a9d008ddbed2c7ca827c789b
|
eigenric/euler
|
/euler004.py
| 763
| 4.125
| 4
|
# author: Ricardo Ruiz
"""
Project Euler Problem 4
=======================
A palindromic number reads the same both ways. The largest palindrome made
from the product of two 2-digit numbers is 9009 = 91 * 99.
Find the largest palindrome made from the product of two 3-digit numbers.
"""
import itertools
def is_palindrome(number):
return str(number)[::-1] == str(number)
def largest_palindrome_product(digits):
possible_products = itertools.product(range(1, 10**digits), repeat=2)
largest = 0
for a, b in possible_products:
product = a * b
if is_palindrome(product) and product > largest:
largest = product
return largest
if __name__ == '__main__':
print(largest_palindrome_product(3))
| true
|
d4d673ef94eca4ddfd5b6713726e507dad1849d6
|
abhaj2/Phyton
|
/sample programs_cycle_1_phyton/13.py
| 285
| 4.28125
| 4
|
#To find factorial of the given digit
factorial=1
n=int(input("Enter your digit"))
if n>0:
for i in range(1,n+1):
factorial=factorial*i
else:
print(factorial)
elif n==0:
print("The factorial is 1")
else:
print("Factorial does not exits")
| true
|
047d6aa0dd53e1adaf6989cd5a977f07d346c73c
|
abhaj2/Phyton
|
/sample programs_cycle_1_phyton/11.py
| 235
| 4.28125
| 4
|
#to check the entered number is +ve or -ve
x=int(input("Enter your number"))
if x>0:
print("{0} is a positive number".format(x))
elif x==0:
print("The entered number is zero")
else:
print("{0} is a negative number".format(x))
| true
|
afad18bd31239b95dd4fd00ea0b8f66c668fd1a6
|
abhaj2/Phyton
|
/sample programs_cycle_1_phyton/12.py
| 374
| 4.1875
| 4
|
#To find the sum of n natural numbers
n=int(input("Enter your limit\n"))
y=0
for i in range (n):
x=int(input("Enter the numbers to be added\n"))
y=y+x
else:
print("The sum is",y)
#To find the sum of fist n natural numbers
n=int(input("Enter your limit\n"))
m=0
for i in range (1,n):
m=m+i
else:
print("The sum of first m natural numbers are", m)
| false
|
5bd43106071a675af17a6051c9de1f0cee0e0aec
|
abhaj2/Phyton
|
/cycle-2/3_c.py
| 244
| 4.125
| 4
|
wordlist=input("Enter your word\n")
vowel=[]
for x in wordlist:
if('a' in x or 'e' in x or 'i' in x or 'o' in x or'u' in x or 'A' in x or 'E' in x or 'I' in x or 'O'in x or"U" in x):
vowel.append(x)
print(vowel)
| true
|
a1a9fc369a0b994c99377dc6af16d00612a68f3b
|
juliaviolet/Python_For_Everybody
|
/Overtime_Pay_Error.py
| 405
| 4.15625
| 4
|
hours=input("Enter Hours:")
rate=input("Enter Rate:")
try:
hours1=float(hours)
rate1=float(rate)
if hours1<=40:
pay=hours1*rate1
pay1=str(pay)
print('Pay:'+'$'+pay1)
elif hours1>40:
overtime=hours1-40.0
pay2=overtime*(rate1*1.5)+40.0*rate1
pay3=str(pay2)
print('Pay:'+'$'+pay3)
except:
print('Error, please enter numeric input')
| true
|
6995eed67a401cd363dcfa60b2067ef13732becb
|
ha1fling/CryptographicAlgorithms
|
/3-RelativePrimes/Python-Original2017Code/Task 3.py
| 1,323
| 4.25
| 4
|
while True: #while loop for possibility of repeating program
while True: #integer check for input a
try:
a= input ("Enter a:")
a= int(a)
break
except ValueError:
print ("Not valid, input integers only")
while True: #integer check for input b
try:
b= input ("Enter b:")
b= int(b)
break
except ValueError:
print ("Not valid, input integers only")
def gcd(a,b): #define function
c=abs(a-b) #c = the absolute value of a minus b
if (a-b)==0: # if a-b=0
return b #function outputs b
else:
return gcd(c,min(a,b)) #function outputs smallest value out of a,b and c
d=gcd(a,b) #function assigned to value d
if d==1:
print ("-They are relative primes") #if the gcd is one they are relative primes
else:
print ("-They are not relative primes") #else/ if the gcd is not one they are not relative primes
print ()
v=input("Would you like to repeat the relative prime identifier? Enter y or n.") #while loop for repeating program
print ()
if v == "y": #y repeats program
continue
elif v == "n": #n ends program
break
| true
|
aeb8f28c7c87fcf9df9f60e1a0b65786b9910beb
|
Crazyinfo/Python-learn
|
/basis/基础/偏函数.py
| 766
| 4.3125
| 4
|
print(int('12345'))
print(int('12345',base = 8)) # int()中还有一个参数base,默认为10,可以做进制转换
def int2(x,base=2):
return int(x,base) # 定义一个方便转化大量二进制的函数
print(int2('11011'))
# functools.partial就是帮助我们创建一个偏函数的,不需要我们自己定义int2(),可以直接使用下面的代码创建一个新的函数int3:
import functools
int3 = functools.partial(int , base = 2) # 固定了int()函数的关键字参数base
print(int3('11000111'))
# functools.partial的作用就是,把一个函数的某些参数给固定住(也就是设置默认值),返回一个新的函数,调用这个新函数会更简单。
print(int3('110101',base = 8)) # base = 2可以重新定义
| false
|
9e0314bd94c25a0a1b012545cb2047d796a949b1
|
true-false-try/Python
|
/A_Byte_of_Python/lambda_/natural_number.py
| 1,551
| 4.21875
| 4
|
"""
Дано натуральне число n та послідовність натуральних чисел a1, a2,
…, an. Показати всі елементи послідовності, які є
а) повними квадратами;
б) степенями п’ятірки;
в) простими числами.
Визначити відповідні функції для перевірки, чи є число: повним квадратом,
степенню п’ятірки, простим числом.
"""
import random as rn
n = int(input('Write one number for create a length list:'))
lst_step = [rn.randint(1, 11) for i in range(1, n + 1)]
square_number = list(filter(lambda x: (x ** 0.5).is_integer() == True, lst_step))
fifth_power = list(filter(lambda x: (x ** 0.2).is_integer() == True, lst_step))
# this function shows simple numbers
def simple_number():
lst_simple = []
count = 0
for i in range(len(lst_step)):
for j in range(2, lst_step[i] + 1):
if lst_step[i] % j == 0:
count += 1
if count == 1:
lst_simple.append(lst_step[i])
else:
count = 0
continue
count = 0
return lst_simple
print('This is list with random numbers:', lst_step, sep='\n')
print('This is a list of square numbers:', square_number, sep='\n')
print('This is a list of fifth power numbers:', fifth_power, sep='\n')
print('This is a list of simple numbers:', simple_number(), sep='\n')
| false
|
64d01a920fcf73ad8e0e2f55d894029593dc559d
|
zitorelova/python-classes
|
/competition-questions/2012/J1-2012.py
| 971
| 4.34375
| 4
|
# Input Specification
# The user will be prompted to enter two integers. First, the user will be prompted to enter the speed
# limit. Second, the user will be prompted to enter the recorded speed of the car.
# Output Specification
# If the driver is not speeding, the output should be:
# Congratulations, you are within the speed limit!
# If the driver is speeding, the output should be:
# You are speeding and your fine is $F .
# where F is the amount of the fine as described in the table above.
'''
1 to 20 -> 100
21 to 30 -> 270
31 and above -> 500
'''
speed_limit = int(input('Enter the speed limit: '))
speed = int(input('Enter the recorded speed of the car: '))
if speed <= speed_limit:
print('Congratulations, you are within the speed limit!')
else:
if speed - speed_limit <= 20:
fine = 100
elif speed - speed_limit <= 30:
fine = 270
else:
fine = 500
print('You are speeding and your fine is $' + str(fine) + '.')
| true
|
693c554c403602ca49fb6a852648c4e9547723d7
|
Pasquale-Silv/Bit4id_course
|
/Course_Bit4id/ThirdDay/Loop_ex1.py
| 711
| 4.40625
| 4
|
items = ["Python", 23, "Napoli", "Pasquale"]
for item in items:
print(item)
print()
for item in items:
print("Mi chiamo {}, vivo a {}, ho {} anni e sto imparando il linguaggio di programmazione '{}'.".format(items[-1],
items[-2],
items[-3],
items[0]))
print()
for item in items:
print("Vediamo ciclicamente cosa abbiamo nella nostra lista:", item)
| false
|
56ce5b83d5ed2b0fb6807d22e52cc0dc9514a9d6
|
Pasquale-Silv/Bit4id_course
|
/Some_function/SF6_factorialWithoutRec.py
| 822
| 4.28125
| 4
|
def factorial_WithoutRec(numInt):
"""Ritorna il fattoriale del numero inserito come argomento."""
if (numInt <= 0):
return 1
factorial = 1
while(numInt > 0):
factorial *= numInt
numInt -= 1
return factorial
factorial5 = factorial_WithoutRec(5)
print("5! =", factorial5)
factorial4 = factorial_WithoutRec(4)
print("4! =", factorial4)
factorial3 = factorial_WithoutRec(3)
print("3! =", factorial3)
while(True):
num = int(input("Inserisci il numero di cui vuoi vedere il fattoriale:\n"))
factorialNum = factorial_WithoutRec(num)
print("{}! = {}".format(num, factorialNum))
risposta = input("Desideri ripetere l'operazione?\nPremi S per confermare, qualunque altra cosa per annullare.\n").upper()
if(risposta != "S"):
break
| false
|
c32334bce0e237b3ad2dac4de7efeb73cdbfb123
|
Pasquale-Silv/Bit4id_course
|
/Course_Bit4id/FourthDay/ex5_SortingIntList.py
| 808
| 4.5
| 4
|
nums = [100, -80, 3, 8, 0]
print("Lista sulla quale effettueremo le operazioni:", nums)
print("\nOriginal order:")
for num in nums:
print(num)
print("\nIncreasing order::")
for num in sorted(nums):
print(num)
print("\nOriginal order:")
for num in nums:
print(num)
print("\nDecreasing order:")
for num in sorted(nums,reverse=True):
print(num)
print("\nOriginal order:")
for num in nums:
print(num)
print("\nReverse-positional order:")
nums.reverse()
for num in nums:
print(num)
nums.reverse()
print("\nOriginal order:")
for num in nums:
print(num)
print("\nPermanent increasing order:")
nums.sort()
for num in nums:
print(num)
print("\nPermanent decreasing order:")
nums.sort(reverse=True)
for num in nums:
print(num)
| false
|
6da48b1d055c81f33d761c13c3ceef41133231bb
|
a1ip/python-learning
|
/phyton3programming/1ex4.awfulpoetry2_ans.py
| 1,576
| 4.1875
| 4
|
#!/usr/bin/env python3
"""
добавьте в нее программный код, дающий пользователю возможность определить количество выводимых строк (от 1 до 10 включительно),
передавая число в виде аргумента командной строки. Если программа вызывается без аргумента,
она должна по умолчанию выводить пять строк, как и раньше.
"""
import random
#tuple (кортежи) - относятся к разряду неизменяемых объектов
t_art=('the','a','an') #article, артикли
t_noun=('cat', 'dog', 'man', 'woman') #существительные
t_verb=('sang', 'ran', 'jumped') #глагол
t_adv=('loudly', 'quietly', 'well', 'badly') #adverb, наречие
max=5
while True:
line = input("enter a number of row or Enter to finish: ")
if line:
try:
max = int(line)
except ValueError as err:
print(err)
continue
else:
break
print ("max=",max)
if max == 0:
max=5
i = 0
l=()
while i < max:
if (random.randint(1,2))==1:
l=random.choice(t_art)
l=l+" "+random.choice(t_noun)
l=l+" "+random.choice(t_verb)
l=l+" "+random.choice(t_adv)
else:
l=random.choice(t_art)
l=l+" "+random.choice(t_noun)
l=l+" "+random.choice(t_verb)
print(l)
i+=1
| false
|
efba9a36610e4837f4723d08518a5255da5a881a
|
TonyZaitsev/Codewars
|
/8kyu/Remove First and Last Character/Remove First and Last Character.py
| 680
| 4.3125
| 4
|
/*
https://www.codewars.com/kata/56bc28ad5bdaeb48760009b0/train/python
Remove First and Last Character
It's pretty straightforward. Your goal is to create a function that removes the first and last characters of a string. You're given one parameter, the original string. You don't have to worry with strings with less than two characters.
*/
def remove_char(s):
return s[1:][:-1]
/*
Sample Tests
Test.describe("Tests")
Test.assert_equals(remove_char('eloquent'), 'loquen')
Test.assert_equals(remove_char('country'), 'ountr')
Test.assert_equals(remove_char('person'), 'erso')
Test.assert_equals(remove_char('place'), 'lac')
Test.assert_equals(remove_char('ok'), '')
*/
| true
|
0c17db71399217a47698554852206d60743ef93e
|
TonyZaitsev/Codewars
|
/7kyu/Reverse Factorials/Reverse Factorials.py
| 968
| 4.375
| 4
|
"""
https://www.codewars.com/kata/58067088c27998b119000451/train/python
Reverse Factorials
I'm sure you're familiar with factorials – that is, the product of an integer and all the integers below it.
For example, 5! = 120, as 5 * 4 * 3 * 2 * 1 = 120
Your challenge is to create a function that takes any number and returns the number that it is a factorial of. So, if your function receives 120, it should return "5!" (as a string).
Of course, not every number is a factorial of another. In this case, your function would return "None" (as a string).
Examples
120 will return "5!"
24 will return "4!"
150 will return "None"
"""
def reverse_factorial(num):
f = num
n = 1
while n <= f:
f /= n
n += 1
return "None" if f != 1 else str(n-1) + "!"
"""
Sample Tests
test.assert_equals(reverse_factorial(120), '5!')
test.assert_equals(reverse_factorial(3628800), '10!')
test.assert_equals(reverse_factorial(150), 'None')
"""
| true
|
3d35471031ccadd2fc2e526881b71a7c8b55ddc0
|
TonyZaitsev/Codewars
|
/8kyu/Is your period late?/Is your period late?.py
| 1,599
| 4.28125
| 4
|
"""
https://www.codewars.com/kata/578a8a01e9fd1549e50001f1/train/python
Is your period late?
In this kata, we will make a function to test whether a period is late.
Our function will take three parameters:
last - The Date object with the date of the last period
today - The Date object with the date of the check
cycleLength - Integer representing the length of the cycle in days
If the today is later from last than the cycleLength, the function should return true. We consider it to be late if the number of passed days is larger than the cycleLength. Otherwise return false.
"""
from datetime import *
def period_is_late(last,today,cycle_length):
return last + timedelta(days = cycle_length) < today
"""
Sample Tests
Test.describe("Basic tests")
Test.assert_equals(period_is_late(date(2016, 6, 13), date(2016, 7, 16), 35), False)
Test.assert_equals(period_is_late(date(2016, 6, 13), date(2016, 7, 16), 28), True)
Test.assert_equals(period_is_late(date(2016, 6, 13), date(2016, 7, 16), 35), False)
Test.assert_equals(period_is_late(date(2016, 6, 13), date(2016, 6, 29), 28), False)
Test.assert_equals(period_is_late(date(2016, 7, 12), date(2016, 8, 9), 28), False)
Test.assert_equals(period_is_late(date(2016, 7, 12), date(2016, 8, 10), 28), True)
Test.assert_equals(period_is_late(date(2016, 7, 1), date(2016, 8, 1), 30), True)
Test.assert_equals(period_is_late(date(2016, 6, 1), date(2016, 6, 30), 30), False)
Test.assert_equals(period_is_late(date(2016, 1, 1), date(2016, 1, 31), 30), False)
Test.assert_equals(period_is_late(date(2016, 1, 1), date(2016, 2, 1), 30), True)
"""
| true
|
019b5d23d15f4b1b28ee9d89112921f4d325375e
|
TonyZaitsev/Codewars
|
/7kyu/Sum Factorial/Sum Factorial.py
| 1,148
| 4.15625
| 4
|
"""
https://www.codewars.com/kata/56b0f6243196b9d42d000034/train/python
Sum Factorial
Factorials are often used in probability and are used as an introductory problem for looping constructs. In this kata you will be summing together multiple factorials.
Here are a few examples of factorials:
4 Factorial = 4! = 4 * 3 * 2 * 1 = 24
6 Factorial = 6! = 6 * 5 * 4 * 3 * 2 * 1 = 720
In this kata you will be given a list of values that you must first find the factorial, and then return their sum.
For example if you are passed the list [4, 6] the equivalent mathematical expression would be 4! + 6! which would equal 744.
Good Luck!
Note: Assume that all values in the list are positive integer values > 0 and each value in the list is unique.
Also, you must write your own implementation of factorial, as you cannot use the built-in math.factorial() method.
"""
def factorial(n):
if n == 1:
return 1
return n * factorial(n-1)
def sum_factorial(lst):
return sum(list(map(lambda x: factorial(x), lst)))
"""
Sample Tests
test.assert_equals(sum_factorial([4,6]), 744)
test.assert_equals(sum_factorial([5,4,1]), 145)
"""
| true
|
56be1dd38c46c57d5985d8c85b00895eeca5777d
|
TonyZaitsev/Codewars
|
/5kyu/The Hashtag Generator/The Hashtag Generator.py
| 2,177
| 4.3125
| 4
|
"""
https://www.codewars.com/kata/52449b062fb80683ec000024/train/python
The Hashtag Generator
The marketing team is spending way too much time typing in hashtags.
Let's help them with our own Hashtag Generator!
Here's the deal:
It must start with a hashtag (#).
All words must have their first letter capitalized.
If the final result is longer than 140 chars it must return false.
If the input or the result is an empty string it must return false.
Examples
" Hello there thanks for trying my Kata" => "#HelloThereThanksForTryingMyKata"
" Hello World " => "#HelloWorld"
"" => false
"""
def generate_hashtag(s):
hashtag = "#" + "".join(list(map(lambda x: x.capitalize(), s.split(" "))))
return hashtag if 1< len(hashtag) < 140 else False
"""
Sample Tests
Test.describe("Basic tests")
Test.assert_equals(generate_hashtag(''), False, 'Expected an empty string to return False')
Test.assert_equals(generate_hashtag('Do We have A Hashtag')[0], '#', 'Expeted a Hashtag (#) at the beginning.')
Test.assert_equals(generate_hashtag('Codewars'), '#Codewars', 'Should handle a single word.')
Test.assert_equals(generate_hashtag('Codewars '), '#Codewars', 'Should handle trailing whitespace.')
Test.assert_equals(generate_hashtag('Codewars Is Nice'), '#CodewarsIsNice', 'Should remove spaces.')
Test.assert_equals(generate_hashtag('codewars is nice'), '#CodewarsIsNice', 'Should capitalize first letters of words.')
Test.assert_equals(generate_hashtag('CodeWars is nice'), '#CodewarsIsNice', 'Should capitalize all letters of words - all lower case but the first.')
Test.assert_equals(generate_hashtag('c i n'), '#CIN', 'Should capitalize first letters of words even when single letters.')
Test.assert_equals(generate_hashtag('codewars is nice'), '#CodewarsIsNice', 'Should deal with unnecessary middle spaces.')
Test.assert_equals(generate_hashtag('Looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong Cat'), False, 'Should return False if the final word is longer than 140 chars.')
"""
| true
|
3afc1ab7a0de2bb6dc837084dd461865a2c34089
|
mirpulatov/racial_bias
|
/IMAN/utils.py
| 651
| 4.15625
| 4
|
def zip_longest(iterable1, iterable2):
"""
The .next() method continues until the longest iterable is exhausted.
Till then the shorter iterable starts over.
"""
iter1, iter2 = iter(iterable1), iter(iterable2)
iter1_exhausted = iter2_exhausted = False
while not (iter1_exhausted and iter2_exhausted):
try:
el1 = next(iter1)
except StopIteration:
iter1_exhausted = True
iter1 = iter(iterable1)
continue
try:
el2 = next(iter2)
except StopIteration:
iter2_exhausted = True
if iter1_exhausted:
break
iter2 = iter(iterable2)
el2 = next(iter2)
yield el1, el2
| true
|
3a1566cb54285e6f282a6e871ec37ff22caba743
|
EkajaSowmya/SravanClass
|
/conditionalStatements/ifStatement.py
| 295
| 4.25
| 4
|
n1 = int(input("enter first number"))
n2 = int(input("enter second number"))
n3 = int(input("enter third number"))
if n1 > n2 and n1 > n3:
print("n1 is largest", n1)
if n2 > n3 and n2 > n3:
print("n2 is largest number", n2)
if n3 > n1 and n3 > n2:
print("n3 is largest number", n3)
| false
|
ef92a4e1ebdf637dc387c96ba210fcaa95b7ffde
|
yuyaxiong/interveiw_algorithm
|
/剑指offer/二叉树的深度.py
| 1,525
| 4.15625
| 4
|
"""
输入一颗二叉树的根节点,求该树的深度。从根节点到叶节点一次经过的节点(含根,叶节点)形成树的一条路径,
最长路径的长度为树的深度。
5
3 7
2 8
1
"""
class BinaryTree(object):
def __init__(self):
self.value = None
self.left = None
self.right = None
class Solution(object):
def tree_depth(self, pRoot):
depth = 0
current = 0
return self.depth_help(pRoot, depth, current)
def depth_help(self, pRoot, depth, current):
if pRoot is None:
return depth
current += 1
depth = max(depth, current)
depth = self.depth_help(pRoot.left, depth, current)
depth = self.depth_help(pRoot.right, depth, current)
return depth
class Solution1(object):
def tree_depth(self, pRoot):
if pRoot is None:
return 0
left = self.tree_depth(pRoot.left)
right = self.tree_depth(pRoot.right)
return max(left, right) + 1
if __name__ == '__main__':
pRoot = BinaryTree()
pRoot.value = 5
pRoot.left = BinaryTree()
pRoot.left.value = 3
pl = pRoot.left
pRoot.right = BinaryTree()
pRoot.right.value = 7
pr = pRoot.right
pl.left = BinaryTree()
pl.right = BinaryTree()
pr.left = BinaryTree()
pr.right = BinaryTree()
pl.left.value = 2
pl.right.value = 4
# pr.left.value =
pr.right.value = 8
s = Solution1()
print(s.tree_depth(pRoot))
| false
|
77c9f7f18798917cbee5e7fc4044c3a70d73bb33
|
amitrajhello/PythonEmcTraining1
|
/psguessme.py
| 611
| 4.1875
| 4
|
"""The player will be given 10 chances to guess a number, and when player gives a input, then he should get a feedback
that his number was lesser or greater than the random number """
import random
key = random.randint(1, 1000)
x = 1
while x <= 10:
user_input = int(input('Give a random number to play the game: '))
if user_input > key:
print('your input is more than the number, please try again')
elif user_input < key:
print('your input is less than the number')
elif user_input == key:
print('Congratulations! you won!')
break
x += 1
| true
|
67e83fd9552337c410780198f08039044c925965
|
Mickey248/ai-tensorflow-bootcamp
|
/pycharm/venv/list_cheat_sheet.py
| 1,062
| 4.3125
| 4
|
# Empty list
list1 = []
list1 = ['mouse', [2, 4, 6], ['a']]
print(list1)
# How to access elements in list
list2 = ['p','r','o','b','l','e','m']
print(list2[4])
print(list1[1][1])
# slicing in a list
list2 = ['p','r','o','b','l','e','m']
print(list2[:-5])
#List id mutable !!!!!
odd = [2, 4, 6, 8]
odd[0] = 1
print(odd)
odd[1:4] =[3 ,5 ,7]
print(odd)
#append and extend can be also done in list
odd.append(9)
print(odd)
odd.extend([11, 13])
print(odd)
# Insert an element into a list
odd = [1, 9]
odd.insert(1, 3)
print(odd)
odd[2:2] =[5,7]
print(odd)
# How to delete an element from a list?
del odd[0]
print(odd)
#remove and pop are the same as in array !!!
# Clear
odd.clear()
print(odd)
#Sort a list
numbers = [1, 5, 2, 3]
numbers.sort()
print(numbers)
# An elegant way to create a list
pow2 = [2 ** x for x in range(10)]
print(pow2)
pow2 = [2 ** x for x in range(10) if x > 5]
print(pow2)
# Membership in list
print(2 in pow2)
print(2 not in pow2)
# Iterate through in a list
for fruit in ['apple','banana','orange']:
print('i like', fruit)
| true
|
c9f325732c1a2732646deadb25c9132f3dcae649
|
samir-0711/Area_of_a_circle
|
/Area.py
| 734
| 4.5625
| 5
|
import math
import turtle
# create screen
screen = turtle.Screen()
# take input from screen
r = float(screen.textinput("Area of Circle", "Enter the radius of the circle in meter: "))
# draw circle of radius r
t=turtle.Turtle()
t.fillcolor('orange')
t.begin_fill()
t.circle(r)
t.end_fill()
turtle.penup()
# calculate area
area = math.pi * r * r
# color,style and position of text
turtle.color('deep pink')
style = ('Courier', 10, 'italic')
turtle.setpos(-20,-20)
# display area of circle with radius r
turtle.write(f"Area of the circle with radius {r} meter is {area} meter^2", font=style, align='center')
# hide the turtle symbol
turtle.hideturtle()
# don't close the screen untill click on close
turtle.getscreen()._root.mainloop()
| true
|
c7ac2454578be3c3497759f156f7bb9f57415433
|
dawid86/PythonLearning
|
/Ex7/ex7.py
| 513
| 4.6875
| 5
|
# Use words.txt as the file name
# Write a program that prompts for a file name,
# then opens that file and reads through the file,
# and print the contents of the file in upper case.
# Use the file words.txt to produce the output below.
fname = input("Enter file name: ")
fhand = open(fname)
# fread = fhand.read()
# print(fread.upper())
#for line in fread:
# line = line.rstrip()
# line = fread.upper()
# print(line)
for line in fhand:
line = line.rstrip()
line = line.upper()
print(line)
| true
|
acd10df184f13bb7c54a6f4a5abac553127b27af
|
chittoorking/Top_questions_in_data_structures_in_python
|
/python_program_to_create_grade_calculator.py
| 830
| 4.25
| 4
|
#Python code for the Grade
#Calculate program in action
#Creating a dictionary which
#consists of the student name,
#assignment result test results
#And their respective lab results
def grade(student_grade):
name=student_grade['name']
assignment_marks=student_grade['assignment']
assignment_score=sum(assignment_marks)/len(assignment_marks)
test_marks=student_grade['test']
test_score=sum(test_marks)/len(test_marks)
lab_marks=student_grade['lab']
lab_score=sum(lab_marks)/len(lab_marks)
score=0.1*assignment_score+0.7*test_score+0.2*lab_score
if score>=90 :return 'A'
elif score>=80 :return 'B'
elif score>=70 :return 'C'
elif score>=60 :return 'D'
jack={"name":"Jack Frost","assignment":[80,50,40,20],"test":[75,75],"lab":[78,20,77,20]}
x=grade(jack)
print(x)
| true
|
968829ff7ec07aabb3dedfb89e390334b9b9ee57
|
chittoorking/Top_questions_in_data_structures_in_python
|
/python_program_to_check_if_a_string_is_palindrome_or_not.py
| 450
| 4.3125
| 4
|
print("This is python program to check if a string is palindrome or not")
string=input("Enter a string to check if it is palindrome or not")
l=len(string)
def isPalindrome(string):
for i in range(0,int(len(string)/2)):
if string[i]==string[l-i-1]:
flag=0
continue
else :
flag=1
return flag
ans=isPalindrome(string)
if ans==0:
print("Yes")
else:
print("No")
| true
|
06132de9f0dd0dfbf3138ead23bd4a936ca4a70a
|
chittoorking/Top_questions_in_data_structures_in_python
|
/python_program_to_interchange_first_and_last_elements_in_a_list_using_pop.py
| 277
| 4.125
| 4
|
print("This is python program to swap first and last element using swap")
def swapList(newList):
first=newList.pop(0)
last=newList.pop(-1)
newList.insert(0,last)
newList.append(first)
return newList
newList=[12,35,9,56,24]
print(swapList(newList))
| true
|
0901c75662df3c0330deb4d25087868ba0693e94
|
dipesh1011/NameAgeNumvalidation
|
/multiplicationtable.py
| 360
| 4.1875
| 4
|
num = input("Enter the number to calculate multiplication table:")
while(num.isdigit() == False):
print("Enter a integer number:")
num = input("Enter the number to calculate multiplication table:")
print("***************************")
print("Multiplication table of",num,"is:")
for i in range(1, 11):
res = int(num) * i
print(num,"*",i,"=",res)
| true
|
8ed94e5a5bc207a34271e2bb52029d7b6b71870d
|
darlenew/california
|
/california.py
| 2,088
| 4.34375
| 4
|
#!/usr/bin/env python
"""Print out a text calendar for the given year"""
import os
import sys
import calendar
FIRSTWEEKDAY = 6
WEEKEND = (5, 6) # day-of-week indices for saturday and sunday
def calabazas(year):
"""Print out a calendar, with one day per row"""
BREAK_AFTER_WEEKDAY = 6 # add a newline after this weekday
c = calendar.Calendar()
tc = calendar.TextCalendar(firstweekday=FIRSTWEEKDAY)
for month in range(1, 12+1):
print()
tc.prmonth(year, month)
print()
for day, weekday in c.itermonthdays2(year, month):
if day == 0:
continue
print("{:2} {} {}: ".format(day,
calendar.month_abbr[month],
calendar.day_abbr[weekday]))
if weekday == BREAK_AFTER_WEEKDAY:
print()
def calcium(year, weekends=True):
"""Print out a [YYYYMMDD] calendar, no breaks between weeks/months"""
tc = calendar.TextCalendar()
for month_index, month in enumerate(tc.yeardays2calendar(year, width=1), 1):
for week in month[0]: # ?
for day, weekday in week:
if not day:
continue
if not weekends and weekday in (WEEKEND):
print()
continue
print(f"[{year}{month_index:02}{day:02}]")
def calzone(year):
"""Prints YYYYMMDD calendar, like calcium without weekends"""
return calcium(year, weekends=False)
if __name__ == "__main__":
import argparse
parser = argparse.ArgumentParser(description="print out a calendar")
parser.add_argument('year', metavar='YEAR', type=int, help='the calendar year')
parser.add_argument('style', metavar='STYLE', help='calendar style')
args = parser.parse_args()
style = {'calcium': calcium,
'calabazas': calabazas,
'calzone': calzone,
}
try:
style[args.style](args.year)
except KeyError:
raise(f"Calendar style {args.style} not found")
| true
|
d86ab402a950557261f140137b2771e84ceafbbe
|
priyankagarg112/LeetCode
|
/MayChallenge/MajorityElement.py
| 875
| 4.15625
| 4
|
'''
Given an array of size n, find the majority element. The majority element is the element that appears more than ⌊ n/2 ⌋ times.
You may assume that the array is non-empty and the majority element always exist in the array.
Example 1:
Input: [3,2,3]
Output: 3
Example 2:
Input: [2,2,1,1,1,2,2]
Output: 2
'''
from typing import List
#Solution1:
from collections import Counter
class Solution:
def majorityElement(self, nums: List[int]) -> int:
return Counter(nums).most_common(1)[0][0]
#Solution2:
class Solution:
def majorityElement(self, nums: List[int]) -> int:
visited = []
for i in nums:
if i in visited:
continue
if nums.count(i) > (len(nums)/2):
return i
visited.append(i)
if __name__ == "__main__":
print(Solution().majorityElement([3,1,3,2,3]))
| true
|
61329cb09135f5634b1c64baa1db566836929a26
|
shivamach/OldMine
|
/HelloWorld/python/strings.py
| 527
| 4.375
| 4
|
print("trying basic stuff out")
m1 = "hello"
m2 = "World"
name = "shivam"
univ = "universe"
print(m1,", ",m2)
print(m1.upper())
print(m2.lower())
message = '{}, {}. welcome !'.format(m1,m2.upper())
print(message)
message = message.replace(m2.upper(),name.upper())
#replacing with methods should be precise
print(message)
name = "not shivam"
#trying out replace with f strings
message = f'{m1}, {m2.upper()}. welcome!'
print(message)
message = message.replace(m2.upper(),name.upper())
print(message)
#everything covered ayyay
| false
|
433027b761e728e242c5b58c11866208fe39ca23
|
caesarbonicillo/ITC110
|
/quadraticEquation.py
| 870
| 4.15625
| 4
|
#quadratic quations must be a positive number
import math
def main():
print("this program finds real solutions to quadratic equations")
a = float(input("enter a coefficient a:"))
b = float(input("enter coefficient b:"))
c = float(input("enter coefficient c:"))
#run only if code is greater or qual to zero
discrim = b * b - 4 * a *c
if(discrim < 0): #1, 2, 3
print("no real roots") # should always put the default in before any real work that way it doesn't do any unnessesary work.
elif(discrim ==0):#1, 2, 1
root = -b / (2 * a)
print("there is a double root at", root)
else:#1, 5, 6
discRoot = math.sqrt(b * b -4 *a *c)
root1 = (-b + discRoot) / (2* a)
root2 = (-b - discRoot) / (2 * a)
print ("\nThe solutions are:", root1, root2)
main()
| true
|
12c96ea6817d91f8d488f13c119752f747971c94
|
caesarbonicillo/ITC110
|
/Temperature.py
| 496
| 4.125
| 4
|
#convert Celsius to Fehrenheit
def main(): #this is a function
#input
celsius = eval (input ("Enter the temp in Celsius ")) #must convert to number call function EVAL
#processing
fahrenheit = round(9/5 * celsius + 32, 0)
#output
print (celsius, "The Fehrenheit temp is", fahrenheit)
main() # press f5 to run
def kiloMile():
kilo = eval (input("enter kilometers "))
miles = 1.6 * kilo
print ( kilo, "The conversion is", miles)
kiloMile()
| true
|
d8325a2d9e1214a72880b37b023d4af1a8d88469
|
pandeesh/CodeFights
|
/Challenges/find_and_replace.py
| 556
| 4.28125
| 4
|
#!/usr/bin/env python
"""
ind all occurrences of the substring in the given string and replace them with another given string...
just for fun :)
Example:
findAndReplace("I love Codefights", "I", "We") = "We love Codefights"
[input] string originalString
The original string.
[input] string stringToFind
A string to find in the originalString.
[input] string stringToReplace
A string to replace with.
[output] string
The resulting string.
"""
def findAndReplace(o, s, r):
"""
o - original string
s - substitute
r - replace
"""
return re.sub(s,r,o)
| true
|
5fa88d472f98e125a2dd79e2d6986630bbb28396
|
pandeesh/CodeFights
|
/Challenges/palindromic_no.py
| 393
| 4.125
| 4
|
#!/usr/bin/env python
"""
You're given a digit N.
Your task is to return "1234...N...4321".
Example:
For N = 5, the output is "123454321".
For N = 8, the output is "123456787654321".
[input] integer N
0 < N < 10
[output] string
"""
def Palindromic_Number(N):
s = ''
for i in range(1,N):
s = s + str(i)
return s + str(N) + s[::-1]
#tests
print(Palindromic_Number(5))
| true
|
a69789bfada6cdab50325c5d2c9ff3edf887aebe
|
dhasl002/Algorithms-DataStructures
|
/stack.py
| 1,562
| 4.3125
| 4
|
class Stack:
def __init__(self):
self.elements = []
def pop(self):
if not self.is_empty():
top_element = self.elements[len(self.elements)-1]
self.elements.pop(len(self.elements)-1)
return top_element
else:
print("The stack is empty, you cannot pop")
def push(self, element):
self.elements.append(element)
def peek(self):
if not self.is_empty():
top_element = self.elements[len(self.elements)-1]
else:
print("The stack is empty, you cannot peek")
return top_element
def is_empty(self):
if len(self.elements) > 0:
return False
else:
return True
def access_element_n(self, n):
if n > len(self.elements)-1:
return None
tmp_stack = Stack()
for i in range(0, n-1):
tmp_stack.push(self.pop())
element_to_return = self.peek()
for i in range(0, n-1):
self.push(tmp_stack.pop())
return element_to_return
if __name__ == "__main__":
print("Creating a stack with values 0-4")
stack = Stack()
for i in range(0, 5):
stack.push(i)
print("Is the stack we built empty? {}".format(stack.is_empty()))
print("Peek the top of the stack: {}".format(stack.peek()))
print("Pop the top of the stack: {}".format(stack.pop()))
print("Peek to make sure the pop worked: {}".format(stack.peek()))
print("Access the 3rd element: {}".format(stack.access_element_n(2)))
| false
|
83a2fe0e985ffa4d33987b15e6b4ed8a6eb5703b
|
Nbouchek/python-tutorials
|
/0001_ifelse.py
| 836
| 4.375
| 4
|
#!/bin/python3
# Given an integer, , perform the following conditional actions:
#
# If is odd, print Weird
# If is even and in the inclusive range of 2 to 5, print Not Weird
# If is even and in the inclusive range of 6 to 20, print Weird
# If is even and greater than 20, print Not Weird
# Input Format
#
# A single line containing a positive integer, .
#
# Constraints
#
# Output Format
#
# Print Weird if the number is weird; otherwise, print Not Weird.
#
# Sample Input 0
import math
import os
import random
import re
import sys
if __name__ == '__main__':
n = int(input("Enter a number >>> ").strip())
if n % 2 == 1:
print("Weird")
if n % 2 == 0 and 2 <= n <= 5:
print("Not Weird")
if n % 2 == 0 and 6 <= n <= 20:
print("Weird")
if n % 2 == 0 and n > 20:
print("Not Weird")
| true
|
a30b0e3f5120fc484cd712f932171bd322e757df
|
ByketPoe/gmitPandS
|
/week04-flow/lab4.1.3gradeMod2.py
| 1,152
| 4.25
| 4
|
# grade.py
# The purpose of this program is to provide a grade based on the input percentage.
# It allows for rounding up of grades if the student is 0.5% away from a higher grade bracket.
# author: Emma Farrell
# The percentage is requested from the user and converted to a float.
# Float is appropriate in this occasion as we do not want people to fail based on rounding to an integer.
percentage = float(input("Enter the percentage: "))
# In this modification of the program, the percentage inputted by the user is rounded.
# As we want to round up if the first decimal place is 0.5 or greater, we do not need to state number of decimal places.
percentageRounded = round(percentage)
# The if statements are executed as in the original program, but evaluating the new variable "percentageRounded" instead of "percentage"
if percentageRounded < 0 or percentageRounded > 100:
print("Please enter a number between 0 and 100")
elif percentageRounded < 40:
print("Fail")
elif percentageRounded < 50:
print("Pass")
elif percentageRounded < 60:
print("Merit 1")
elif percentageRounded < 70:
print("Merit 2")
else:
print("Distinction")
| true
|
6f16bc65643470b2bca5401667c9537d88187656
|
ByketPoe/gmitPandS
|
/week04-flow/lab4.1.1isEven.py
| 742
| 4.5
| 4
|
# isEven.py
# The purpose of this program is to use modulus and if statements to determine if a number is odd or even.
# author: Emma Farrell
# I prefer to use phrases like "text" or "whole number" instead of "string" and "integer" as I beleive they are more user friendly.
number = int(input("Enter a whole number: "))
# Modulus (%) is used to calculated the remainder of the input number divided by 2.
# The if statement evaluates if the remainder is equal to 0.
# If true, the number is even and a message to indicate this is printed.
# Otherwise, the number is odd and the message diplayed will state that it is odd.
if (number % 2) == 0:
print("{} is an even number".format(number))
else:
print("{} is an odd number".format(number))
| true
|
4dc6ecdfe3063f3015801cf13472f7f77d742f0a
|
Denton044/Machine-Learning
|
/PythonPractice/python-programming-beginner/Python Basics-1.py
| 2,217
| 4.5625
| 5
|
## 1. Programming And Data Science ##
england = 135
india = 124
united_states = 134
china = 123
## 2. Display Values Using The Print Function ##
china = 123
india = 124
united_states = 134
print (china)
print (united_states)
print (india)
## 3. Data Types ##
china_name = "China"
china_rounded = 123
china_exact = 122.5
print(china_name, china_rounded, china_exact)
## 4. The Type Function ##
china_name = "China"
china_exact = 122.5
print (type(china_exact))
## 5. Converting Types ##
china_rounded = 123
int_to_str = str(china_rounded)
str_to_int = int(int_to_str)
## 6. Comments ##
#temperature in China
china = 123
#temperature in India
india = 124
#temperature in United__States
united_states = 134
## 7. Arithmetic Operators ##
china_plus_10 = china + 10
us_times_100 = united_states *100
print (china_plus_10, us_times_100)
## 8. Order Of Operations ##
china = 123
india = 124
united_states = 134
china_celsius = (china - 32) * 0.56
india_celsius = (india - 32) * 0.56
us_celsius = (united_states -32) *0.56
## 10. Using A List To Store Multiple Values ##
countries = []
temperatures = []
countries.append('China')
countries.append('India')
countries.append('United States')
temperatures.append(122.5)
temperatures.append(124.0)
temperatures.append(134.1)
print (countries, temperatures)
## 11. Creating Lists With Values ##
temps = ['China', 122.5, 'India', 124.0, 'United States', 134.1]
## 12. Accessing Elements In A List ##
countries = []
temperatures = []
countries.append("China")
countries.append("India")
countries.append("United States")
temperatures.append(122.5)
temperatures.append(124.0)
temperatures.append(134.1)
# Add your code here.
china = countries[0]
china_temperature = temperatures[0]
## 13. Retrieving The Length Of A List ##
countries = ["China", "India", "United States", "Indonesia", "Brazil", "Pakistan"]
temperatures = [122.5, 124.0, 134.1, 103.1, 112.5, 128.3]
two_sum = len(countries) + len(temperatures)
## 14. Slicing Lists ##
countries = ["China", "India", "United States", "Indonesia", "Brazil", "Pakistan"]
temperatures = [122.5, 124.0, 134.1, 103.1, 112.5, 128.3]
countries_slice = countries[1:4]
temperatures_slice = temperatures[-3:]
| false
|
6fa32bc3efeb0a908468e6f9cec210846cd69085
|
yoli202/cursopython
|
/ejerciciosBasicos/main3.py
| 396
| 4.40625
| 4
|
'''
Escribir un programa que pregunte el nombre del usuario en la consola
y después de que el usuario lo introduzca muestre por pantalla <NOMBRE>
tiene <n> letras, donde <NOMBRE> es el nombre de usuario en mayúsculas y
<n> es el número de letras que tienen el nombre.
'''
name = input(" Introduce tu nombre: ")
print(name.upper() + " Tu nombre tiene " + str(len(name)) + (" letras"))
| false
|
5901b1fcabefe69b1ecc24f2e15ffe2d3daed18b
|
MaurizioAlt/ProgrammingLanguages
|
/Python/sample.py
| 454
| 4.125
| 4
|
#input
name = input("What is your name? ")
age = input("What is your age? ")
city = input("What is your city ")
enjoy = input("What do you enjoy? ")
print("Hello " + name + ". Your age is " + age )
print("You live in " + city)
print("And you enjoy " + enjoy)
#string stuff
text = "Who dis? "
print(text*3)
#or for lists
listname.reverse
#reverse
print(text[::-1])
len(text)
#if condition:
# code...
#else if condition:
# code...
#else:
# code...
| true
|
a588eb9088de56096f90119b4193087ce7ee6a58
|
setsunaNANA/pythonhomework
|
/__init__.py
| 663
| 4.1875
| 4
|
import turtle
def tree(n,degree):
# 设置出递归条件
if n<=1and degree<=10:
return
#首先让画笔向当前指向方向画n的距离
turtle.forward(n)
# 画笔向左转20度
turtle.right(degree)
#进入递归 把画n的距离缩短一半 同时再缩小转向角度
tree(n/2, degree/1.3)
# 出上层递归 转两倍角度把“头”转正
turtle.left(2*degree)
# 对左边做相同操作
tree(n / 2, degree / 1.3)
turtle.right(degree)
# 退出该层递归后画原来长度
turtle.backward(n)
if __name__ == '__main__':
# 先把画笔角度转正
turtle.left(90)
tree(100, 60)
| false
|
e91613869c1751c8bb3a0a0abaeb1dfb9cafa5c3
|
MingCai06/leetcode
|
/7-ReverseInterger.py
| 1,118
| 4.21875
| 4
|
"""
Given a 32-bit signed integer, reverse digits of an integer.
Example 1:
Input: 123
Output: 321
Example 2:
Input: -123
Output: -321
Example 3:
Input: 120
Output: 21
Note:
Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [−231, 231 − 1]. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.
"""
class Solution:
def reverse(self, x: int) -> int:
r_x = ''
if x > -10 and x<10:
return x
elif x > pow(2,31)-1 or x < -pow(2,31):
return 0
else:
str_x =str(x)
if x>0:
r_x = r_x
elif x<0:
str_x = str_x[1:]
r_x += '-'
for i in reversed(range(len(str_x))):
if i== len(str_x)-1 and str_x[i]==0:
r_x = r_x
else:
r_x = r_x + str_x[i]
if int(r_x)> pow(2,31)-1 or int(r_x) < -pow(2,31):
return 0
else:
return int(r_x)
| true
|
169aab304dfd600a169822c65e448b7e4a4abeb3
|
simgroenewald/Variables
|
/Details.py
| 341
| 4.21875
| 4
|
# Compulsory Task 2
name = input("Enter your name:")
age = input ("Enter your age:")
house_number = input ("Enter the number of your house:")
street_name = input("Enter the name of the street:")
print("This is " + name + " he/she is " + age + " years old and lives at house number " + house_number + " on " + street_name +" street.")
| true
|
4e8834fd82ae0c6b78a0d134058afbdb11d2da95
|
MaxiFrank/calculator-2
|
/new_arithmetic.py
| 1,560
| 4.28125
| 4
|
"""Functions for common math operations."""
def add(ls):
sum = 0
for num in ls:
sum = sum + num
return sum
def subtract(ls):
diff = 0
for num in ls:
diff = num - diff
return diff
# def multiply(num1, num2):
def multiply(ls):
"""Multiply the two inputs together."""
result = 1
for num in ls:
result = result * num
return result
def divide(ls):
"""Divide the first input by the second and return the result."""
result = 1
for num in ls:
result = num / result
return result
def square(num1):
# doesn't make sense to have a list
"""Return the square of the input."""
return num1 * num1
def cube(num1):
# doesn't make sense to have a list
"""Return the cube of the input."""
return num1 * num1 * num1
def power(ls):
"""Raise num1 to the power of num2 and return the value."""
result = ls[0]
for num in ls[1:]:
result = result ** num
return result # ** = exponent operator
def mod(num1, num2):
"""Return the remainder of num1 / num2."""
result = None
for num in ls:
result = result %num
return result
def add_mult(num1, num2, num3):
"""Add num1 and num2 and multiply sum by num3."""
# uncertain about how this one works. for for example ([1, 2, 3, 4])
return multiply(add(num1, num2), num3)
def add_cubes(ls):
"""Cube num1 and num2 and return the sum of these cubes."""
sum = 0
for num in ls:
sum = sum + cube(num)
return sum
print(divide([2,4,2]))
| true
|
3264f6baf0939442a45689f1746d62d6be07eece
|
aacampb/inf1340_2015_asst2
|
/exercise2.py
| 2,014
| 4.5
| 4
|
#!/usr/bin/env python
""" Assignment 2, Exercise 2, INF1340, Fall, 2015. DNA Sequencing
This module converts performs substring matching for DNA sequencing
"""
__author__ = 'Aaron Campbell, Sebastien Dagenais-Maniatopoulos & Susan Sim'
__email__ = "aaronl.campbell@mail.utoronto.ca, sebastien.maniatopoulos@mail.utoronto.ca & ses@drsusansim.org"
__copyright__ = "2015 Aaron Campbell & Sebastien Dagenais-Maniatopoulos & Susan Sim"
__license__ = "MIT License"
def find(input_string, substring, start, end):
"""
Function to find a substring within a longer string.
:param input_string: phrase or string of letters
:param substring: string found within input_string
:param start: first index position of input_string
:param end: last index position of input_string
:return : index value of the first character of substring found in input_string
:raises :
"""
index = 0
input_string = input_string.lower() # correct for variations in case
substring = substring.lower()
for ch in range(start, end): # iterate through the string
if input_string[index:index + len(substring)] == substring: # compare slice from both strings
return index
index += 1
else:
return -1
# find()
def multi_find(input_string, substring, start, end):
"""
Function to find all of the instances of a substring within in a longer string.
Return a list of the index value for the first character of each found instance.
:param input_string: phrase or string of letters
:param substring: string found within input_string
:param start: first index position of input_string
:param end: last index position of input_string
:return: list of index values of first character of each instance of substring found in input_string,
returns empty string if no instances found
"""
index = 0
input_string = input_string.lower()
substring = substring.lower()
result = ""
while index < end:
for ch in range(start, end):
if input_string[index:index + len(substring)] == substring:
result += str(index) + "," # convert int
index += 1
result = result[0:-1] # return slice of all index points
return result
else:
return ""
# multi_find()
| true
|
bb81d71014e5d45c46c1c34f10ee857f5763c75a
|
sicou2-Archive/pcc
|
/python_work/part1/ch03/c3_4.py
| 1,813
| 4.125
| 4
|
#Guest list
dinner_list = ['Sam Scott', 'Tyler Jame', 'Abadn Skrettn', 'Sbadut Reks']
def invites():
print(f'You want food {dinner_list[0]}? Come get food!')
print(f'Please honor me {dinner_list[1]}. Dine and talk!')
print(f'Hunger gnaws at you {dinner_list[2]}. Allow me to correct that.')
print(f'Poison is not for {dinner_list[3]}. You are safe eating here.')
invites()
list_len = len(dinner_list)
print(list_len)
print(f'\n{dinner_list[1]} will do me no honor. His name struck from the fun list\n\n')
del dinner_list[1]
dinner_list.append('Nahony Simpho')
invites()
print('\n\nThe council of Elders has seen fit to commission a more grand dining table. We have thus allowed for an expanded guest list.\n\n')
dinner_list.insert(0, 'Havlone of Maxuo')
dinner_list.insert(2, 'Barben Blorts')
dinner_list.append('Bill')
def expanded_invites():
print(f'We must talk {dinner_list[4]}. The food will be good.')
print(f'Be there of be dead {dinner_list[5]}. You will not starve.')
print(f'You have been asking forever. This one time {dinner_list[6]}, you may sit with us.')
invites()
expanded_invites()
list_len = len(dinner_list)
print(list_len)
print('\nWar! Trechery! The table has been destroyed by the vile Choob! Dinner for many has been lost to the sands of time. Our two closest advisors will be allowed council.\n')
list_len = len(dinner_list) - 2
for i in range(0, list_len):
dis_invited = dinner_list.pop()
print(f'Your dishonor shall be avenged {dis_invited}! Further preperations for correction are forthcoming!\n')
list_len = len(dinner_list)
print(list_len)
for i in range(0, list_len):
print(f'We urgently must consult, {dinner_list[0]}! We must correct our table tragedy!\n')
del dinner_list[0]
print(dinner_list)
# note(BCL): Working on 3-7
| true
|
0a4cc84bd54d8e538b82324172d78b145d7df88e
|
abishamathi/python-program-
|
/largest.py
| 226
| 4.21875
| 4
|
num1=10
num2=14
num3=12
if (num1 >= num2) and (num1 >= num3):
largest=num1
elif (num2 >= num1) and (num2 >=num3):
largest=num2
else:
largest=num3
print("the largest num between",num1,"num2,"num3,"is",largest)
| false
|
bad58f360c606e5a92312ffd2115872b42fffd57
|
tenasimi/Python_thero
|
/Class_polymorphism.py
| 1,731
| 4.46875
| 4
|
# different object classes can share the same name
class Dog():
def __init__(self, name):
self.name = name
def speak(self): # !! both Nico and Felix share the same method name called speak.
return self.name + " says woof!"
class Cat():
def __init__(self, name):
self.name = name
def speak(self):
return self.name + " says meow!"
#creating 2 instances one for each class
niko = Dog("niko")
felix = Cat("felix")
print(niko.speak())
print(felix.speak())
# metod 1 iterasiya ile gormek olur polimprfizmi
for pet in [niko,felix]: # pet!! iterating via list of items
print(type(pet))
print(type(pet.speak())) # both class instances share the same method name called speak
print()
print(pet.speak()) # however they are different types here main__.Cat' , main__.Dog'
print()
# metod 2 funksiya ile:
def pet_speak(pet):
print(pet.speak())
pet_speak(niko)
pet_speak(felix)
# Method3, abstract base class use
class Animal():
def __init__(self,name):
self.name = name
def speak(self): # we a raising an error, It's expecting you to inherit the animal class and then overwrite the speak method.
raise NotImplementedError("Subclass must implement this abstarct method")
# bunlari acsan erroru gorersen
#myanimal = Animal('fred')
#print(myanimal.speak())
class Dog(Animal):
def speak(self):
return self.name+ " says woof!"
class Cat(Animal):
def speak(self):
return self.name + " says meow!"
fido = Dog("Fido")
isis = Cat("isis")
# different object classes can share the same method name
print(fido.speak())
print(isis.speak())
| false
|
5cd6aae2bacc1b6626dafbc541c626c811e67aac
|
tenasimi/Python_thero
|
/Class_Inheritance.py
| 717
| 4.15625
| 4
|
class Animal():
def __init__(self):
print("ANIMAL CREATED")
def who_am_i(self):
print("I am animal")
def eat(self):
print("I am eating")
myanimal = Animal() #__init__ method gets automatically executed when you
# create Anumal()
myanimal.who_am_i()
myanimal.eat()
print()
#Dog is a Derived class from the base class Animal
class Dog(Animal):
def __init__(self):
Animal.__init__(self)
print("Dog Created")
def who_am_i(self):
print("I am a dog!")
def bark(self):
print("WOOF!")
def eat(self):
print("I am a dog and eating")
mydog = Dog()
mydog.eat()
mydog.who_am_i()
mydog.bark()
mydog.eat()
| false
|
434f69b6fd36753ac13589061bec3cd3da51124a
|
Alex0Blackwell/recursive-tree-gen
|
/makeTree.py
| 1,891
| 4.21875
| 4
|
import turtle as t
import random
class Tree():
"""This is a class for generating recursive trees using turtle"""
def __init__(self):
"""The constructor for Tree class"""
self.leafColours = ["#91ff93", "#b3ffb4", "#d1ffb3", "#99ffb1", "#d5ffad"]
t.bgcolor("#abd4ff")
t.penup()
t.sety(-375)
t.pendown()
t.color("#5c3d00")
t.pensize(2)
t.left(90)
t.forward(100) # larger trunk
t.speed(0)
self.rootPos = t.position()
def __drawHelp(self, size, pos):
"""
The private helper method to draw the tree.
Parameters:
size (int): How large the tree is to be.
pos (int): The starting position of the root.
"""
if(size < 20):
if(size % 2 == 0):
# let's only dot about every second one
t.dot(50, random.choice(self.leafColours))
return
elif(size < 50):
t.dot(50, random.choice(self.leafColours))
# inorder traversial
t.penup()
t.setposition(pos)
t.pendown()
t.forward(size)
thisPos = t.position()
thisHeading = t.heading()
size = size - random.randint(10, 20)
t.setheading(thisHeading)
t.left(25)
self.__drawHelp(size, thisPos)
t.setheading(thisHeading)
t.right(25)
self.__drawHelp(size, thisPos)
def draw(self, size):
"""
The method to draw the tree.
Parameters:
size (int): How large the tree is to be.
"""
self.__drawHelp(size, self.rootPos)
def main():
tree = Tree()
tree.draw(125)
t.hideturtle()
input("Press enter to terminate program: ")
if __name__ == '__main__':
main()
| true
|
002464d45f720f95b4af89bfa30875ae2ed46f70
|
spencerhcheng/algorithms
|
/codefights/arrayMaximalAdjacentDifference.py
| 714
| 4.15625
| 4
|
#!/usr/bin/python3
"""
Given an array of integers, find the maximal absolute difference between any two of its adjacent elements.
Example
For inputArray = [2, 4, 1, 0], the output should be
arrayMaximalAdjacentDifference(inputArray) = 3.
Input/Output
[execution time limit] 4 seconds (py3)
[input] array.integer inputArray
Guaranteed constraints:
3 ≤ inputArray.length ≤ 10,
-15 ≤ inputArray[i] ≤ 15.
[output] integer
The maximal absolute difference.
"""
def maxDiff(arr):
max_diff = float('-inf')
for idx in range(1, len(arr)):
max_diff = max(max_diff, abs(arr[idx] - arr[idx - 1]))
return max_diff
if __name__ == "__main__":
arr = [2, 4, 1, 0]
print(maxDiff(arr))
| true
|
ecaa063b18366d5248e01f5392fcb51e59612c1e
|
borisnorm/codeChallenge
|
/practiceSet/levelTreePrint.py
| 591
| 4.125
| 4
|
#Print a tree by levels
#One way to approach this is to bfs the tree
def tree_bfs(root):
queOne = [root]
queTwo = []
#i need some type of switching mechanism
while (queOne or queTwo):
print queOne
while(queOne):
item = queOne.pop()
if (item.left is not None):
queTwo.append(item.left)
if (item.right is not None):
queTwo.append(item.right)
print queTwo
while(queTwo):
item = queTwo.pop()
if (item.left is not None):
queOne.append(item.left)
if (item.right is not None):
queOne.append(item.right)
| true
|
582d85050e08a6b8982aae505cdc0acc273aec74
|
Kyle-Koivukangas/Python-Design-Patterns
|
/A.Creational Patterns/4.Prototype.py
| 1,661
| 4.1875
| 4
|
# A prototype pattern is meant to specify the kinds of objects to use a prototypical instance,
# and create new objects by copying this prototype.
# A prototype pattern is useful when the creation of an object is costly
# EG: when it requires data or processes that is from a network and you don't want to
# pay the cost of the setup each time, especially when you know the data won't change.
from copy import deepcopy
class Car:
def __init__(self):
self.__wheels = []
self.__engine = None
self.__body = None
def setBody(self, body):
self.___body = body
def attachWheel(self, wheel):
self.__wheels.append(wheel)
def setEngine(self, engine):
self.__engine = engine
def specification(self):
print(f"body: {self.__body.shape}")
print(f"engine horsepower: {self.__engine.horsepower}")
print(f"tire size: {self.__wheels[0].size}")
#it's pretty similar to the builder pattern, except you have a method that will easily allow you to copy the instance
# this stops you from having to
def clone(self):
return deepcopy(self)
# Here is another separate example
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def __str__(self):
print(f"({self.x}, {self.y})")
def move(self, x, y):
self.x += x
self.y += y
def clone(self, move_x, move_y):
""" This clone method allows you to clone the object but it also allows you to clone it at a different point on the plane """
obj = deepcopy(self)
obj.move(move_x, move_y)
return obj
| true
|
1d55b37fbef0c7975527cd50a4b65f2839fd873a
|
Kyle-Koivukangas/Python-Design-Patterns
|
/A.Creational Patterns/2.Abstract_Factory.py
| 1,420
| 4.375
| 4
|
# An abstract factory provides an interface for creating families of related objects without specifying their concrete classes.
# it's basically just another level of abstraction on top of a normal factory
# === abstract shape classes ===
class Shape2DInterface:
def draw(self): pass
class Shape3DInterface:
def build(self): pass
# === concrete shape classes ===
class Circle(Shape2DInterface):
def draw(self):
print("Circle.draw")
class Square(Shape2DInterface):
def draw(self):
print("Square.draw")
class Sphere(Shape3DInterface):
def draw(self):
print("Sphere.build")
class Cube(Shape3DInterface):
def draw(self):
print("Cube.build")
# === Abstract shape factory ===
class ShapeFactoryInterface:
def getShape(self, sides): pass
# === Concrete shape factories ===
class Shape2DFactory(Shape2DInterface):
@staticmethod
def getShape(sides):
if sides == 1:
return Circle()
if sides == 4:
return Square()
assert 0, f"Bad 2D shape creation: shape not defined for {sides} sides"
class Shape3DFactory(Shape3DInterface):
@staticmethod
def getShape(sides):
"""technically, sides refers to faces"""
if sides == 1:
return Sphere()
if sides == 6:
return Cube()
assert 0, f"Bad 3D shape creation: shape not defined for {sides} sides"
| true
|
1994561a1499d77769350b55a6f32cdd111f31fa
|
Ajat98/LC-2021
|
/easy/buy_and_sell_stock.py
| 1,330
| 4.21875
| 4
|
"""
You are given an array prices where prices[i] is the price of a given stock on the ith day.
You want to maximize your profit by choosing a single day to buy one stock and choosing a different day in the future to sell that stock.
Return the maximum profit you can achieve from this transaction. If you cannot achieve any profit, return 0.
Input: prices = [7,1,5,3,6,4]
Output: 5
Explanation: Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6-1 = 5.
Note that buying on day 2 and selling on day 1 is not allowed because you must buy before you sell.
"""
class Solution:
def maxProfit(self, prices: List[int]) -> int:
maxProfit = 0
minProfit = float('inf') #to represent largest possible val
#TOO SLOW on large arrays
# for i in range(len(prices)):
# for x in range(i, len(prices)):
# profit = prices[x] - prices[i]
# if profit > maxProfit:
# maxProfit = profit
#compare min buy price difference to max sell price at every step, keep tracking as you go.
for i in prices:
minProfit = min(i, minProfit)
profit = i - minProfit
maxProfit = max(profit, maxProfit)
return maxProfit
| true
|
3b76875ec54479b956a45331c3863f956a61df9a
|
mounui/python
|
/examples/use_super.py
| 643
| 4.125
| 4
|
# -*- coding: utf-8 -*-
# super使用 避免基类多次调用
class Base(object):
def __init__(self):
print("enter Base")
print("leave Base")
class A(Base):
def __init__(self):
print("enter A")
super(A, self).__init__()
print("leave A")
class B(Base):
def __init__(self):
print("enter B")
super(B, self).__init__()
print("leave B")
class C(A, B):
def __init__(self):
print("enter C")
super(C, self).__init__()
print("leave C")
C()
# 测试结果
# enter C
# enter A
# enter B
# enter Base
# leave Base
# leave B
# leave A
# leave C
| false
|
8e0e070279b4e917758152ea6f833a26bc56bad7
|
chirag16/DeepLearningLibrary
|
/Activations.py
| 1,541
| 4.21875
| 4
|
from abc import ABC, abstractmethod
import numpy as np
"""
class: Activation
This is the base class for all activation functions.
It has 2 methods -
compute_output - this is used during forward propagation. Calculates A given Z
copute_grad - this is used during back propagation. Calculates dZ given dA and A
"""
class Activation(ABC):
@abstractmethod
def compute_output(self, Z):
pass
@abstractmethod
def compute_grad(self, A, dA):
pass
"""
class: Sigmoid
This activation is used in the last layer for networks performing binary classification.
"""
class Sigmoid(Activation):
def __init__(self):
pass
def compute_output(self, Z):
return 1. / (1 + np.exp(-Z))
def compute_grad(self, Y, A, dA):
return dA * A * (1 - A)
"""
class: Softmax
This activation is used in the last layer for networks performing multi-class classification.
"""
class Softmax(Activation):
def __init__(self):
pass
def compute_output(self, Z):
return np.exp(Z) / np.sum(np.exp(Z), axis=0)
def compute_grad(self, Y, A, dA):
return A - Y
"""
class ReLU
This activation is used in hidden layers.
"""
class ReLU(Activation):
def __init__(self):
pass
def compute_output(self, Z):
A = Z
A[Z < 0] = 0
return A
def compute_grad(self, Y, A, dA):
dZ = dA
dZ[A == 0] = 0
return dZ
| true
|
f97b32658a54680d8cbfe95abbfd5612e6d22e4e
|
ssj9685/lecture_test
|
/assignment/week3.py
| 290
| 4.15625
| 4
|
num1=int(input("first num: "))
num2=int(input("second num: "))
print("num1 + num2 = ", num1 + num2)
print("num1 + num2 = ", num1 - num2)
print("num1 + num2 = ", num1 * num2)
print("num1 + num2 = ", num1 / num2)
print("num1 + num2 = ", num1 // num2)
print("num1 + num2 = ", num1 % num2)
| false
|
9c5afd492bc5f9a4131d440ce48636ca03fa721c
|
viharika-22/Python-Practice
|
/Problem-Set-2/prob1.py
| 332
| 4.34375
| 4
|
'''1.) Write a Python program to add 'ing' at the end of a given
string (length should be at least 3). If the given string
already ends with 'ing' then add 'ly' instead.
If the string length of the given string is less than 3,
leave it unchanged.'''
n=input()
s=n[len(n)-3:len(n)]
if s=='ing':
print(n[:len(n)-3]+'ly')
| true
|
bd512cbe3014297b8a39ab952c143ec153973495
|
CarolinaPaulo/CodeWars
|
/Python/(8 kyu)_Generate_range_of_integers.py
| 765
| 4.28125
| 4
|
#Collect|
#Implement a function named generateRange(min, max, step), which takes three arguments and generates a range of integers from min to max, with the step. The first integer is the minimum value, the second is the maximum of the range and the third is the step. (min < max)
#Task
#Implement a function named
#generateRange(2, 10, 2) // should return iterator of [2,4,6,8,10]
#generateRange(1, 10, 3) // should return iterator of [1,4,7,10]
#Note
#min < max
#step > 0
#the range does not HAVE to include max (depending on the step)
def generate_range(min, max, step):
hey = []
contador = min
while contador < max:
hey.append(contador)
if step > max:
break
contador = contador + step
return hey
| true
|
adcad46d8b5e27a20b1660861e8316f9c7044eab
|
zingpython/Common_Sorting_Algorithms
|
/selection.py
| 594
| 4.125
| 4
|
def selectionSort():
for element in range(len(alist)-1):
print("element", element)
minimum = element
print("minimum", minimum)
for index in range(element+1,len(alist)):
print("index",index)
if alist[index] < alist[minimum]:
print("alist[index]",alist[index])
print("alist[minimum]",alist[minimum])
minimum = index
print("changing minimum", minimum)
alist[element], alist[minimum] = alist[minimum], alist[element]
print("swap a,b = b,a",alist[element], alist[minimum])
# alist = [54,26,93,17,77,31,44,55,20]
alist = [30,20,10]
selectionSort()
print(alist)
| false
|
1395e5ded5679ceb8a5c607b36a04e647a407147
|
siddhantpushpraj/Python_Basics-
|
/class.py
| 2,929
| 4.1875
| 4
|
'''
class xyz:
var=10
obj1=xyz()
print(obj1.var)
'''
'''
class xyz:
var=10
def display(self):
print("hi")
obj1=xyz()
print(obj1.var)
obj1.display()
'''
##constructor
'''
class xyz:
var=10
def __init__(self,val):
print("hi")
self.val=val
print(val)
print(self.val)
obj1=xyz(10)
print(obj1.var)
'''
'''
class xyz:
class_var=0
def __init__(self,val):
xyz.class_var+=1
self.val=val
print(val)
print("class_var+=1",xyz.class_var)
obj1=xyz(10)
obj1=xyz(20)
obj1=xyz("sid")
print(obj1.val)
'''
##wap with class employee keeps the track of number of employee in a organisation and also store thier name, desiganation and salary
'''
class comp:
count=0
def __init__(self,name,desigantion,salary):
comp.count+=1
self.name=name
self.desigantion=desigantion
self.salary=salary
print("name ",name,"desigantion ",desigantion,"salary ",salary)
obj1=comp("sid","ceo","150000")
obj12=comp("rahul","manager1","150000")
obj3=comp("danish","manger2","150000")
'''
#wap that has a class circle use a class value define the vlaue of the pi use class value and calculate area nad circumferance
'''
class circle:
pi=3.14
def __init__(self,radius):
self.area=self.pi*radius**2
self.circum=self.pi*radius*2
print("circumferance",self.circum)
print("area", self.area)
radius=int(input())
obj1=circle(radius)
'''
#wap that have a class person storing dob of the person .the program subtract the dob from today date to find whether the person is elgoble for vote or vote
'''
import datetime
class vote:
def __intit__(self,name,dob):
self.name=name
self.dob=dob
def agevote():
today=datetime.date.today()
print(today)
obj1=vote("siddhant",1997)
obj.agevote()
'''
# ACCESS SPECIFIED IN PYTHON
## 1) .__ (private variable) 2)._ (protected variable)
'''
class abc:
def __init__(self,var,var1):
self.var=var
self.__var1=var1
def display(self):
print(self.var)
print(self.__var1)
k=abc(10,20)
k.display()
print(k.var)
# print(k.__var1) #private
print(k.__abc__var1)
'''
##wap uses classes to store the name and class of a student ,use a list to store the marks of three student
class student:
mark=[]
def __init__(self,name):
self.name=name
self.mark=[]
def getmarks(self,sub):
for i in range(sub):
m=int(input())
self.mark.append(m)
def display(self):
print(self.name," ",self.mark)
print("total student")
n=int(int(input()))
print("total subject")
sub=int(input())
s=[]
for i in range(n):
print("student name")
name=input()
s=student(name)
s.getmarks(sub)
s.display()
| false
|
80643111235604455d6372e409fa248db684da97
|
s56roy/python_codes
|
/python_prac/calculator.py
| 1,136
| 4.125
| 4
|
a = input('Enter the First Number:')
b = input('Enter the Second Number:')
# The entered value 10 is a string, not a number. To convert this into a number we can use int() or float() functions.
sum = float(a)+float(b)
print(sum)
print('The sum of {0} and {1} is {2}'.format(a, b, sum))
print('This is output to the screen')
print ('this is output to the screen')
print ('The Sum of a & b is', sum)
print('The sum is %.1f' %(float(input('Enter again the first number: '))+float(input('Enter again the second number: '))))
print(1,2,3,4)
# Output: 1 2 3 4
print(1,2,3,4,sep='*')
# Output: 1*2*3*4
print(1,2,3,4,sep='#',end='&')
# Output: 1#2#3#4&
print('I love {0} and {1}'.format('bread','butter'))
# Output: I love bread and butter
print('I love {1} and {0}'.format('bread','butter'))
# Output: I love butter and bread
print('Hello {name}, {greeting}'.format(greeting = 'Goodmorning', name = 'John'))
# Hello John, Goodmorning
x = 12.3456789
print('The value of x is %3.2f' %x)
# The value of x is 12.35
print('The value of x is %3.4f' %x)
# The value of x is 12.3457
import math
print(math.pi)
from math import pi
pi
| true
|
9060d68c59660d4ee334ee824eda15cc49519de9
|
ykcai/Python_ML
|
/homework/week5_homework_answers.py
| 2,683
| 4.34375
| 4
|
# Machine Learning Class Week 5 Homework Answers
# 1.
def count_primes(num):
'''
COUNT PRIMES: Write a function that returns the number of prime numbers that exist up to and including a given number
count_primes(100) --> 25
By convention, 0 and 1 are not prime.
'''
# Write your code here
# --------------------------------Code between the lines!--------------------------------
primes = [2]
x = 3
if num < 2: # for the case of num = 0 or 1
return 0
while x <= num:
for y in range(3, x, 2): # test all odd factors up to x-1
if x % y == 0:
x += 2
break
else:
primes.append(x)
x += 2
print(primes)
return len(primes)
# ---------------------------------------------------------------------------------------
def count_primes2(num):
'''
COUNT PRIMES FASTER
'''
primes = [2]
x = 3
if num < 2:
return 0
while x <= num:
for y in primes: # use the primes list!
if x % y == 0:
x += 2
break
else:
primes.append(x)
x += 2
print(primes)
return len(primes)
# Check
print(count_primes(100))
# 2.
def palindrome(s):
'''
Write a Python function that checks whether a passed in string is palindrome or not.
Note: A palindrome is word, phrase, or sequence that reads the same backward as forward, e.g., madam or nurses run.
'''
# Write your code here
# --------------------------------Code between the lines!--------------------------------
# This replaces all spaces ' ' with no space ''. (Fixes issues with strings that have spaces)
s = s.replace(' ', '')
return s == s[::-1] # Check through slicing
# ---------------------------------------------------------------------------------------
print(palindrome('helleh'))
print(palindrome('nurses run'))
print(palindrome('abcba'))
# 3.
def ran_check(num, low, high):
'''
Write a function that checks whether a number is in a given range (inclusive of high and low)
'''
# Write your code here
# --------------------------------Code between the lines!--------------------------------
# Check if num is between low and high (including low and high)
if num in range(low, high+1):
print('{} is in the range between {} and {}'.format(num, low, high))
else:
print('The number is outside the range.')
# ---------------------------------------------------------------------------------------
# Check
print(ran_check(5, 2, 7))
# 5 is in the range between 2 and 7 => True
| true
|
e25a8fc38ef3e98e5dc34aae30fbbea316e709c2
|
Hackman9912/PythonCourse
|
/Curriculum/My Git Stuff/05PythonProgramming/Additional Stuff/Basic Stuff/LoopsPractice/3.py
| 1,029
| 4.21875
| 4
|
# 3. Budget Analysis
# Write a program that asks the user to enter the amount that he or she has budgeted for amonth.
# A loop should then prompt the user to enter each of his or her expenses for the month, and keep a running total.
# When the loop finishes, the program should display theamount that the user is over or under budget.
def main():
budget = float(input("Enter the amount you have budgeted this month: "))
total = 0
cont = "Y"
while cont == "Y" or cont == "y":
expense = float(input("Enter the expense amount you want tabulated from the budget: "))
cont = str(input("Enter y to continue or any other key to quit: "))
total += expense
if total < budget:
bottom_line = budget - total
print(f"You are {bottom_line:.2f} under budget.")
elif total > budget:
bottom_line = total - budget
print(f"You are {bottom_line:.2f} over budget.")
else:
print("Your expenses matched your budget.")
main()
| true
|
2b1cf90a6ed89d0f5162114a103397c0f2a211e8
|
Hackman9912/PythonCourse
|
/Curriculum/My Git Stuff/05PythonProgramming/Additional Stuff/Hard Stuff/More advance things/iter.py
| 612
| 4.25
| 4
|
# Python iterators
# mylist = [1, 2, 3, 4]
# for item in mylist:
# print(item)
# def traverse(iterable):
# it = iter(iterable)
# while True:
# try:
# item = next(it)
# print(item)
# except: StopIteration:
# break
l1 = [1, 2, 3]
it = iter(l1)
# print next iteration in list
# print(it.__next__())
# print(it.__next__())
# print(it.__next__())
# print(it.__next__())
# or you can use this
print(next(it))
print(next(it))
print(next(it))
# print(next(it))
# some objects are not itreable and will error
iter(100)
| true
|
b62ba48d92de96b49332b094f8b34a5f5af4a6cb
|
Hackman9912/PythonCourse
|
/Curriculum/My Git Stuff/05PythonProgramming/Additional Stuff/Hard Stuff/More advance things/map.py
| 607
| 4.375
| 4
|
# The map() function
# Takes in at least 2 args. Can apply a function to every item in a list/iterable quickly
def square(x):
return x*x
numbers = [1, 2, 3, 4, 5]
squarelist = map(square, numbers)
print(next(squarelist))
print(next(squarelist))
print(next(squarelist))
print(next(squarelist))
print(next(squarelist))
sqrlist2 = map(lambda x : x*x, numbers)
print(next(sqrlist2))
print(next(sqrlist2))
print(next(sqrlist2))
print(next(sqrlist2))
print(next(sqrlist2))
tens = [10, 20, 30, 40, 50]
indx = [1, 2, 3, 4, 5]
powers = list(map(pow, tens, indx[:3]))
print(powers)
| true
|
8abfe167d6fa9e524df27f0adce9f777f4e2df58
|
Hackman9912/PythonCourse
|
/Curriculum/My Git Stuff/05PythonProgramming/Additional Stuff/Basic Stuff/LoopsPractice/5.py
| 1,278
| 4.5625
| 5
|
# 5. Average Rainfall
# Write a program that uses nested loops to collect data and calculate the average rainfall over a period of years.
# The program should first ask for the number of years. The outer loop will iterate once for each year.
# The inner loop will iterate twelve times, once for each month. Each iteration of the inner loop will ask the user for the inches of rainfall for that month.
# After all iterations,the program should display the number ofmonths, the total inches of rainfall, and the average rainfall per month for the entire period.
monthdict = {
1: "January",
2: "February",
3: "March",
4: "April",
5: "May",
6: "June",
7: "July",
8: "August",
9: "September",
10: "October",
11: "November",
12: "December"
}
months = 0
years = int(input("Enter a number of years to enter rainfall data for: "))
total_rainfall = 0
for i in range(years):
for key in monthdict:
rainfall = float(input(f"Enter the rainfall for {monthdict.get(key):}: "))
total_rainfall += rainfall
months += 1
average = total_rainfall / months
print(f"The total rainfall per for {months:} months is", total_rainfall, "\n"
f"The average rainfall a month is {average:}"
)
| true
|
60f890e1dfb13d2bf8071374024ef673509c58b2
|
Hackman9912/PythonCourse
|
/Curriculum/My Git Stuff/05PythonProgramming/Additional Stuff/Medium Stuff/Classes/Inheritance/Practice/Inheritance Exercises - 1.py
| 1,870
| 4.59375
| 5
|
"""
1. Employee and ProductionWorker Classes
Write an Employee class that keeps data attributes for the following pieces of information:
• Employee name
• Employee number
Next, write a class named ProductionWorker that is a subclass of the Employee class. The
ProductionWorker class should keep data attributes for the following information:
• Shift number (an integer, such as 1, 2, or 3)
• Hourly pay rate
The workday is divided into two shifts: day and night. The shift attribute will hold an integer value representing the shift that the employee works. The day shift is shift 1 and the
night shift is shift 2. Write the appropriate accessor and mutator methods for each class.
Once you have written the classes, write a program that creates an object of the
ProductionWorker class and prompts the user to enter data for each of the object’s data
attributes. Store the data in the object and then use the object’s accessor methods to retrieve
it and display it on the screen.
"""
import worker
def main():
shift1 = employees()
shift2 = employees()
shift3 = employees()
displaystuff(shift1)
displaystuff(shift2)
displaystuff(shift3)
def employees():
name = input('Enter the employees name: ')
number = int(input('Enter the employee number: '))
shift = int(input('Enter the shift number for the employee, 1 - Days, 2 - Swings, 3 - Mids: '))
pay = float(input('Enter the hourly pay rate of the employee: '))
return worker.ProdWork(name, number, shift, pay)
def displaystuff(thingy):
print()
print('Name: ', thingy.get_name())
print('Employee Number: ', thingy.get_number())
print('Employees Shift: ', thingy.get_shift())
print(f'Employees hourly pay rate ${thingy.get_pay()}')
main()
| true
|
d5b0d5d155c1733eb1a9fa27a7dbf11902673537
|
Hackman9912/PythonCourse
|
/Curriculum/My Git Stuff/05PythonProgramming/Additional Stuff/Basic Stuff/FunctionExercise/4.py
| 1,166
| 4.1875
| 4
|
# 4. Automobile Costs
# Write a program that asks the user to enter the monthly costs for the following expenses incurred from operating his or her automobile:
# loan payment, insurance, gas, oil, tires, andmaintenance.
# The program should then display the total monthly cost of these expenses,and the total annual cost of these expenses
loan = 0.0
insurance = 0.0
gas = 0.0
oil = 0.0
tire = 0.0
mx = 0.0
def main():
global loan, insurance, gas, oil, tire, mx
print("Enter the monthly loan cost")
loan = getcost()
print("Enter the monthly insurance cost")
insurance = getcost()
print("Enter the monthly gas cost")
gas = getcost()
print("Enter the monthly oil cost")
oil = getcost()
print("Enter the monthly tire cost")
tire = getcost()
print("Enter the monthly maintenance cost")
mx = getcost()
total()
def getcost():
return float(input())
def total():
monthly_amount = loan+insurance+gas+oil+tire+mx
print("Your monthly costs are $", monthly_amount)
annual_amount = monthly_amount*12
print("Your annual cost is $", annual_amount)
main()
| true
|
e51cbe700da1b5305ce7dfe9c1748ad3b2369690
|
Hackman9912/PythonCourse
|
/Curriculum/My Git Stuff/05PythonProgramming/Additional Stuff/Basic Stuff/Dictionaries and Sets/Sets/notes.py
| 2,742
| 4.59375
| 5
|
# Sets
# A set contains a collection of unique values and works like a mathematical set
# 1 All the elements in a set must be unique. No two elements can have the same value
# 2 Sets are unordered, which means that the elements are not stored in any particular order
# 3 The elements that are stored in a set can be of different data types
# Creating a set
my_set = set(['a', 'b', 'c'])
print(my_set)
my_set2 = set('abc')
print(my_set2)
# will remove the duplicates for us
my_set3 = set('aabbcc')
print(my_set3)
# will error, set can only take one argument
# my_set4 = set('one', 'two', 'three')
# print(my_set4)
# Brackets help
my_set5 = set(['one', 'two', 'three'])
print(my_set5)
# find length
print(len(my_set5))
# add and remove elements of a set
# initialize a blank set
new_set = set()
new_set.add(1)
new_set.add(2)
new_set.add(3)
print("New set", new_set)
# Update works
new_set.update([4, 5, 6])
print("After update: ", new_set)
new_set2 = set([7, 8, 9])
new_set.update(new_set2)
print(new_set)
# cannot do 10 instead would use .discard discard will do nothing if it won't work as opposed to return an error
new_set.remove(1)
print(new_set)
# using a for loop to iterate over a set
new_set3 = set(['a', 'b', 'c'])
for val in new_set3:
print(val)
# using in and not operator to test the value of a set
numbers_set = set([1, 2, 4])
if 1 in numbers_set:
print('The value 1 is in the set. ')
if 99 not in numbers_set:
print('The value 99 is not in the set. ')
# Find the union of sets
set1 = set([1, 2, 3, 4])
set2 = set([3, 4, 5, 6])
set3 = set1.union(set2)
print('set3', set3)
# the same as above
set5 = set1 | set2
print('set5', set5)
# Find the intersection of sets
set4 = set1.intersection(set2)
print('set 4', set4)
# same as above
set6 = set1 & set2
print('set6', set6)
char_set = set(['abc'])
char_set_upper = set(['ABC'])
char_intersect = char_set.intersection(char_set_upper)
print('character intersect upper and lower', char_intersect)
char_union = char_set.union(char_set_upper)
print('character union upper lower', char_union)
# find the difference of sets
set7 = set1.difference(set2)
print('1 and 2 diff', set7)
print('set 1', set1)
print('set 2', set2)
set8 = set2.difference(set1)
print('set 8', set8)
set9 = set1 - set2
print('set9', set9)
# finding symmetric difference in sets
set10 = set1.symmetric_difference(set2)
print('set10', set10)
set11 = set1 ^ set2
print('set11', set11)
# find the subsets and supersets
set12 = set([1,2,3,4])
set13 = set([1,2])
print(' is 13 a subset of 12', set13.issubset(set12))
print('is 12 a superset of 13', set12.issuperset(set13))
| true
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.