blob_id stringlengths 40 40 | repo_name stringlengths 5 127 | path stringlengths 2 523 | length_bytes int64 22 545k | score float64 3.5 5.34 | int_score int64 4 5 | text stringlengths 22 545k |
|---|---|---|---|---|---|---|
aa8d3118caa910d1b2198cc6882b755d5dcb68c8 | shivg7706/CodeJam | /gcj1.py | 923 | 3.53125 | 4 | def curdam(s):
charge = 1
damage = 0
for i in s:
if i == 'C':
charge *= 2
else:
damage += charge
return damage
def swap_required(s, d):
swap_c = 0
while True:
current_damage = curdam(s)
if current_damage <= d:
return swap_c
else:
pos = -1
for i in range(len(s)-1):
if s[i] == 'C' and s[i+1] == 'S':
pos = i
if pos == -1:
return pos
s[pos], s[pos+1] = s[pos+1], s[pos]
swap_c += 1
def main():
for i in range(int(input())):
x = input().split()
d = int(x[0])
s = x[1]
s = list(s)
minimum_damage = s.count('S')
currunt_damage = curdam(s)
if currunt_damage <= d:
print("Case #"+str(i+1)+": 0")
elif minimum_damage > d:
print("Case #"+str(i+1)+": IMPOSSIBLE")
else:
swap_c = swap_required(s,d)
if swap_c == -1:
print("Case #"+str(i+1)+": IMPOSSIBLE")
else:
print("Case #"+str(i+1)+": "+str(swap_c))
if __name__ == '__main__':
main() |
42c2467e03efa96cb2e2c7a250ce9e741e0f383b | GitOsku/Olio-ohjelmointi | /Exercise 1 p4.py | 196 | 4.0625 | 4 | counter = 0
while True:
number = int(input("Enter a number "))
if number > 0 :
continue
if number < 0 :
counter += 1
else:
break
print (counter) |
d6f65d9feaf588632bda256f7ddf3d41ca2c9208 | GitOsku/Olio-ohjelmointi | /Harjoitus5/Actual/PlayerClass.py | 1,466 | 3.875 | 4 | from Dicefilu import Dice
class Player(Dice):
def __init__(self, id):
self.firstname = "Oskari"
self.lastname = "Helenius"
self.ID = id
self.roll = 0
#setters
def setFirstname(self):
set_firstname = input("Gimme your firstname: ")
self.firstname = set_firstname
def setlastname(self):
set_lastname = input("Gimme your lastname: ")
self.lastname = set_lastname
def setIdenticator(self, ID):
self.ID = ID
#getters
def getFirstname(self):
return self.firstname
def getLastname(self):
return self.lastname
def getIdenticator(self):
return self.ID
def __str__(self):
return "\nFirsname: " + format(self.firstname)\
+ "\nLastname: " + format(self.lastname)\
+ "\nID: " + format(self.ID)
def main():
Player1 = Player(1)
Player1.set_toss() #rolling dice
Player2 = Player(2)
Player2.set_toss() #rolling dice
Player3 = Player(3)
Player3.set_toss() #rolling dice
dicti = {
Player1.getIdenticator(): Player1.get_toss(),
Player2.getIdenticator(): Player2.get_toss(),
Player3.getIdenticator(): Player3.get_toss()
}
for key, value in dicti.items():
print("Player", key, ' rolled: ', value)
main() |
504ef80a8922a640784e7cb0d63fb3e20324a41e | AlvisonHunterArnuero/EinstiegPythonProgrammierung- | /spam_catcher.py | 806 | 4.09375 | 4 | # let us create a list containing a set of phrases that could be considered as spam.
# Made with ❤️ in Python 3 by Alvison Hunter - January 28th, 2021
spams_lst = ["make","money","buy","subscribe","click","claim","prize","win","lottery"]
def spam_catcher():
# Bool variable to determine if the phrase is an spam or not
is_spam = False
try:
# let us ask for the phrase y convert it to lowercase
phrase = input("Enter some phrase: \n").lower()
for el in spams_lst:
if el in phrase:
is_spam = True
break
else:
continue
except:
print("Uh oh, an error has occurred. Program terminated")
quit()
else:
print("This is Spam") if is_spam else print("This is not Spam")
print("Thank you for using the Spam Catcher - January 2021")
spam_catcher()
|
ffbaeccca8238647d0d8b397684fad814b47e7e7 | AlvisonHunterArnuero/EinstiegPythonProgrammierung- | /sales_commission_calculation.py | 1,177 | 3.6875 | 4 | # --------------------------------------------------------------------------------
# Calculate Sales commision for sales received by a salesperson
# Made with ❤️ in Python 3 by Alvison Hunter - October 16th, 2021
# JavaScript, Python and Web Development tips at: https://bit.ly/3p9hpqj
# --------------------------------------------------------------------------------
class CalculateCommission:
def __init__(self, name, amount_sales, class_type):
self.name = name
self.amount_sales = amount_sales
self.class_type = class_type
self.commision_received = 0
def displayCalculations(self):
print(f"Name: {self.name}")
print(f"Amount Of Sales: {self.amount_sales}")
print(f"Class Type: {self.class_type}")
print(f"Commission Received: {self.commision_received}")
def calculateCommission(self):
if(self.class_type==1):
print("Class 1")
elif():
print("Class 2")
elif():
print("Class 3")
else:
print("No Class")
print(f"\nGood bye for now, {self.name}.")
Employee_01 = CalculateCommission("Declan Hunter",4, 2)
|
2e0daa14381cb9216d32d9b564747b51fc381487 | AlvisonHunterArnuero/EinstiegPythonProgrammierung- | /MACHINE LEARNING/ai_basic_decision_tree.py | 361 | 3.734375 | 4 | # -------------------------------------------------------------------------
# Basic operations with colletion types | Python exercises | Beginner level
# Made with ❤️ in Python 3 by Alvison Hunter Arnuero - April 7th, 2021
# JavaScript, Python and Web Development tips at: https://bit.ly/3p9hpqj
# -------------------------------------------------------------------------
|
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()
|
27c3847708abed4649efa487ed02fbe4d89904e5 | AlvisonHunterArnuero/EinstiegPythonProgrammierung- | /randomPwdGenerator.py | 1,828 | 4.0625 | 4 | # This function will generate a random string with a lenght based
# on user input number. This can be useful for temporary passwords
# or even for some temporary login tokens.
# Made with ❤️ in Python 3 by Alvison Hunter - December 28th, 2020
from random import sample
import time
from datetime import datetime
# We will incorporate some colors to the terminal
class bcolors:
PRIMARY ='\033[34m'
SECONDARY = '\033[95m'
FOOTER = '\033[37m'
INFO = '\033[36m'
SUCCESS = '\033[32m'
WARNING = '\033[93m'
DANGER = '\033[31m'
FAIL = '\033[91m'
ENDC = '\033[0m'
BOLD = '\033[1m'
UNDERLINE = '\033[4m'
# Main function is defined here
def generate_rand_pwd():
try:
print("░░░░░░░░░░░░░ Hunter Password Generator Tool ░░░░░░░")
print("============= We do not store any passwords. =======")
pwd_len = int(input("Please Enter Password Length: \n"))
if pwd_len < 70:
base_str = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789@*+&^%$#!"
str_results = ''.join(sample(base_str, pwd_len))
print(f"{bcolors.WARNING}Generating new password, please hold...{bcolors.ENDC}")
time.sleep(1)
print(f"{bcolors.INFO}The new password is:{bcolors.ENDC}\n {bcolors.SUCCESS}{str_results}{bcolors.ENDC}")
else:
print (f"{bcolors.FAIL}The password length is too big, number has to be less than 70.{bcolors.ENDC}")
return
except:
print(f"{bcolors.FAIL}Uh Oh, something went wrong!{bcolors.ENDC}")
return
finally:
print(f"{bcolors.FOOTER}© {datetime.today().strftime('%Y')} Hunter Password Generator Tool. All rights reserved.{bcolors.ENDC}")
# Time to call the function now, fellows
generate_rand_pwd()
|
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}")
|
9d079ba2115bf5b9fc4a88255b33959813c6ce1c | AlvisonHunterArnuero/EinstiegPythonProgrammierung- | /reverse_words_order_and_swap_cases.py | 604 | 3.890625 | 4 | # Esta es una antigua Forma de comunicacion inventada por un famoso general salvadoreño
# llamado Francisco Malespin en 1845 a las tropas en el salvador, honduras y nicaragua.
# Made with ❤️ in Python 3 by Alvison Hunter - November 27th, 2020
IN = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
OUT = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
def reverse_words_order_and_swap_cases(sentence):
str_res = sentence.translate(sentence.maketrans(IN, OUT))
lst = str_res.split()
reversed_lst = lst[::-1]
return (" ".join(reversed_lst))
reverse_words_order_and_swap_cases("rUns dOg")
|
f5469143697a9cdcbdf8bd41c326bafa3416137d | AlvisonHunterArnuero/EinstiegPythonProgrammierung- | /euclidian_algorithm.py | 843 | 3.796875 | 4 | # Made with ❤️ in Python 3 by Alvison Hunter - November 3rd, 2020
# primero importaremos este modulo para usar su metodo reduce
import functools as ft
# procedamos ahora a declarar la lista con los numeros que usaremos
numblst = [2, 6, 8, 4, 10, 24, 9, 96]
# Vamos a usar una funcion lambda para hacer nuestro calculo
# aplicandolo a dos de los elementos de la lista numblist
def mcd(a, b): return a if b == 0 else mcd(b, a % b)
# una vez hecho esto, usemos el reduce para iterar en la lista
# aplicando la misma funcion declarada arriba con los valores
# de cada elemento restante de la lista e imprimimos el final
print(ft.reduce(lambda x, y: mcd(x, y), numblst))
# Espero que te sirva, saludos desde Nicaragua. Subire pronto un video
# sobre este algoritmo explicando mas o menos como lo hice en mi canal
# YouTube: https://bit.ly/3mFFgwK
|
a6be5496ab9c0802d4142373f2dc4724faf74429 | AlvisonHunterArnuero/EinstiegPythonProgrammierung- | /units_inducement_calculations.py | 944 | 4.0625 | 4 | # -------------------------------------------------------------------------
# Basic operations with colletion types | Python exercises | Beginner level
# Get weekly production units per day & calculate if employee gets bonus
# Made with ❤️ in Python 3 by Alvison Hunter Arnuero - April 16th, 2021
# JavaScript, Python and Web Development tips at: https://bit.ly/3p9hpqj
# -------------------------------------------------------------------------
units_lst = []
week_days = ["Monday", "Tuesday", "Wednesday",
"Thursday", "Friday", "Saturday"]
while True:
try:
[units_lst.append(
int(input(f"Enter Employee Units for {d}: "))) for i, d in enumerate(week_days)]
total = sum(units_lst)
got_bonus = "YES" if total > 99 else "NO"
print(f"Weekly Units: {total} | Inducement: {got_bonus}")
break
except ValueError:
print("Units should be numbers! Please try again.")
pass
|
01a58f453134cfd65c7a80a32c61b00cae4bb91f | AlvisonHunterArnuero/EinstiegPythonProgrammierung- | /PYTHON NOTEBOOKS/9.0.6_file_function_questions_&_solutions.py | 2,277 | 4.09375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sat Oct 26 15:15:24 2019
@author: giles
"""
# Exercises
'''
#Question 1
#Create a function that will calculate the sum of two numbers. Call it sum_two.
#'''
#
#def sum_two(a,b):
# ''' This function returns the sum of two numbers. '''
#
# return a + b
##
#print(f'The sum of 3 and 4 is {sum_two(3,4)}' )
#
'''
Question 2
Write a function that performs multiplication of two arguments. By default the
function should multiply the first argument by 2. Call it multiply.
'''
#def multiply(a,b=2):
#
# '''
# Returns the product of a and b; if b not given
# returns 2 * a.
# '''
#
# return a * b
##
#print(f'Inputting 3 gives {multiply(3)}')
#print(f'Inputting 3 and 5 gives {multiply(3,5)}')
#
#
#
'''
#Question 3
#Write a function to calculate a to the power of b. If b is not given
#its default value should be 2. Call it power.
#'''
#
#def power(a,b=2):
# '''
# Returns a**b; if b not given,
# it will return a**2
# '''
# return a ** b
#
#print(f'Inputting 8 gives {power(8)}')
#print(f'Inputting 2 and 8 gives {power(2,8)}')
'''
##Question 4
##Create a new file called capitals.txt , store the names of five capital cities
##in the file on the same line.
##'''
#file = open('capitals.txt','w')
#file.write('London, ')
#file.write('Paris, ')
#file.write('Madrid, ')
#file.write('Lisbon, ')
#file.write('Rome,')
#file.close()
'''
#Question 5
#Write some code that requests the user to input another capital city.
#Add that city to the list of cities in capitals. Then print the file to
#the screen.
#'''
#user_input = input('Plese enter a capital city:> ')
#
#file = open('capitals.txt','a')
#file.write('\n' + user_input)
#file.close
#
#file = open('capitals.txt','r')
#print(file.read())
#file.close
'''
Question 6
Write a function that will copy the contents of one file to a new file.
'''
def copy_file(infile,outfile):
''' Copies the contents of infile to a new file, outfile.'''
with open(infile) as file_1:
with open(outfile, "w") as file_2:
file_2.write(file_1.read())
copy_file('capitals.txt','new_capitals.txt')
|
ef10b945cf9569f72e199b22b35f839eae98c7ce | AlvisonHunterArnuero/EinstiegPythonProgrammierung- | /PYTHON NOTEBOOKS/9.0.1_Files_&_Functions.py | 2,846 | 3.6875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thu Oct 24 10:19:52 2019
@author: giles
"""
# File handling in Python
# Python can open, close, read to and write to files
#f = open('kipling.txt','w')
#
#print(type(f))
#
#f.write('If you can keep your head while all about you \nare losing theirs\
#and blaming it on you,\n')
#
#f.write('If you can trust yourself when all men doubt you,\n\
#But make allowance for their doubting too;\n')
#
#f.write('If you can wait and not be tired by waiting,\n\
#Or being lied about, don\'t deal in lies,\n')
#
#f.write('Or being hated, don\'t give way to hating,\n\
#And yet don\'t look too good, nor talk too wise:\n')
#
#f.close()
#
#f = open('kipling.txt','r')
#
#print(type(f))
#
#print(f.read())
#f.close()
#
#f = open('kipling.txt','r')
#
#print(f.readline())
#f.close()
#print()
#
#f = open('kipling.txt','r')
#
#print(type(f))
#
#print(f.readlines())
#f.close()
#f = open('kipling.txt','r')
#
#print(type(f))
#
#content = f.readlines()
#f.close()
#
#f = open('kipling.txt','a')
#f.write('If you can dream - and not make dreams your master;\n\
#If you can think - and not make thoughts your aim;\n')
#f.close()
#print()
#f = open('kipling.txt','r')
#print(f.read())
#f.close()
#print()
#with open('kipling.txt','r') as f:
# for line in f.readlines():
# print(line,end='')
# Functions
#print('Hello, world!')
#def hello():
# print('Hello, world!')
#
#hello()
##
#for i in range(5):
# hello()
#def hi(name):
# print(f'Hello, {name}!')
##
#hi('Giles')
#hi('Anthony')
#hi()
#def hi_2(name='Giles'):
# print(f'Hello, {name}!')
##
#hi_2()
#n=20
#a = 0
#b = 1
#for i in range(n):
# a,b = b,a+b
#print(a)
#
#
#
def fib(n):
''' Calculates and returns the nth fibonacci number'''
a = 0
b = 1
for i in range(n):
a,b = b,a+b
return a
#
##
#fib_num = fib(20)
#print(fib_num)
##
#for i in range(20):
# print(fib(i))
# Docstring
#def calc_mean(first,*remainder):
# '''
# This calculates the mean of numbers.
# '''
# mean = (first + sum(remainder))/ (1 + len(remainder))
# print(type(remainder))
# return mean
#
#print(calc_mean(23,43,56,76,45,34,65,78,975,3456,54))
#
#
#
# Recursion
def fib_2(n):
if n == 0:
return 0
elif n == 1:
return 1
else:
return fib_2(n-1) + fib_2(n-2)
#
#x = fib_2(20)
#print(x)
#y = fib(1000)
#print(y)
##
#x = fib_2(37)
#print(x)
import timeit
t1 = timeit.Timer("fib(36)","from greetings import fib")
print(t1.timeit(5))
t2 = timeit.Timer("fib_2(36)","from greetings import fib_2")
print(t2.timeit(5))
|
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
|
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
|
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.
|
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}')
|
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)
|
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") |
d4686acca2d88d7307d3ee688c718aa9812f217b | AlvisonHunterArnuero/EinstiegPythonProgrammierung- | /fillWithZeros.py | 460 | 3.859375 | 4 |
def main():
msg = "This program will take a number and change last 2 digits to zero if is greater than 99."
msg = msg + "\n Otherwise, the number will be returned without any particular change."
print(msg)
strAmount = input("Please type in your amout: ")
if int(strAmount) > 99:
print(f"New Number is: {strAmount[:-2]}00")
else:
print(f"The Number remained the same: {strAmount} ")
if __name__ == "__main__":
main()
|
d7762178460e77a2d4a468fccf7ab93a1c63ed1d | AlvisonHunterArnuero/EinstiegPythonProgrammierung- | /AR_TURTLE.py | 528 | 3.6875 | 4 | import turtle
import random
colours = {
0: 'green',
1: 'gold',
2: 'orange',
3: 'blue',
4: 'navy',
5: 'violet',
6: 'cyan',
7: 'yellow',
8: 'red',
9: 'light blue',
}
t = turtle.Turtle()
s = turtle.Screen()
s.bgcolor('black')
t.pencolor('white')
a = 0
b = 0
t.speed(0)
t.penup()
t.goto(0,200)
t.pendown()
while True:
t.pencolor(random.choice(list(colours.values())))
t.forward(a)
t.right(b)
a+=3
b+=1
if b == 210:
break
t.hideturtle()
turtle.done()
|
e4550b3253ee04830024ad04a076e48b92354ba0 | AlvisonHunterArnuero/EinstiegPythonProgrammierung- | /roman_numerals_helper.py | 1,883 | 3.515625 | 4 | romans_dict = {"IV": 4, "IX": 9, "XL": 40, "XC": 90, "CD": 400, "CM": 900,
"I": 1, "V": 5, "X": 10, "L": 50, "C": 100, "D": 500, "M": 1000}
def from_roman(roman_num):
try:
numeric_value = 0
roman_key = ""
roman_double_key = ""
for n in range(len(roman_num)):
roman_key = romans_dict.get(roman_num[n])
roman_double_key = romans_dict.get(roman_num[n:n+2])
if(roman_double_key != None):
print(f"Double: {n} => {roman_double_key} Glyph: {roman_num[n]}")
numeric_value += roman_double_key
n += 1
elif(roman_key != None):
print(f"One: {roman_double_key} Glyph: {roman_num[n]}")
numeric_value += roman_key
n += 1
else:
print("Entro al Else")
pass
print(f"Number for {roman_num} is : {numeric_value}")
print("-"*45)
except KeyError:
pass
def to_roman(num):
numbers_dict = {"M": 1000, "CM": 900, "D": 500, "CD": 400, "C": 100,
"C": 100, "XC": 90, "L": 50, "XL": 40, "X": 10, "IX": 9, "V": 5, "IV": 4, "I": 1}
roman_value = ""
init_number = num
while (num > 0):
for k, val in numbers_dict.items():
if(val <= num):
roman_value = roman_value + k
num -= val
break
else:
pass
print(f"Number for {init_number} is : {roman_value}")
from_roman('I') # 1
from_roman('III') # 3
from_roman('IV') # 4
from_roman('XXI') # 21
from_roman('MMVIII') # 2008
# from_roman('MMVII') # 2007
# from_roman('MDCLXIX') # 1669
# to_roman(1000) # M
# to_roman(1990) # MCMXC
# to_roman(4) # 'IV'
# to_roman(1) # 'I'
# to_roman(1991) # 'MCMXCI'
# to_roman(2006) # 'MMVI'
# to_roman(2020) # 'MMXX'
|
2c5248348bc7cfa59f6cac6887176bfe922f6b90 | AlvisonHunterArnuero/EinstiegPythonProgrammierung- | /Working with text Files/textFiles.py | 1,795 | 4.09375 | 4 | # This function will generate a random string with a lenght based on user input number.
# This can be useful for temporary passwords or even for some temporary login tokens.
# The information is saved afterwards in a text file with the date and the username
# of the person who requested the creation of the new password.
# may you have questions of comments, reach out to me at alvison@gmail.com
import random
import time
from datetime import date
def main():
today = date.today()
print("░░░░░░░░░░░░░░░░ Password Generator Tool ░░░░░░░░░░░░░░░")
username = input("Enter user name: ")
numCharacters = int(input("Insert the desired number of characters: "))
if numCharacters > 70:
print ("The entered amount is too big, number has to be less than 70")
else:
baseString = list ("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789@*+&^%$#!")
strResult = ""
generated_list = random.sample(baseString, numCharacters)
for character in generated_list:
strResult += character
print("Generating new password, please hold...")
time.sleep(1)
print("The new password is: {} created by {} on {}".format(strResult, username,today.strftime("%b-%d-%Y")))
f=open("mypwdfile.txt", "a+")
f.write("\nThe new password is: {} created by {} on {}".format(strResult, username,today.strftime("%b-%d-%Y")))
f.close()
print("Passwords were successfully updated on the mypwdfile.txt as well.".format(username))
print("░░░░░░░░░░░░░░░░ Powered by Alvison Hunter ░░░░░░░░░░░░░░░")
if __name__== "__main__":
main()
|
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")
|
e3ae1adfb9306b0d81504716aab521373f427a42 | AlvisonHunterArnuero/EinstiegPythonProgrammierung- | /liam_birthday_cake.py | 657 | 3.5625 | 4 | import turtle as t
import math as m
import random as r
def drawX(a, i):
angle = m.radians(i)
return a * m.cos(angle)
def drawY(b, i):
angle = m.radians(i)
return b * m.sin(angle)
t.bgcolor("#d3dae8")
t.setup(1000, 800)
t.penup()
t.goto(150, 0)
t.pendown()
t.pencolor("white")
t.begin_fill()
for i in range(360):
x = drawX(150, i)
y = drawY(60, i)
t.goto(x, y)
t.fillcolor("#fef5f7")
t.end_fill()
t.begin_fill()
for i in range(180):
x = drawX(150, -i)
y = drawY(70, -i)
t.goto(x, y)
for i in range(180, 360):
x = drawX(150, i)
y = drawY(60, i)
t.goto(x, y)
t.fillcolor("#f2d7dd")
t.end_fill()
|
5913c4bf968dd46bbf3f0552a61c1855264a4782 | AlvisonHunterArnuero/EinstiegPythonProgrammierung- | /TURTLE PROJECTS/TURTLE EXAMPLES/multi_circles.py | 462 | 3.5 | 4 | import turtle
import random
colours = {
0: 'green',
1: 'gold',
2: 'orange',
3: 'blue',
4: 'navy',
5: 'violet',
6: 'cyan',
7: 'yellow',
8: 'red',
9: 'light blue',
}
# t = turtle.Turtle()
#turtle.Screen().bgcolor("black")
#t.pensize(2)
# t.hideturtle()
# turtle.tracer(2)
# n = 0
# while True:
# t.color(random.choice(list(colours.values())))
# t.circle(5 + n)
# n += 2
# if n > 40:
# break
|
9fa15e00d4b8b91a607277992f09681deed7b89c | AlvisonHunterArnuero/EinstiegPythonProgrammierung- | /strips_input.py | 1,176 | 3.734375 | 4 | # Made with ❤️ in Python 3 by Alvison Hunter - December 31st, 2020
def find_solution(string, markers):
lst_rows = string.split("\n")
for index_num, elem in enumerate(lst_rows):
for marker in markers:
ind = elem.find(marker)
if (ind != -1):
elem = elem[:ind]
lst_rows[index_num] = elem.rstrip(' ')
print("\n".join(lst_rows))
print('-'*65)
return("\n".join(lst_rows))
find_solution("apples, pears\ngrapes\nbananas !", ["#", "!"])
find_solution(
"apples, pears # and bananas\ngrapes\nbananas !apples", ["#", "!"])
# "apples, pears\ngrapes\nbananas"
find_solution("a #b\nc\nd $e f g", ["#", "$"]) # "a\nc\nd"
# 'avocados lemons avocados oranges strawberries\n\nwatermelons cherries avocados strawberries'
find_solution('avocados lemons avocados oranges strawberries\n.\nwatermelons cherries avocados strawberries', [
'#', "'", '.', '!', ',', '^'])
find_solution("! pears avocados oranges\nstrawberries cherries lemons lemons cherries watermelons\n' - oranges oranges\ncherries ! bananas bananas strawberries\noranges cherries cherries",
['-', "'", '!', '@', '^'])
|
2e515aa55f3994049bfa5e5da33753b927c54374 | AlvisonHunterArnuero/EinstiegPythonProgrammierung- | /find_positive_neg_numbers.py | 944 | 4.03125 | 4 | # ---------------------------------------------------------------------------------------------
# Get 10 numbers, find out if they are all positive, minor or equal to 99 & if 99 was typed.
# Made with ❤️ in Python 3 by Alvison Hunter - May 17th, 2021
# JavaScript, Python and Web Development tips at: https://bit.ly/3p9hpqj
# ---------------------------------------------------------------------------------------------
cardinals = [
"First",
"Second",
"Third",
"Fourth",
"Fifth",
"Sixth",
"Seventh",
"Eighth",
"Ninth",
"Tenth",
]
tmp_lst = []
print("Enter 10 positive numbers: \n")
[tmp_lst.append(int(input(f"Enter {cardinals[i]} Number: ")))
for i in range(10)]
[
print(f"{el} is positive.") if (el >= 0) else print(f"{el} is negative.")
for el in tmp_lst
]
[
print("Positive number 99 was typed.")
if (any(e == 99 for e in tmp_lst))
else print("Positive number 99 was NOT typed.")
]
|
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)# [' * ', ' *** ', '*****'])
|
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()
|
57214b69ac361ea4a28d62f1d9da29879a895215 | AlvisonHunterArnuero/EinstiegPythonProgrammierung- | /bike_rental_payment.py | 1,728 | 3.796875 | 4 | # --------------------------------------------------------------------------------
# Bike rentals. 100 mins = 7xmin, 101 > 1440 = 50 x min, 1440 > 96000
# Made with ❤️ in Python 3 by Alvison Hunter - March 23th, 2021
# JavaScript, Python and Web Development tips at: https://bit.ly/3p9hpqj
# --------------------------------------------------------------------------------
def bike_rental_payment():
REGULAR_RATE = 7
OVERTIME_RATE = 50
regular_charge = 0
overtime_charge = 0
exceeding_charge = 0
total = 0
while True:
# Error handling try...except init block
try:
usage_time = int(input("Please enter total amount of rented minutes: \n"))
if(usage_time<=0):
print("Invalid amount of rented minutes. Please try again.")
continue
if(usage_time <= 100):
regular_charge = usage_time * REGULAR_RATE
elif(usage_time>100 and usage_time <= 1440):
regular_charge = 100 * REGULAR_RATE
overtime_charge = (usage_time - 100) * OVERTIME_RATE
else:
regular_charge = 100 * REGULAR_RATE
overtime_charge = 1300 * OVERTIME_RATE
exceeding_charge = 0 if usage_time < 1440 else 96000
# Error handling exceptions
except ValueError:
print ("ValueError: This value should be a number.")
continue
except:
print("Uh oh! Something went really wrong!. Please try again.")
quit
else:
total = regular_charge + overtime_charge + exceeding_charge
print(f"Invoice Total: U${total}.")
break
bike_rental_payment()
|
f229b5e567fb0243c3c8b32acc730c11dfcf3856 | AlvisonHunterArnuero/EinstiegPythonProgrammierung- | /TURTLE PROJECTS/TURTLE EXAMPLES/spirograph_sphere.py | 694 | 3.640625 | 4 | # ---------------------------------------------------------------------------
# Let's built a multi-colored lines Spirograph using python and turtle module
# Made with ❤️ in Python 3 by Alvison Hunter - March 23th, 2022
# JavaScript, Python and Web Development tips at: https://bit.ly/3p9hpqj
# ---------------------------------------------------------------------------
import turtle as tt
tt.setup(800,800)
tt.pensize(2)
tt.speed(0)
wn = tt.Screen()
wn.title("Build a SpiroGraph!")
wn.bgcolor("black")
for i in range(12):
for c in ['red','magenta','blue','cyan','green','white','yellow']:
tt.color(c)
tt.circle(120)
tt.left(15)
tt.hideturtle()
wn.mainloop()
|
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()
|
2b586de4cf57c5cea9060af113a9d97d047952b4 | Ziles131/PyCourseStepik | /1.6_inheritance_class_3.py | 321 | 3.625 | 4 | import time
class Loggable:
def log(self, msg):
print(str(time.ctime()) + ": " + str(msg))
class LoggableList(list, Loggable):
def append(self, v):
super(LoggableList, self).append(v)
super(LoggableList, self).log(v)
l = LoggableList()
print(l)
l.append(17)
l.append(1)
l.append(89)
l.append(9)
l.append(35)
|
e917dbbac09b04a21d97e7a322597eac8e86fa41 | Ziles131/PyCourseStepik | /Standard_Language_Facilities_2/Errors_and_exceptions_2.3.py | 214 | 3.53125 | 4 | class NonPositiveError(Exception):
pass
class PositiveList(list):
def append(self, x):
if int(x) > 0:
y = super(PositiveList, self).append(x)
return y
else:
raise NonPositiveError("incorrect number") |
13739cc96abe84a26a355655e16e5e4885bbbb33 | leofeen/Translator_Web | /translator/translator_web/translate.py | 16,771 | 3.96875 | 4 | def translate(input_data: str, language: str):
"""
Keywords are case insensitive.
Commands are case sensitive.
"""
output_data = ''
language_reference = get_language_reference(language)
# Every programm should have main block:
# starts with 'begin' token,
# ends with 'end' token - checking on it
if not (input_data.upper().find(language_reference['begin']) != -1
and input_data.upper().find(language_reference['end']) != -1):
raise SyntaxError('Expected main block of program')
input_data = input_data.split('\n')
# Count number og lines for tracebacks
line_count = 0
# Parse all enters to one string in output
input_string = ''
first_input = True
while input_data[0].upper().find(language_reference['begin']) == -1:
line_count += 1
input_string_line = input_data[0]
input_string_line = input_string_line.strip().strip('\t')
if input_string_line != '':
if not input_string_line.upper().startswith(language_reference['enter']):
raise SyntaxError(f'Unexpected keyword at line {line_count}: {input_string_line}')
enter_keyword, string_element, number_of_repetition = input_string_line.split()
if first_input:
first_input = False
else:
input_string += ' + '
if int(number_of_repetition) > 1:
input_string += f'\'{string_element}\'*{number_of_repetition}'
elif int(number_of_repetition) == 1:
input_string += f'\'{string_element}\'' # Do not write 'a'*1
else:
raise SyntaxError(f'Type Error at line {line_count}: expected positive number of string element repetition, but {number_of_repetition} was given')
del input_data[0]
if input_string != '':
output_data += f'string = {input_string}\n'
output_data += '\n'
# Every programm should have main block:
# starts with 'begin' token,
# ends with 'end' token - this is at least 2 lines
if len(input_data) < 2:
raise SyntaxError(f'Unexpected pseudocode structure after line {line_count}')
# Parse main block of pseudocode programm
number_of_spaces = 0
in_while = 0
in_if = 0
# Trying to output good-looking code,
# so excluding two or more blank line in a row
previous_line_is_blank = False
while input_data[0].upper().strip().strip('\t') != language_reference['end']:
line_count += 1
# Preformating line to handle parsing more easily
line = input_data[0]
line = line.strip().strip('\t')
while line.find(language_reference['find'] + ' ') != -1 or line.find(language_reference['replace'] + ' ') != -1:
line = line.replace(language_reference['find'] + ' ', language_reference['find'])
line = line.replace(language_reference['replace'] + ' ', language_reference['replace'])
while line.find('( ') != -1 or line.find(' )') != -1:
line = line.replace('( ', '(')
line = line.replace(' )', ')')
if line.upper() == language_reference['begin']:
pass
elif line.startswith('//'):
output_data += ' '*number_of_spaces + '#' + line[2:] + '\n'
elif line.upper() == language_reference['end_while']:
number_of_spaces -= 4
if not in_while:
raise SyntaxError(f'Unexpected end of while block at line {line_count}')
in_while -= 1
if not previous_line_is_blank:
output_data += '\n'
previous_line_is_blank = True
elif line.upper() == language_reference['end_if']:
number_of_spaces -= 4
if not in_if:
raise SyntaxError(f'Unexpected end of if block at line {line_count}')
in_if -= 1
if not previous_line_is_blank :
output_data += '\n'
previous_line_is_blank = True
elif line.upper().startswith(language_reference['while']):
previous_line_is_blank = False
in_while += 1
output_data += ' '*number_of_spaces + 'while'
number_of_spaces += 4
conditions = line[len(language_reference['while']):].split()
for condition in conditions:
if not (condition.startswith(language_reference['find'])
or condition.upper() == language_reference['or']
or condition.upper() == language_reference['and']
or condition.upper() == language_reference['not']):
raise SyntaxError(f'Unexpected keyword at line {line_count}: {condition}')
if condition.upper() == language_reference['or']:
output_data += ' or'
elif condition.upper() == language_reference['and']:
output_data += ' and'
elif condition.upper() == language_reference['not']:
output_data += ' not'
else:
arg = condition[len(language_reference['find'])+1:-1]
output_data += f' string.find(\'{arg}\') != -1'
output_data += ':\n'
elif line.upper().startswith(language_reference['if']):
previous_line_is_blank = False
in_if += 1
output_data += ' '*number_of_spaces + 'if'
number_of_spaces += 4
conditions = line[len(language_reference['if']):].split()
for condition in conditions:
if not (condition.startswith(language_reference['find'])
or condition.upper() == language_reference['or']
or condition.upper() == language_reference['and']
or condition.upper() == language_reference['not']):
raise SyntaxError(f'Unexpected keyword at line {line_count}: {condition}')
if condition.upper() == language_reference['or']:
output_data += ' or'
elif condition.upper() == language_reference['and']:
output_data += ' and'
elif condition.upper() == language_reference['not']:
output_data += ' not'
else:
arg = condition[len(language_reference['find'])+1:-1]
output_data += f' string.find(\'{arg}\') != -1'
output_data += ':\n'
elif line.upper().startswith(language_reference['then']):
previous_line_is_blank = False
command = line[len(language_reference['then'])+1:]
if command != '':
if not command.startswith(language_reference['replace']):
raise SyntaxError(f'Unexpected command at line {line_count}: {command}')
args = command[len(language_reference['replace'])+1:-1].split(',')
if len(args) != 2:
raise SyntaxError(f'Type Error at line {line_count}: replace command expected 2 arguments, but {len(args)} was given')
output_data += ' '*number_of_spaces + f'string = string.replace(\'{args[0]}\', \'{args[1].strip()}\', 1)\n'
elif line.upper().startswith(language_reference['else']):
previous_line_is_blank = False
output_data += ' '*(number_of_spaces-4) + 'else:\n'
command = line[len(language_reference['else'])+1:]
if command != '':
if not command.startswith(language_reference['replace']):
raise SyntaxError(f'Unexpected command at line {line_count}: {command}')
args = command[len(language_reference['replace'])+1:-1].split(',')
if len(args) != 2:
raise SyntaxError(f'Type Error at line {line_count}: replace command expected 2 arguments, but {len(args)} was given')
output_data += ' '*number_of_spaces + f'string = string.replace(\'{args[0]}\', \'{args[1].strip()}\', 1)\n'
elif line.startswith(language_reference['replace']):
previous_line_is_blank = False
args = line[len(language_reference['replace'])+1:-1].split(',')
if len(args) != 2:
raise SyntaxError(f'Type Error at line {line_count}: replace command expected 2 arguments, but {len(args)} was given')
output_data += ' '*number_of_spaces + f'string = string.replace(\'{args[0]}\', \'{args[1].strip()}\', 1)\n'
elif line.upper() == language_reference['str_out']:
previous_line_is_blank = False
output_data += ' '*number_of_spaces + 'print(string)\n'
elif line.upper() == language_reference['len_out']:
previous_line_is_blank = False
output_data += ' '*number_of_spaces + 'print(len(string))\n'
elif line.upper() == language_reference['sum_out']:
previous_line_is_blank = False
output_data += ' '*number_of_spaces + 'summ = 0\n'
output_data += ' '*number_of_spaces + 'for element in string:\n'
output_data += ' '*(number_of_spaces + 4) + 'if element.isnumeric(): summ += int(element)\n'
output_data += ' '*number_of_spaces + 'print(summ)\n'
else:
raise SyntaxError(f'Unexpected keyword at line {line_count}: {line}')
del input_data[0]
# Every 'if' or 'while' token should have closing 'end_if' and
# 'end_while' tokens respectfully
if in_if:
raise SyntaxError('Expected end of if block, but got EOF') # End-Of-File
if in_while:
raise SyntaxError('Expected end of while block, but got EOF') # End-Of-File
return output_data
def get_language_reference(language: str):
# Languge reference keywords must be in upper case
if language == 'ru':
language_reference = {
'begin': 'НАЧАЛО',
'enter': 'ВВОД',
'end': 'КОНЕЦ',
'find': 'нашлось',
'replace': 'заменить',
'end_while': 'КОНЕЦ ПОКА',
'end_if': 'КОНЕЦ ЕСЛИ',
'if': 'ЕСЛИ',
'while': 'ПОКА',
'or': 'ИЛИ',
'and': 'И',
'not': 'НЕ',
'then': 'ТО',
'else': 'ИНАЧЕ',
'str_out': 'ВЫВОД СТРОКИ',
'len_out': 'ВЫВОД ДЛИНЫ',
'sum_out': 'ВЫВОД СУММЫ',
}
elif language == 'en':
language_reference = {
'begin': 'BEGIN',
'enter': 'ENTER',
'end': 'END',
'find': 'find',
'replace': 'replace',
'end_while': 'END WHILE',
'end_if': 'END IF',
'if': 'IF',
'while': 'WHILE',
'or': 'OR',
'and': 'AND',
'not': 'NOT',
'then': 'THEN',
'else': 'ELSE',
'str_out': 'OUTPUT STRING',
'len_out': 'OUTPUT LENGTH',
'sum_out': 'OUTPUT SUM',
}
else:
raise ValueError(f'Unsopported language: {language}')
return language_reference
def get_language_description(language: str):
if language == 'ru':
language_description = {
'НАЧАЛО ... КОНЕЦ': 'Операторные скобки для основного блока программы.',
'ВВОД str number': 'Добавляет <code class="code-snippet">number</code> раз к строке для обработки подстроку <code class="code-snippet">str</code>. Может идти только перед <code class="code-snippet">НАЧАЛО</code>.',
'нашлось(str)': 'Проверяет наличие подстроки <code class="code-snippet">str</code> в строке для обработки. Возвращает True, если подстрока найдена. Иначе возвращает False.',
'заменить(old, new)': 'Заменяет первую слева подстроку <code class="code-snippet">old</code> на подстроку new в строке для обработки. Если подстрока old отсутствует, то команда не выполняется.',
'ПОКА condition ... КОНЕЦ ПОКА': 'Объявление блока цикла Пока. Выполняются строки внутри блока, пока <code class="code-snippet">condition</code> возвращает True.',
'ЕСЛИ condition ТО ... ИНАЧЕ ... КОНЕЦ ЕСЛИ': 'Объявление блока Если/То/Иначе. Если <code class="code-snippet">condition</code> возвращает True, то выполняются строка с <code class="code-snippet">ТО</code> или строки между <code class="code-snippet">ТО</code> и <code class="code-snippet">ИНАЧЕ</code>/<code class="code-snippet">КОНЕЦ ЕСЛИ</code>, иначе выполняется строка с <code class="code-snippet">ИНАЧЕ</code> или строки между <code class="code-snippet">ИНАЧЕ</code> и <code class="code-snippet">КОНЕЦ ЕСЛИ</code>, если такие присутствуют.',
'ВЫВОД СТРОКИ': 'Печатает строку для обработки в текущем состоянии.',
'ВЫВОД ДЛИНЫ': 'Печатает длину строки для обработки в текущем состоянии.',
'ВЫВОД СУММЫ': 'Печатет сумму всех цифр в строке для обработки в текущем состоянии.',
'// ...': 'Строка, начинающаяся с <code class="code-snippet">//</code>, является комментарием, не влияющим на исполнение кода.',
'И, ИЛИ, НЕ': 'Логические операторы, использующиеся в <code class="code-snippet">condition</code> в <code class="code-snippet">ЕСЛИ</code> и <code class="code-snippet">ПОКА</code> между несколькими <code class="code-snippet">нашлось()</code>.',
}
elif language == 'en':
language_description = {
'BEGIN ... END': 'Declaration of main block of the program.',
'ENTER str number': 'Appends substring <code class="code-snippet">str</code> to input string <code class="code-snippet">number</code> times. This must go before <code class="code-snippet">BEGIN</code> statement.',
'find(str)': 'Check if substing <code class="code-snippet">str</code> is a part of input string. Returns True if <code class="code-snippet">str</code> was found. Returns False otherwise.',
'replace(old, new)': 'Replace first from the left substring <code class="code-snippet">old</code> by substring <code class="code-snippet">new</code> in input string. If there is no inclusion of substring <code class="code-snippet">old</code> in input string, than nothing happens.',
'WHILE condition ... END WHILE': 'Declaration of While block. Lines inside block will be executed, while <code class="code-snippet">condition</code> returns True.',
'IF condition THEN ... ELSE ... END IF': 'Declaration of If/Then/Else block. If <code class="code-snippet">condition</code> returns True, then line with <code class="code-snippet">THEN</code> or lines between <code class="code-snippet">THEN</code> and <code class="code-snippet">ELSE</code>/<code class="code-snippet">END IF</code> will be executed, else line with <code class="code-snippet">ELSE</code> or lines between <code class="code-snippet">ELSE</code> and <code class="code-snippet">END IF</code> will be executed, if there is one.',
'OUTPUT STRING': 'Print input string in current state of processing.',
'OUTPUT LENGTH': 'Print length input string in current state of processing.',
'OUTPUT SUM': 'Print sum of all digits in input string in current state of processing.',
'// ...': 'Line that starts with <code class="code-snippet">//</code>, considered a сomment and does not affect program execution.',
'AND, OR, NOT': 'Logic operands that used in <code class="code-snippet">condition</code> inside <code class="code-snippet">IF</code> and <code class="code-snippet">WHILE</code> statements between several <code class="code-snippet">find()</code>.',
}
else:
raise ValueError(f'Unsopported language: {language}')
return language_description |
805e604bebdab27987ca0939a06dee8475e9bd82 | yellowsimulator/data-centric-software-application | /examples/3 - data-storage/database_operations.py | 1,873 | 3.8125 | 4 | """
Implemets databases operations such as
- creates database
- creates table
- inssert rows into a table
- drop a table
Uses local host by default.
"""
import psycopg2 as psg
from sql_queries import create_table_queries
from sql_queries import drop_table_queries
def connect_to_database():
"""Creates a connection.
"""
conn = psg.connect(host='127.0.0.1', dbname='music_library', \
user='postgres', password='admin')
cursor = conn.cursor()
return cursor, conn
def create_database(database_name: str, username: str, password: str):
"""Creates a database
Args:
database_name: the target database name.
username: the username
password: the password
"""
conn = psg.connect(host='127.0.0.1', user='postgres', password='admin')
cursor = conn.cursor()
conn.set_session(autocommit=True)
cursor.execute(f'DROP DATABASE IF EXISTS {database_name}')
cursor.execute(f'CREATE DATABASE {database_name} WITH ENCODING "utf8" TEMPLATE template0')
conn.close()
def create_table(conn, cursor):
for query in create_table_queries:
cursor.execute(query)
conn.commit()
conn.close()
def drop_tables(conn, cursor):
for query in drop_table_queries:
cursor.execute(query)
conn.commit()
conn.close()
# def run_task(task='create_tables'):
# """[summary]
# Args:
# task (str, optional): [description]. Defaults to 'create_tables'.
# """
# cursor, conn = connect_to_database()
# tasks = {'create_tables': create_table(conn, cursor), \
# 'drop_tables': drop_tables(conn, cursor)}
# tasks[task]
if __name__ == '__main__':
database_name = 'music_library'
username = 'postgres'
password = 'admin'
#create_database(database_name, username, password)
create_table() |
9edc52e38c8638524b6d9174eefa07228892ec13 | Irziii-Hasan/ttd | /MainMenu.py | 3,738 | 3.984375 | 4 | """
Game rules:
-The goal of blackjack is to beat the dealer's hand without going over 21.
-Face cards are worth 10. Aces are worth 1 or 11, whichever makes a better
hand.
-Each player starts with two cards, one of the dealer's cards is hidden
until the end.
-To 'Hit' is to ask for another card. To 'Stand' is to hold your total and
end your turn.
-If you go over 21 you bust, and the dealer wins regardless of the dealer's
hand.
-If you are dealt 21 from the start (Ace & 10), you got a blackjack.
-Dealer will hit until his/her cards total 17 or higher.
Instructions:
When the program starts running, it opens a main menu window with
2 buttons. One can close the window and exit the program and the other button
let's start the game itself. The Play button opens a new window where the game works.
the game is started by pressing the large image / button in the window, which
above reads DEAL. The player and dealer are then dealt
the first cards. The player has both cards visible and the dealer
again, the first card appears normally and the second shows only the back.
The program also has a function where the back of the card changes each time you play.
Even when the program is running. When the player and the dealer have
The cards dealt to the player have two options Hit or Stand. When you press Hit-
option the player gets a new card. The hit button can be pressed as long as
player score <= 21 but it doesn't always make sense to ask for a new one
cards but keep the current hand. This function can be performed by pressing
Stand button. Once the player has pressed the stand button, the dealer begins
turn. As the rules read the dealer must hit whenever his
the value of his hand is <= 16 and must be fixed when it is> 16. If neither is
"busted" i.e. the value of the hand has exceeded 21 so we see the dealer's turn
after which one has won. The winner can also be seen in special situations
in the past, for example, if either has "blackjack" or cards
the value is 21 when 2 cards are dealt to both. When the program is
announced the winner can the player press the "new game" button that appears
on the screen to start a new game.
"""
from tkinter import *
from Game import Blackjack
class Mainmenu:
# the main menu window is created in init
def __init__(self):
self.__mainmenu = Tk()
imagename1 = "images/Menu.png"
self.__canvas = Canvas(self.__mainmenu, width=1230, height=762)
self.__canvas.pack()
img1 = PhotoImage(file=imagename1)
self.__canvas.background = img1
self.__canvas.create_image(0, 0, anchor=NW, image=img1)
self.__img2 = PhotoImage(file="images/Play.png")
self.__img3 = PhotoImage(file="images/Quit.png")
self.__playbutton = Button(
self.__canvas, justify=LEFT, command=self.play
)
self.__playbutton.config(image=self.__img2)
self.__playbutton.place(x=420, y=480)
self.__quitbutton = Button(
self.__canvas, command=self.quit, justify=LEFT
)
self.__quitbutton.config(image=self.__img3)
self.__quitbutton.place(x=420, y=620)
def play(self):
"""
Destroys the main menu window and opens the game window
:return:
"""
self.__mainmenu.destroy()
Blackjack(Tk()).start()
def quit(self):
"""
Destroys the main menu window
:return:
"""
self.__mainmenu.destroy()
def start(self):
"""
Open the main menu window
:return:
"""
self.__mainmenu.mainloop()
def main():
Mainmenu().start()
if __name__ == "__main__":
main()
|
8d518deff2e20738be27d935dde0a2f63021c251 | gonium/statsintro | /Code3/pythonFunction.py | 817 | 3.84375 | 4 | '''Demonstration of a Python Function
author: thomas haslwanter, date: May-2015
'''
import numpy as np
def incomeAndExpenses(data):
'''Find the sum of the positive numbers, and the sum of the negative ones.'''
income = np.sum(data[data>0])
expenses = np.sum(data[data<0])
return (income, expenses)
if __name__=='__main__':
testData = np.array([-5, 12, 3, -6, -4, 8])
# If only real banks would be so nice ;)
if testData[0] < 0:
print('Your first transaction was a loss, and will be dropped.')
testData = np.delete(testData, 0)
else:
print('Congratulations: Your first transaction was a gain!')
(myIncome, myExpenses) = incomeAndExpenses(testData)
print('You have earned {0:5.2f} EUR, and spent {1:5.2f} EUR.'.format(myIncome, -myExpenses))
|
f2bc3ca82085bcc512b5a69c878c1c5159371267 | pyotel/tensorflow_example | /Day_02_02_slicing.py | 522 | 3.71875 | 4 | # Day_02_02_slicing.py
a = [1, 3, 5, 7, 9, 2, 4, 6, 8, 0]
print(a[0], a[-1])
print(a[3:7]) # 시작, 종료
print(a[0:len(a)//2])
print(a[len(a)//2:len(a)])
print(a[:len(a)//2])
print(a[len(a)//2:])
# 문제
# 짝수 번째만 출력해 보세요.
# 홀수 번째만 출력해 보세요.
# 거꾸로 출력해 보세요.
print(a[::])
print(a[::2])
print(a[1::2])
print(a[3:4])
print(a[3:3])
print(a[len(a)-1:0:-1])
print(a[-1:0:-1])
print(a[-1:-1:-1])
print(a[-1::-1])
print(a[::-1])
|
f476ccc1026447d2f41ca07d5c5e6de5468018c6 | jonathf/adventofcode | /2019/06/run.py | 7,045 | 4.21875 | 4 | """
--- Day 6: Universal Orbit Map ---
You've landed at the Universal Orbit Map facility on Mercury. Because
navigation in space often involves transferring between orbits, the orbit maps
here are useful for finding efficient routes between, for example, you and
Santa. You download a map of the local orbits (your puzzle input).
Except for the universal Center of Mass (COM), every object in space is in
orbit around exactly one other object. An orbit looks roughly like this:
\
\
|
|
AAA--> o o <--BBB
|
|
/
/
In this diagram, the object BBB is in orbit around AAA. The path that BBB takes
around AAA (drawn with lines) is only partly shown. In the map data, this
orbital relationship is written AAA)BBB, which means "BBB is in orbit around
AAA".
Before you use your map data to plot a course, you need to make sure it wasn't
corrupted during the download. To verify maps, the Universal Orbit Map facility
uses orbit count checksums - the total number of direct orbits (like the one
shown above) and indirect orbits.
Whenever A orbits B and B orbits C, then A indirectly orbits C. This chain can
be any number of objects long: if A orbits B, B orbits C, and C orbits D, then
A indirectly orbits D.
For example, suppose you have the following map:
COM)B
B)C
C)D
D)E
E)F
B)G
G)H
D)I
E)J
J)K
K)L
Visually, the above map of orbits looks like this:
G - H J - K - L
/ /
COM - B - C - D - E - F
\
I
In this visual representation, when two objects are connected by a line, the
one on the right directly orbits the one on the left.
Here, we can count the total number of orbits as follows:
- D directly orbits C and indirectly orbits B and COM, a total of 3 orbits.
- L directly orbits K and indirectly orbits J, E, D, C, B, and COM, a total
of 7 orbits.
- COM orbits nothing.
The total number of direct and indirect orbits in this example is 42.
What is the total number of direct and indirect orbits in your map data?
--- Part Two ---
Now, you just need to figure out how many orbital transfers you (YOU) need to
take to get to Santa (SAN).
You start at the object YOU are orbiting; your destination is the object SAN is
orbiting. An orbital transfer lets you move from any object to an object
orbiting or orbited by that object.
For example, suppose you have the following map:
COM)B
B)C
C)D
D)E
E)F
B)G
G)H
D)I
E)J
J)K
K)L
K)YOU
I)SAN
Visually, the above map of orbits looks like this:
YOU
/
G - H J - K - L
/ /
COM - B - C - D - E - F
\
I - SAN
In this example, YOU are in orbit around K, and SAN is in orbit around I. To
move from K to I, a minimum of 4 orbital transfers are required:
- K to J
- J to E
- E to D
- D to I
Afterward, the map of orbits looks like this:
G - H J - K - L
/ /
COM - B - C - D - E - F
\
I - SAN
\
YOU
What is the minimum number of orbital transfers required to move from the
object YOU are orbiting to the object SAN is orbiting? (Between the objects
they are orbiting - not between YOU and SAN.)
"""
from typing import Dict, List, Tuple
from collections import defaultdict
def count_orbits(
name: str,
graph: Dict[str, List[str]],
parent_count: int = 0,
) -> int:
"""
Recursively count the number of direct and indirect orbits.
Simple sum of itself and sum of its children, where each child is worth one
more than the parent.
Args:
name:
Name of the current item.
graph:
A one-to-many directed graph where keys are name of parents, and
values are names of all its children.
parent_count:
The number of direct and indirect orbits to current item.
Returns:
The sum of all direct and indirect orbits for all (connected) items in
`graph`.
Examples:
>>> graph = {"COM": ["B"], "B": ["C", "G"], "G": ["H"], "H": [],
... "C": ["D"], "D": ["E", "I"], "I": ["SAN"], "SAN": [],
... "E": ["F", "J"], "F": [], "J": ["K"],
... "K": ["L", "YOU"], "L": [], "YOU": []}
>>> count_orbits("COM", graph=graph)
54
>>> count_orbits("E", graph=graph)
10
>>> count_orbits("I", graph=graph)
1
"""
return sum(count_orbits(child, graph, parent_count+1)
for child in graph[name]) + parent_count
def find_santa(name: str, graph: Dict[str, List[str]]) -> Tuple[str, int]:
"""
Recursively locate items "YOU" and "SAN" and sum up the number of transfers
needed between them.
Args:
name:
Name of the current item.
graph:
A one-to-many directed graph where keys are name of parents, and
values are names of all its children.
Returns:
status:
String representing what has been found. Either "" (nothing is
found), "SAN" (Santa is found), "YOU" (you are found), or "SANYOU"
(both you and Santa are found).
count:
If both Santa and you are found, then return the number of orbital
transfers needed to get you and santa in the same orbit. If only
one of them are found, return the number of orbital transfers back
to start. Else return 0.
Examples:
>>> graph = {"COM": ["B"], "B": ["C", "G"], "G": ["H"], "H": [],
... "C": ["D"], "D": ["E", "I"], "I": ["SAN"], "SAN": [],
... "E": ["F", "J"], "F": [], "J": ["K"], "K": ["L", "YOU"],
... "L": [], "YOU": []}
>>> find_santa("COM", graph)
('SANYOU', 4)
>>> find_santa("E", graph)
('YOU', 3)
>>> find_santa("I", graph)
('SAN', 1)
>>> find_santa("G", graph)
('', 0)
"""
# Leaf handle
if not graph[name]:
# only consider YOU and SAN
status = name if name in ("SAN", "YOU") else ""
return status, 0
# gather results from children
statuses, counts = zip(*[
find_santa(child, graph) for child in graph[name]])
status = "".join(sorted(statuses))
# add to count only if SAN or YOU is found, but not both
count = sum(counts) + (status in ("SAN", "YOU"))
return status, count
if __name__ == "__main__":
GRAPH = defaultdict(list)
with open("input") as src:
for line in src.read().strip().split():
center, periphery = line.split(")")
graph[center].append(periphery)
print("solution part 1:", count_orbits("COM", GRAPH))
# solution part 1: 117672
print("solution part 2:", find_santa("COM", GRAPH)[1])
# solution part 2: 277
|
cf31bb2cfe70b1bb00ba4045a1482ac568f76fa5 | jonathf/adventofcode | /2019/04/run.py | 3,597 | 4.125 | 4 | """
--- Day 4: Secure Container ---
You arrive at the Venus fuel depot only to discover it's protected by
a password. The Elves had written the password on a sticky note, but someone
threw it out.
However, they do remember a few key facts about the password:
* It is a six-digit number.
* The value is within the range given in your puzzle input.
* Two adjacent digits are the same (like 22 in 122345).
* Going from left to right, the digits never decrease; they only ever
increase or stay the same (like 111123 or 135679).
Other than the range rule, the following are true:
* 111111 meets these criteria (double 11, never decreases).
* 223450 does not meet these criteria (decreasing pair of digits 50).
* 123789 does not meet these criteria (no double).
How many different passwords within the range given in your puzzle input meet
these criteria?
--- Part Two ---
An Elf just remembered one more important detail: the two adjacent matching
digits are not part of a larger group of matching digits.
Given this additional criterion, but still ignoring the range rule, the
following are now true:
* 112233 meets these criteria because the digits never decrease and all
repeated digits are exactly two digits long.
* 123444 no longer meets the criteria (the repeated 44 is part of a larger
group of 444).
* 111122 meets the criteria (even though 1 is repeated more than twice, it
still contains a double 22).
How many different passwords within the range given in your puzzle input meet
all of the criteria?
Your puzzle input is 357253-892942.
"""
from typing import Iterator
def increasing_numbers(start: int, stop: int) -> Iterator[str]:
"""
Iterate all numbers in a range that is increasing in digits.
Args:
start:
The first number to check in range.
stop:
The last number (inclusive) to check.
Yields:
Numbers with increasing digits, represented as strings.
Examples:
>>> list(increasing_numbers(60, 80))
['66', '67', '68', '69', '77', '78', '79']
>>> list(increasing_numbers(895, 999))
['899', '999']
"""
for number in range(start, stop+1):
number = str(number)
consecutives = zip(number[:-1], number[1:])
if all(int(digit1) <= int(digit2) for digit1, digit2 in consecutives):
yield number
def part1(start: int, stop: int) -> int:
"""Do part 1 of the assignment."""
count = 0
for number in increasing_numbers(start, stop):
consecutives = zip(number[:-1], number[1:])
count += any(digit1 == digit2 for digit1, digit2 in consecutives)
return count
def part2(start: int, stop: int) -> int:
"""Do part 2 of the assignment."""
count = 0
for number in increasing_numbers(start, stop):
consecutive_digits = zip(number[:-1], number[1:])
matches = [digit1 == digit2 for digit1, digit2 in consecutive_digits]
# Pad values to allow for consecutive numbers at the beginning and end of number.
matches = [False] + matches + [False]
consecutive_matches = zip(matches[:-2], matches[1:-1], matches[2:])
# A match surrounded by non-matches.
count += any(triplet == (False, True, False)
for triplet in consecutive_matches)
return count
if __name__ == "__main__":
START = 357253
STOP = 892942
print("solution part 1:", part1(START, STOP))
# solution part 1: 530
print("solution part 2:", part2(START, STOP))
# solution part 2: 324
|
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()
|
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)
|
1723f2e6d0885e6abc7dadf890fef8fd63062ae4 | William-McKee/udacity-data-analyst | /Enron_Fraud_POI_Identifier/explore_dataset.py | 3,896 | 3.703125 | 4 | """
Explore basic information about the data set
"""
import numpy as np
def explore_basics(dataset):
'''Print basic statistics about dataset'''
print("Data Set Basics")
print("Number of employees/vendors? ", len(dataset))
print("Number of persons of interest (POIs)? ", get_feature_valid_points_count(dataset, 'poi', 0))
print("How many features?", get_feature_count(dataset))
def get_feature_count(dataset):
'''How many features?'''
dataset_keys = dataset.keys()
#dataset_values = dataset.values()
any_key = next(iter(dataset_keys))
return len(dataset[any_key])
def get_feature_valid_points_count(dataset, feature, bad_value):
'''
How many points in data set?
dataset: dictionary containing list of people, where each person is represented by dictionary
feature: feature for which to find valid data points
bad_value: for valid point, feature != this value
'''
count=0
dataset_keys = dataset.keys()
for item in dataset_keys:
if dataset[item][feature] != bad_value:
count += 1
return count
def get_bad_value(feature):
'''Return bad value for feature'''
if feature == 'poi':
return 0
else:
return 'NaN'
def explore_features(dataset):
'''Get and print count of all features of dataset'''
# Get the list of features
dataset_keys = dataset.keys()
any_key = next(iter(dataset_keys))
features = dataset[any_key].keys()
# Loop through features
for feature in features:
bad_value = get_bad_value(feature)
count = get_feature_valid_points_count(dataset, feature, bad_value)
print(str(feature) + ": " + str(count))
def explore_metrics(dataset):
'''Get and print metrics of all features of dataset'''
# Get the list of features
dataset_keys = dataset.keys()
any_key = next(iter(dataset_keys))
features = dataset[any_key].keys()
# Loop through features
for feature in features:
feature_list = []
bad_value = get_bad_value(feature)
for item in dataset:
if dataset[item][feature] != bad_value:
feature_list.append(dataset[item][feature])
np_feature = np.array(feature_list)
if (feature != 'email_address' and np_feature.size > 0):
print(feature + ": " + str(np_feature.size) + " / " + str(np_feature.min()) + " / " + str(np_feature.mean()) + " / " + str(np_feature.max()))
else:
print(feature + ": 0 / 0.000 / 0.000 / 0.000")
def dataset_basics(dataset):
'''Explore top level information about the dataset,
including POI and non-POI'''
# Print dataset information
print("\n")
explore_basics(dataset)
print("\n")
print("How many known values for each feature?")
explore_features(dataset)
# Split data set into POI and non-POI
poi_dataset = {}
nonpoi_dataset = {}
for item in dataset:
if dataset[item]['poi'] == 1:
poi_dataset[item] = dataset[item]
else:
nonpoi_dataset[item] = dataset[item]
print("\n")
print("How many known values for each feature for POIs?")
explore_features(poi_dataset)
print("\n")
print("How many known values for each feature for non-POIs?")
explore_features(nonpoi_dataset)
print("\n")
print("### METRICS ###")
print("Field: Min / Mean / Max")
explore_metrics(dataset)
print("\n")
print("### POI METRICS ###")
print("Field: Min / Mean / Max")
explore_metrics(poi_dataset)
print("\n")
print("### NON-POI METRICS ###")
print("Field: Min / Mean / Max")
explore_metrics(nonpoi_dataset)
print("\n") |
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))
|
7320949169efef2b15c71d9fcc44eb366b4fdc3c | JankovicNikola/python | /basics/settype.py | 312 | 3.53125 | 4 | s={10,20,30,'XYZ', 10,20,10}
print(s)
print(type(s))
s.update([88,99])
print(s)
#print(s*3)
s.remove (30)
print(s)
#nema duplikata, ne radi indexind, slicing, repetition ali rade update i remove1
f=frozenset(s)
f.update(20)
#frozenset ne moze update i remove, nema menjanja samo gledanje
|
ba3a81a69f5c609bdae6c134e0e08916f107cea6 | webappDEV0001/python_datetime_util | /utils.py | 622 | 3.546875 | 4 | from datetime import datetime, timedelta
def datetime_converter(value):
if isinstance(value, datetime):
return value.strftime('%Y-%m-%dT%H:%M:%S.%fZ')
def normalize_seconds(seconds):
seconds = int(seconds)
(days, remainder) = divmod(seconds, 86400)
(hours, remainder) = divmod(remainder, 3600)
(minutes, seconds) = divmod(remainder, 60)
if days > 0:
return f'{days} days {hours} hrs'
elif hours > 0:
return f'{hours} hrs {minutes} minutes'
elif minutes > 0:
return f'{minutes} minutes {seconds} seconds'
else:
return f'{seconds} seconds'
|
06788574fddaacde210956943be373cfaac91fa9 | zolars/dashboard-ocr | /packages/opencv/main.py | 11,746 | 3.671875 | 4 | # -*- coding: UTF-8 -*-
import cv2
import numpy as np
import math
from datetime import datetime as dt
def avg_circles(circles, b):
avg_x = 0
avg_y = 0
avg_r = 0
for i in range(b):
# optional - average for multiple circles (can happen when a dashboard is at a slight angle)
avg_x = avg_x + circles[0][i][0]
avg_y = avg_y + circles[0][i][1]
avg_r = avg_r + circles[0][i][2]
avg_x = int(avg_x / (b))
avg_y = int(avg_y / (b))
avg_r = int(avg_r / (b))
return avg_x, avg_y, avg_r
def dist_2_pts(x1, y1, x2, y2):
return np.sqrt((x2 - x1)**2 + (y2 - y1)**2)
def calibrate(img):
'''
This function should be run using a test image in order to calibrate the range available to the dial as well as the
units. It works by first finding the center point and radius of the dashboard. Then it draws lines at hard coded intervals
(separation) in degrees. It then prompts the user to enter position in degrees of the lowest possible value of the dashboard,
as well as the starting value (which is probably zero in most cases but it won't assume that). It will then ask for the
position in degrees of the largest possible value of the dashboard. Finally, it will ask for the units. This assumes that
the dashboard is linear (as most probably are).
It will return the min value with angle in degrees (as a tuple), the max value with angle in degrees (as a tuple),
and the units (as a string).
'''
# cv2.imwrite('./out/image_origin.jpg', img)
height, width = img.shape[:2]
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) # convert to gray
# gray = cv2.GaussianBlur(gray, (5, 5), 0)
# gray = cv2.medianBlur(gray, 5)
# for testing, output gray image
# cv2.imwrite('./out/%s-bw.%s' % (0, 'jpg'), gray)
# apply thresholding which helps for finding lines
mean_value = gray.mean()
if mean_value >= 200:
hist = cv2.calcHist([gray], [0], None, [256], [0, 256])
min_value, max_value, min_index, max_index = cv2.minMaxLoc(hist)
ret, image_edge = cv2.threshold(gray,
int(max_index[1]) - 7, 255,
cv2.THRESH_BINARY_INV)
else:
mean, stddev = cv2.meanStdDev(gray)
ret, image_edge = cv2.threshold(gray, mean_value, 255,
cv2.THRESH_BINARY_INV)
# image_edge = cv2.adaptiveThreshold(gray, 255,
# cv2.ADAPTIVE_THRESH_GAUSSIAN_C,
# cv2.THRESH_BINARY_INV, 11,
# 0)
# found Hough Lines generally performs better without Canny / blurring, though there were a couple exceptions where it would only work with Canny / blurring
image_edge = cv2.medianBlur(image_edge, 5)
image_edge = cv2.Canny(image_edge, 50, 150)
image_edge = cv2.GaussianBlur(image_edge, (5, 5), 0)
cv2.imwrite('./out/image_edge.jpg', image_edge)
# detect circles
# restricting the search from 35-48% of the possible radii gives fairly good results across different samples. Remember that
# these are pixel values which correspond to the possible radii search range.
# 霍夫圆环检测
# image:8位, 单通道图像
# method:定义检测图像中圆的方法. 目前唯一实现的方法cv2.HOUGH_GRADIENT.
# dp:累加器分辨率与图像分辨率的反比. dp获取越大, 累加器数组越小.
# minDist:检测到的圆的中心, (x,y) 坐标之间的最小距离. 如果minDist太小, 则可能导致检测到多个相邻的圆. 如果minDist太大, 则可能导致很多圆检测不到.
# param1:用于处理边缘检测的梯度值方法.
# param2:cv2.HOUGH_GRADIENT方法的累加器阈值. 阈值越小, 检测到的圈子越多.
# minRadius:半径的最小大小 (以像素为单位).
# maxRadius:半径的最大大小 (以像素为单位).
circles = cv2.HoughCircles(image_edge, cv2.HOUGH_GRADIENT, 1, 20,
np.array([]), 100, 50, int(height * 0.35),
int(height * 0.48))
# average found circles, found it to be more accurate than trying to tune HoughCircles parameters to get just the right one
a, b, c = circles.shape
#获取圆的坐标x,y和半径r
x, y, r = avg_circles(circles, b)
return x, y, r
def draw_calibration(img, x, y, r):
# draw center and circle
cv2.circle(img, (x, y), r, (0, 0, 255), 3, cv2.LINE_AA) # draw circle
cv2.circle(img, (x, y), 2, (0, 255, 0), 3,
cv2.LINE_AA) # draw center of circle
# for calibration, plot lines from center going out at every 10 degrees and add marker
separation = 10.0 # in degrees
interval = int(360 / separation)
p1 = np.zeros((interval, 2)) # set empty arrays
p2 = np.zeros((interval, 2))
p_text = np.zeros((interval, 2))
for i in range(0, interval):
for j in range(0, 2):
if (j % 2 == 0):
p1[i][j] = x + 0.5 * r * np.cos(
separation * i * math.pi / 180) # point for lines
else:
p1[i][j] = y + 0.5 * r * np.sin(separation * i * math.pi / 180)
text_offset_x = 10
text_offset_y = 5
for i in range(0, interval):
for j in range(0, 2):
if (j % 2 == 0):
p2[i][j] = x + r * np.cos(separation * i * math.pi / 180)
p_text[i][j] = x - text_offset_x + 1.1 * r * np.cos(
(separation) * (i + 9) * math.pi / 180
) # point for text labels, i+9 rotates the labels by 90 degrees
else:
p2[i][j] = y + r * np.sin(separation * i * math.pi / 180)
p_text[i][j] = y + text_offset_y + 1.1 * r * np.sin(
(separation) * (i + 9) * math.pi / 180
) # point for text labels, i+9 rotates the labels by 90 degrees
# add the lines and labels to the image
for i in range(0, interval):
cv2.line(img, (int(p1[i][0]), int(p1[i][1])),
(int(p2[i][0]), int(p2[i][1])), (0, 255, 0), 2)
cv2.putText(img, '%s' % (int(i * separation)),
(int(p_text[i][0]), int(p_text[i][1])),
cv2.FONT_HERSHEY_SIMPLEX, 0.8, (0, 0, 0), 1, cv2.LINE_AA)
return img
def get_current_value(img, min_angle, max_angle, min_value, max_value, x, y,
r):
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# apply thresholding which helps for finding lines
mean_value = gray.mean()
if mean_value >= 200:
hist = cv2.calcHist([gray], [0], None, [256], [0, 256])
min_value, max_value, min_index, max_index = cv2.minMaxLoc(hist)
ret, image_edge = cv2.threshold(gray,
int(max_index[1]) - 7, 255,
cv2.THRESH_BINARY_INV)
else:
mean, stddev = cv2.meanStdDev(gray)
ret, image_edge = cv2.threshold(gray, mean_value + 15, 255,
cv2.THRESH_BINARY_INV)
# image_edge = cv2.adaptiveThreshold(gray, 255,
# cv2.ADAPTIVE_THRESH_GAUSSIAN_C,
# cv2.THRESH_BINARY_INV, 11,
# 0)
# for testing, show image after thresholding
# cv2.imwrite('./out/%s-bin.%s' % (0, 'jpg'), image_edge)
# found Hough Lines generally performs better without Canny / blurring, though there were a couple exceptions where it would only work with Canny / blurring
# image_edge = cv2.medianBlur(image_edge, 5)
# image_edge = cv2.Canny(image_edge, 50, 150)
# image_edge = cv2.GaussianBlur(image_edge, (5, 5), 0)
# find lines
minLineLength = 10
maxLineGap = 0
lines = cv2.HoughLinesP(
image=image_edge,
rho=3,
theta=np.pi / 180,
threshold=100,
minLineLength=minLineLength,
maxLineGap=0
) # rho is set to 3 to detect more lines, easier to get more then filter them out later
# for testing purposes, show all found lines
# for i in range(0, len(lines)):
# for x1, y1, x2, y2 in lines[i]:
# cv2.line(img, (x1, y1), (x2, y2), (0, 255, 0), 2)
# cv2.imwrite('./out/%s-lines-test.%s' % (0, 'jpg'), img)
# remove all lines outside a given radius
final_line_list = []
diff1LowerBound = 0 # diff1LowerBound and diff1UpperBound determine how close the line should be from the center
diff1UpperBound = 0.5
diff2LowerBound = 0 # diff2LowerBound and diff2UpperBound determine how close the other point of the line should be to the outside of the dashboard
diff2UpperBound = 2
for i in range(0, len(lines)):
for x1, y1, x2, y2 in lines[i]:
# x, y is center of circle
diff1 = dist_2_pts(x, y, x1, y1)
diff2 = dist_2_pts(x, y, x2, y2)
# set diff1 to be the smaller (closest to the center) of the two, makes the math easier
if (diff1 > diff2):
temp = diff1
diff1 = diff2
diff2 = temp
# check if line is within an acceptable range
if (((diff1 < diff1UpperBound * r) and
(diff1 > diff1LowerBound * r) and
(diff2 < diff2UpperBound * r))
and (diff2 > diff2LowerBound * r)):
line_length = dist_2_pts(x1, y1, x2, y2)
# add to final list
final_line_list.append([x1, y1, x2, y2])
# testing only, show all lines after filtering
max_length = 0
xx1, yy1, xx2, yy2 = 0, 0, 0, 0
for final_line in final_line_list:
x1 = final_line[0]
y1 = final_line[1]
x2 = final_line[2]
y2 = final_line[3]
if dist_2_pts(x1, y1, x2, y2) > max_length:
xx1, yy1, xx2, yy2 = x1, y1, x2, y2
max_length = dist_2_pts(x1, y1, x2, y2)
# cv2.line(img, (x1, y1), (x2, y2), (0, 0, 255), 2)
# assumes the longest line is the best one
x1, y1, x2, y2 = xx1, yy1, xx2, yy2
# cv2.line(img, (x1, y1), (x2, y2), (255, 0, 0), 2)
# cv2.imwrite('./out/%s-lines-filter.%s' % (0, 'jpg'), img)
# find the farthest point from the center to be what is used to determine the angle
dist_pt_0 = dist_2_pts(x, y, x1, y1)
dist_pt_1 = dist_2_pts(x, y, x2, y2)
if (dist_pt_0 > dist_pt_1):
x_begin, x_end = x1, x2
y_begin, y_end = y1, y2
else:
x_begin, x_end = x2, x1
y_begin, y_end = y2, y1
x_angle = x_begin - x_end
y_angle = y_end - y_begin
# take the arc tan of y/x to find the angle
res = np.arctan(np.divide(float(y_angle), float(x_angle)))
# these were determined by trial and error
res = np.rad2deg(res)
if x_angle > 0 and y_angle > 0: # in quadrant I
final_angle = 270 - res
elif x_angle < 0 and y_angle > 0: # in quadrant II
final_angle = 90 - res
elif x_angle < 0 and y_angle < 0: # in quadrant III
final_angle = 90 - res
elif x_angle > 0 and y_angle < 0: # in quadrant IV
final_angle = 270 - res
else:
raise UserWarning('Pointer was not detected.')
old_min = float(min_angle)
old_max = float(max_angle)
new_min = float(min_value)
new_max = float(max_value)
old_value = final_angle
old_range = (old_max - old_min)
new_range = (new_max - new_min)
new_value = (((old_value - old_min) * new_range) / old_range) + new_min
return new_value
if __name__ == '__main__':
pass
|
078782bd9138dd1d925474a07b829431101ac648 | vsehgal1/automate_boring_stuff_python | /ch7/strip.py | 589 | 3.921875 | 4 | # strip.py
# automatetheboringstuff.com Chapter 7
# Vikram Sehgal
import re
def strip(strn, chars):
if chars == '':
reg_space = re.compile(r'^(\s*)(\S*)(\s*)$') #regex for whitespace
new_strn = reg_space.search(strn).group(2)
return new_strn
else:
reg = re.compile(r'(^[%s]+)(.+?)([%s]+)$' % (chars,chars)) #regex for character list
new_strn = reg.search(strn).group(2)
return new_strn
if __name__ == '__main__':
strn = input('Enter string: ')
chars = input('Enter char to strip (Optional): ')
print(strip(strn, chars))
|
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))
|
aa4f667f7f4dcb01282041cb3231caf2accaa0d3 | maheshphutane/stegonography | /stegonography.py | 998 | 3.765625 | 4 | from PIL import Image
import stepic
def encode():
img = input("Enter image name(with extension): ")
image = Image.open(img)
data = input("Enter data to be encoded : ")
if (len(data) == 0):
raise ValueError('Data is empty')
#converting string to bytes format
data1 = bytes(data, encoding="ascii")
im1 = stepic.encode(image, data1)
im1.save( input("Enter the name of new image:- "))
def decode():
img = input("Enter image name(with extension):- ")
image = Image.open(img)
data1 = stepic.decode(image)
return data1
def main():
a = int(input(":: Welcome to Steganography ::\n"
"1. Encode\n2. Decode\n"))
if (a == 1):
encode()
elif (a == 2):
print("Decoded word- " + decode())
else:
raise Exception("Enter correct input")
# Driver Code
if __name__ == '__main__':
# Calling main function
main()
|
06779614e3f152ca83124f26e610af400b21c1d0 | cegasa89/Python-Courses | /data/dataFrames.py | 885 | 3.5 | 4 | import numpy as np
import pandas as pd
A = [1, 2, 3, 4]
B = [5, 6, 7, 8]
C = [9, 0, 1, 2]
D = [3, 4, 5, 6]
E = [7, 8, 9, 0]
df = pd.DataFrame([A, B, C, D, E], ['a', 'b', 'c', 'd', 'e'], ['W', 'X', 'Y', 'Z'])
# create a new column
print("-----------------------------")
df['P'] = df['Y'] + df['Z']
# remove a row
print("-----------------------------")
df = df.drop('e')
# remove a column
print("-----------------------------")
df1 = df.drop('P' , axis = 1)
print(df1.loc['a'])
print(df1.loc['a','Y'])
#condicional acessing
print("-----------------------------")
print( df > 3)
print( df[df['W'] > 8][['W']])
d = {'a':[1,2,3,4,5],'b':[6,7,8,9,np.nan],'c':[0,1,2,np.nan,np.nan]}
df = pd.DataFrame(d)
print(df)
#drop all row with any na
print("-----------------------------")
print(df.dropna(axis=0))
print(df.fillna(1))
#missing data
print("-----------------------------")
|
2d28873dbc86e5dbdac27ffac8e42c1c1d96524b | Chahbouni-Chaimae/Atelier1-2 | /python/fact.py | 341 | 3.953125 | 4 | def factorial(x):
if x==1:
return 1
else:
return(x*factorial(x-1))
num=5
print("le factorial de ", num, "est" , factorial(num))
def somme_factorial(s,x):
s=0
s=s+(factorial(x)/x)
n=int(input("entrez un nombre:"))
for x in range(0,n-1):
print("la somme des séries est:" , somme_factorial(x)) |
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)) |
be3cee09655a2fc4851125186fbb587d63f02f97 | cathoderay/gtsimulator | /util/geometry.py | 2,165 | 3.859375 | 4 | import random
class Element:
def __init__(self, center, size):
"""Basic element of the world.
Size zero is the special case where the element is a pixel."""
self.center = center
self.centerx = center[0]
self.centery = center[1]
self.left = center[0] - size
self.right = center[0] + size
self.top = center[1] - size
self.bottom = center[1] + size
def distance(self, e):
"""Return Manhattam distance between 2 elements."""
distance = 0
correction = 0
if e.left > self.right:
distance += e.left - self.right - 1
correction += 1
if e.right < self.left:
distance += self.left - e.right - 1
correction += 1
if e.top > self.bottom:
distance += e.top - self.bottom - 1
correction += 1
if e.bottom < self.top:
distance += self.top - e.bottom - 1
correction += 1
if correction == 2:
distance += 1
#case where it collides
if correction == 0:
return -1
return distance
def direction_to(self, e):
"""Return a valid direction to another Element"""
delta_x = delta_y = 0
if self.right < e.left:
delta_x += 1
if e.right < self.left:
delta_x -= 1
if self.top > e.bottom:
delta_y -= 1
if self.bottom < e.top:
delta_y += 1
if delta_y != 0 and delta_x != 0:
return random.choice([[delta_x, 0], [0, delta_y]])
return [delta_x, delta_y]
def collide(self, e):
"""Check for colllision between 2 Elements"""
if self.distance(e) < 0:
return True
return False
class Vector:
@classmethod
def random_direction(cls):
"""Return a valid direction randomly"""
return random.choice([[1, 0], [0, 1], [-1, 0], [0, -1] ])
@classmethod
def add(cls, v1, v2):
"""Return the sum of 2 vectors"""
return [v1[0] + v2[0], v1[1] + v2[1]]
|
0913ec4362f45464137b5b06569c14aadd126034 | minjjjae/pythoncode | /sqlite/sqliteclass.py | 2,212 | 3.734375 | 4 | import sqlite3
class Book:
def create_conn(self):
conn=sqlite3.connect('sqlite/my_books.db')
return conn
def create_table(self):
conn = self.create_conn()
c = conn.cursor()
sql = '''
create table if not exists books(
title text,
published_date text,
publisher text,
pages integer,
recommend integer
)'''
c.execute(sql)
conn.commit()
c.close()
conn.close()
def insert_book(self,item):
conn=self.create_conn()
c = conn.cursor()
sql='insert into books values(?,?,?,?,?)'
c.execute(sql,item)
conn.commit()
c.close()
conn.close()
def insert_books(self,items):
conn=self.create_conn()
c=conn.cursor()
sql='insert into books values(?,?,?,?,?)'
c.executemany(sql,items)
conn.commit()
c.close()
conn.close()
def all_books(self):
conn=self.create_conn()
c=conn.cursor()
sql='select * from books'
c.execute(sql)
books = c.fetchall()
#print(books)
return books
def one_book(self,title):
conn = self.create_conn()
c=conn.cursor()
sql='select * from books where title=?'
c.execute(sql,title)
book = c.fetchone()
return book
def select_book(self,title):
conn = self.create_conn()
c=conn.cursor()
sql='select * from books where title like ?'
c.execute(sql, title)
book = c.fetchone()
return book
if __name__ == '__main__':
dbo=Book()
dbo.create_table()
item=('데이터분석실무','2020-7-13','위키북스',300,10)
dbo.insert_book(item)
items=[
('빅데이터','2020-7-13','이지퍼블리싱',599,67),
('안드로이드','2020-7-14','삼성',128,8),
('spring','2020-7-15','위키북스',566,10)
]
dbo.insert_books(items)
dbo.all_books()
book =dbo.one_book(('안드로이드',))
print(book)
book = dbo.select_book(('%s%',))
print(book)
|
ce86f7c872f79a9aea96fff7dec144762f436d3e | sireesha98/siri | /siri.py | 210 | 3.875 | 4 | i=raw_input("")
p=['a','e','i','o','u','A','E','I','O','U']
if (i>='a' and i<='z' or i>='A' and i<='Z'):
if (i in p):
print("Vowel")
else:
print("Consonant")
else:
print("invalid")
|
941fe47ca8313a8f1329985bf58eda81771b8619 | ivanklimuk/py_crepe | /utils.py | 1,931 | 3.578125 | 4 | import string
import numpy as np
import pandas as pd
from keras.utils.np_utils import to_categorical
def load_train_data(path, labels_path=None):
'''
Load the train dataset with the labels:
- either as the second value in each row in the read_csv
- or as a separate file
'''
train_text = np.array(pd.read_csv(path, header=None))
if labels_path:
train_labels = np.array(pd.read_csv(labels_path, header=None))
else:
train_labels, train_text = train_text[:, 0], train_text[:, 1]
train_labels = to_categorical(train_labels)
return (train_text, train_labels)
def text_to_array(text, maxlen, vocabulary):
'''
Iterate over the loaded text and create a matrix of size (len(text), maxlen)
Each character is encoded into a one-hot array later at the lambda layer.
Chars not in the vocab are encoded as -1, into an all zero vector.
'''
text_array = np.zeros((len(text), maxlen), dtype=np.int)
for row, line in enumerate(text):
for column in range(min([len(line), maxlen])):
text_array[row, column] = vocabulary.get(line[column], -1) # if not in vocabulary_size, return -1
return text_array
def create_vocabulary_set(ascii=True, digits=True, punctuation=True):
'''
This alphabet is 69 chars vs. 70 reported in the paper since they include two
'-' characters. See https://github.com/zhangxiangxiao/Crepe#issues.
'''
alphabet = []
if ascii:
alphabet += list(string.ascii_lowercase)
if digits:
alphabet += list(string.digits)
if punctuation:
alphabet += list(string.punctuation) + ['\n']
alphabet = set(alphabet)
vocabulary_size = len(alphabet)
vocabulary = {}
reverse_vocabulary = {}
for ix, t in enumerate(alphabet):
vocabulary[t] = ix
reverse_vocabulary[ix] = t
return vocabulary, reverse_vocabulary, vocabulary_size, alphabet
|
a3035208563797b6d6e40fd0441b6bc51aba495b | PSY31170CCNY/Class | /Stephanie Bodden/Assignment 1.py | 661 | 3.609375 | 4 | class Person:
def __init__(self,firstname='', lastname='',email=''):
self.firstname = firstname
self.lastname = lastname
self.email = email
e=open("names.txt","r")
names=e.readlines()
for line in names:
#Decide if it's blank, name, or email line.
#If the length of line is zero than it's blank. (Skip it)(Continues loop)
if len (line)== 0:
continue
x=line.split()
if len (x)==2:
firstname=x[0]
lastname=x[1]
p=Person(firstname, lastname, email='')
if len (x)==1
p.email=x
email=x[1]
p=Person(firstname, lastname, email)
|
d17f62b713eec8210603b4451bb656fe5b60d6fa | PSY31170CCNY/Class | /Daniel Coumswang/Assignment set 1 part 1.py | 305 | 3.796875 | 4 | #Assignment set 1 part 1
x = True
while x:
print("Please enter your information.")
A = input("Enter your first name:")
b = input("Enter your last name:")
c = input("Enter your Email:")
d = open('emaillist.csv','a')
e = '"'+A+'", "' +b+'", "'+c+"\n"
d.write(e)
|
ac6d6abe694e280fdf08930ec914e1b08fe75498 | PSY31170CCNY/Class | /Jamin Chowdhury/Assignment 1.py | 1,247 | 3.96875 | 4 | #Locate and Create
#----------------------------------------
Destination = "C:/Users/Jamin/Desktop/PythAss1/"
Filename = "Email List.csv"
File = Destination + Filename
#----------------------------------------
#Header
#----------------------------------------
z1 = ('First Name')
z2 = ('Last Name')
z3 = ('Email Address')
v0 = str('"'+z1+'",'+'"'+z2+'",'+z3+'\n')
f = open(File,"a") #append
f.writelines(v0)
#----------------------------------------
#Program
#----------------------------------------
List = True
while List:
v1 = input("Would you like to contribute to the Email List? Y/N")
if v1 in 'Nono':
print("It would be really helpful if you did!")
while v1 in "Yesyes":
v2 = input("Person's last name.")
if v2 == "":
break
v3 = input("Person's first name.")
if v3 == "":
break
v4 = input("Person's email address.")
if v4 == "":
break
v5 = str('"'+v3+'",'+'"'+v2+'",'+v4+'\n')
# First Name, Last Name, Email Address formatting
f = open(File,"a") #append
f.writelines(v5)
f.close()
continue
#------------------------------------------
|
0a0b49b0bbaf60cc0a85dcc877dea0f6bd44fa07 | PSY31170CCNY/Class | /Breona Couloote/assignment1.py | 2,751 | 4.0625 | 4 | #assignment
class Person:
def __init__(self,firstname='',lastname='',email=''):
self.firstname = firstname
self.lastname = lastname
self.email = email
def hello(self):
print("hi",self.name)
def askdata(self):
self.firstname = input("enter first name")
if self.firstname= ''
return
self.lastname = input("enter last name")
self.email = input ("enter email")
people=[]
while True:
p=Person()
p.askdata()
if p.firstname="":
break
people.append(p)
drive='C:/Users/bcouloo000/Desktop/'
e=open(drive+'emaillist.csv','a')
for member in people:
l='"'+member.name+'", "'+member.email+'"\n'
e.writelines(l)
e.close()
e=open(drive+'emaillist.csv','a')
print(".......\nread one line at a time and print it:")
print("each entry has a newline at the end, and the print function adds another one.")
for l in e:
print(l)
e.close()
print ("------\nthe whole file as a list:")
e=open(drive+'emaillist.csv','r')
emails=e.readlines()
print (emails)
e.close()
e=open(drive+'emaillist.csv','r')
peopledict = {}
for p in e:
print('text string of this line:',p)
print('length of text string:',len(p))
pvals = p.split(',')
print('Now the text string is made into a list separated by commas:',pvals)
print('The full read-in entry text line is now a list of',len(pvals),'items long')
peopledict[p[0]] = p[1]
e.close()
print("\nThe raw peopledict is:\n",peopledict)
print("---- now displayed by key-value pairs:")
for p in peopledict.keys():
print("lookup key:",p,"value:",peopledict[p][0:-1])
print('===\n')
n=''
while n == '':
n=input("Go ahead, enter a name to look up their data (or q to quit):")
if n in'Qq':
break
try:
print("Error: ",n,"not found in peopledict. Try again or q to quit.")
except:
print("Error: ",n,"not found in peopledict. Try again or q to quit.")
n=''
def getpersondata(data ={'lastname':'','firstname':'','email':''}):
fields=['lastname','firstname','email']
for field in fields:
if len(data[field]>0):
x=input("change "+field+ " from "+data[field]+"(Y/N)")
if x not in 'Yy':
continue
data[field]=input("enter the person's "+field )
return data
while True:
pname = input('enter the name of the person to find:')
pdata = persons[pname]
try:
pdata = persons[pname]
except:
addnew = input(pname+' not found. Add as new (Y/N)?')
if addnew in 'Yy':
persons[pname] = [pname]
else:
contnue
data=getpersondata(pdata)
|
b327a86ce9abee36e12397ef8de85a19217596fc | PSY31170CCNY/Class | /Jamin Chowdhury/Final Exam.py | 3,056 | 4.15625 | 4 |
#PSY31170 Winter Session 2019 Final Exam
1. Fix this expression without changing any numbers, so x evaluates to 28:
x = 7 * 2 **2
--------------------------------------
Answer: x = 7 * (2 **2)
#-----------------------------------------------------------------
2. initialize p correctly so it prints 10
p= ???
for x in range(3):
p = p + x
print(p)
--------------------------------------
Answer:
p = 7 #Initial value
p = p +x
p1 = 7 + 0 = 7
p2 = 7 + 1 = 8
p3 = 8 + 2 = 10
print(p) = 10
#-----------------------------------------------------------------
3. fix the syntax and logic errors in this code snippet so it prints 101
z= true
y=1
while z:
y+=10
if y = 100:
z=false
print(y)
------------
Answer:
z = True
y = 1
while z:
y += 10
print(y)
if y == 101:
z = False
#--------------------------------------------------------------------------
4. Using these variables with the built-in string function str.upper()
and string slicing, put an expression into the print statement that
outputs exactly this:
The quick brown fox jumps over the lazy dog named Rover
s=”the quick brown”
f=[‘animal’, ‘fox’, ‘puppy’]
j=’jumps over “Rover” the lazy dog’
print (?????)
-------------------------
Answer:
print(s + f[2] + j[3:5] + 'named' + j[2])
#---------------------------------------------------------------------
5. What command must be executed before you can use the the csv.reader()
function to read in a text file of values separated by commas?
Demonstrate by writing a very short program to read in a csv file
named “data.csv” using the csv.reader() function.
--------------
Answer:
File = FinalExam.csv
open(File, newline='') as csvfile:
datareader = csv.reader
#-----------------------------------------------------------------------
6. Debug this program so it runs correctly, print out the resulting file
with at least 6 users' data and upload the file to your github Class folder:
# finalexamproblem6.py
# Asks user for their information and adds it to a text file
while True
print(Enter your name,, address and phone, please)
f = open(“textfile.txt”,’w’)
name = ‘input(Your name’)
addr = input’((Your address’)
phone=’input(Your phone)’
f.writelines(name,add,phone)
f.close()
if name=’’:
break
Answer: -----------------------------------------------------------------
Answer:
Destination: "C:/Users/Jamin/Desktop/"
Filename: "Problem_6.txt/"
textfile = Destination + Filename
#Must create textfile before running the program.
print("Enter your name,, address and phone, please")
f = open(textfile, 'w')
name = input("Your name")
addr = input("Your address")
phone= input('Your phone')
f.writelines(name,add,phone)
f.close()
if name == "" :
break
|
9da6e7f67b9c9c6cb1ae477313bbd5faa3d39b63 | PSY31170CCNY/Class | /Ariell Lugo/Personclass.py | 3,906 | 4 | 4 | # Personclass.py
class Person:
def __init__(self,name=' ',address=' ',phone='',email=''):
self.name = name
self.address = address
self.phone = phone
self.email = email
def hello(self):
print("Hi there! My name is ",self.name)
Sally = Person('Sally','1 Any Way','123-4567','sally@gmail')
print(Sally.name)
Sally.hello()
#instantiate a Person in the variable Bob, named "Robert"
Bob = Person("Robert",'1234 Drive',email='bob@gmail')
Bob.hello()
#make a list of the People objects:
people=[Bob,Sally]
drive='/Downloads/Personclass.py
#write the name and emails of the people to a csv file for Excel:
e=open('/media/dave/PSY31170/emaillist.csv','w') #open the file
for member in people:
# construct the text line for each member:
# put the attributes in quotes separated by a comma,
# like this: "Dave","dave@gmail"
# add a newline at the end so each entry is on a new line
l='"' + member.name + '"' + ',"' +member.email+ '"\n'
e.writelines(l)
e.close()
# now read the file and see what it looks like:
e=open('/media/dave/PSY31170/emaillist.csv','r')
print("......\nread one line at a time and print it:")
print("each entry has a newline at the end, and the print function adds another one.")
for l in e: #e is a file object, so this reads the file one line at a time
print (l) # show the line that was just read
e.close() # close the file to keep the operating system happy
# or
print ("------\nthe whole file as a list:")
e=open('/media/dave/PSY31170/emaillist.csv','r') # notice 'r' for read, not 'w' for write
emails=e.readlines() # gets all the lines into memory, for small files
print (emails)
# or
print ("-----\none item in the list at a time (without the newlines):")
for l1 in emails: # each l1 is one line
print(l1[0:-1]) # slice off the last char to remove the trailing newline
e.close() # close the file to keep the operating system happy
# let's read the file in as a python dictionary, so we can look up entries by name
e=open('/media/dave/PSY31170/emaillist.csv','r')
peopledict = {} # initialize an empty dictionary
for p in e:
# each p is one line from the excel format csv filefile
# so it is a text string of a list of attribute values:
print('text string of this line:',p)
print('length of text string:',len(p))
# use split to separate the values:
pvals = p.split(',') # separates by commas
# use the first one as the key to look up by and the second as the
# value that the key is associated with:
print('Now the text string is made into a list separated by commas:',pvals)
print('The full read-in entry text line is now a list of',len(pvals),'items long')
# now put the entry into the dictionary:
peopledict[pvals[0]] = pvals[1] #pvals[0] is the name, pvals[1] is the email
e.close()
# now see what we have in the dictionary peopledict:
print("\nThe raw peopledict is:\n",peopledict)
print ("--- now displayed by key-value pairs:")
for p in peopledict.keys():
print ("lookup key:",p,"value:",peopledict[p][0:-1]) #take off trailing \n
print('===\n')
n=''
while n == '':
n=input("Go ahead, enter a name to look up their email:")
try: # the try-except block catches errors without crashing the program
print(peopledict['"'+n+'"']) # add the quotes present for csv format
except:
print("Error: ",n,"not found in peopledict. Try again.")
n=''
# === TO DO: ===
"""
1. Add a user data entry loop to allow more names and emails to be entered.
Include the entry of the other data attributes of a Person
2. Add more attributes,but leave the data entry for now
3. add a loop to let the user look up an entry by name, and then enter a value
for another attribute if the dictionary entry is found.
4. After any new data is entered, re-write the csv file to save the data.
"""
|
d5f8ef92bfdaca49a9d3a6028b9f9cf79dec5ad6 | nathang21/CNT-4603 | /Project 6/Submission/Source/zipcode.py | 625 | 3.953125 | 4 | '''
Created on Dec 6, 2015
@author: Nathan Guenther
'''
import re
# Ask user for input file
fileName = input('Please enter the name of the file containing the input zipcodes: ')
# Read and save file contents
fileObj = open(fileName, 'r')
allLines = fileObj.readlines()
fileObj.close()
# Regular Expression
test = '^\d{5}(?:[-\s]\d{4})?$'
print('\n\n')
# Check each zip code
for eachLine in allLines:
#Regex check
if re.search(test, eachLine):
print("Match found - valid U.S. zipcode: ", eachLine)
else:
print("Error - no match - invalid U.S. zipcode: ", eachLine)
|
c0c4f7738c75c36dcecbce841d3c432d81530184 | zhengxiang1994/JIANZHI-offer | /test1/bubble_sort.py | 316 | 3.796875 | 4 | class Solution:
def bubblesort(self, L):
for i in range(len(L)-1):
for j in range(len(L)-i-1):
if L[j+1] < L[j]:
L[j], L[j+1] = L[j+1], L[j]
return L
if __name__ == "__main__":
s = Solution()
print(s.bubblesort([1, 3, 5, 7, 2, 4, 6]))
|
79af3c8cf80c6788daffeb7558688fd68326a4bd | zhengxiang1994/JIANZHI-offer | /test1/demo19.py | 784 | 3.84375 | 4 | # -*- coding:utf-8 -*-
class Solution:
# matrix类型为二维列表,需要返回列表
def printMatrix(self, matrix):
# write code here
result = []
while matrix:
result += matrix[0]
if not matrix or not matrix[0]:
break
matrix.pop(0)
if matrix:
matrix = self.rotate(matrix)
return result
def rotate(self, matrix):
height = len(matrix)
width = len(matrix[0])
newmat = []
for i in range(width):
newmat.append([m[width-i-1] for m in matrix])
return newmat
if __name__ == "__main__":
s = Solution()
a = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]]
print(s.printMatrix(a))
|
2600e0f77da5149418d0211182bb74b7f1f0e954 | zhengxiang1994/JIANZHI-offer | /test1/demo32.py | 568 | 3.828125 | 4 | # -*- coding:utf-8 -*-
class Solution:
def PrintMinNumber(self, numbers):
# write code here
# 类似冒泡排序
for i in range(len(numbers)-1):
for j in range(len(numbers)-i-1):
if int(str(numbers[j])+str(numbers[j+1])) > int(str(numbers[j+1])+str(numbers[j])):
numbers[j], numbers[j+1] = numbers[j+1], numbers[j]
s = ""
return s.join(list(map(str, numbers)))
if __name__ == "__main__":
s = Solution()
arr = [3, 32, 321]
print(s.PrintMinNumber(arr)) |
accfb44d8e1b173c48550e18aa9d1845f181e996 | zhengxiang1994/JIANZHI-offer | /test1/demo22.py | 1,031 | 3.90625 | 4 | # -*- coding:utf-8 -*-
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
# 返回从上到下每个节点值列表,例:[1,2,3]
def PrintFromTopToBottom(self, root):
# write code here
ls = []
queue = []
if not root:
return ls
queue.append(root)
while queue:
temp = queue.pop(0)
if temp.left:
queue.append(temp.left)
if temp.right:
queue.append(temp.right)
ls.append(temp.val)
return ls
if __name__ == "__main__":
root0 = TreeNode(8)
root1 = TreeNode(6)
root2 = TreeNode(10)
root3 = TreeNode(5)
root4 = TreeNode(7)
root5 = TreeNode(9)
root6 = TreeNode(11)
root0.left = root1
root0.right = root2
root1.left = root3
root1.right = root4
root2.left = root5
root2.right = root6
s = Solution()
print(s.PrintFromTopToBottom(root0))
|
7b7c9250218d1f36284181b38d93c2ce594a3837 | arvind2608/python- | /desktop background change app.py | 1,910 | 3.734375 | 4 | # import modules
from tkinter import *
from tkinter import filedialog
from wallpaper import set_wallpaper
# user define funtion
def change_wallpaper():
# set your wallpaper
try:
set_wallpaper(str(path.get()))
check = "DONE"
except:
check = "Wallpaper not available"
result.set(check)
def browseFiles():
filename = filedialog.askopenfilename(initialdir="/", title="Select a File",
filetypes=(("jpeg files", "*.jpg")
,("all files", "*.*")))
path.set(filename)
# Change label contents
label_file_explorer.configure(text="File Opened: "+filename)
return filename
# object of tkinter
# and background set
master = Tk()
master.configure(bg='orange')
# Variable Classes in tkinter
result = StringVar()
path = StringVar()
label_file_explorer = Label(master, text="Select a image", width=100, fg="black",bg="white")
# Creating label for each information
# name using widget Label
Label(master, text="Select image : ",fg="black", bg="white").grid(row=0, sticky=W)
Label(master, text="Status :",fg="black", bg="white").grid(row=3, sticky=W)
# Creating label for class variable
# name using widget Entry
Label(master, text="", textvariable=result,
bg="white").grid(row=3, column=1, sticky=W)
# creating a button using the widget
# Button that will call the submit function
b = Button(master, text="Open", command=browseFiles, bg="white")
b.grid(row=0, column=2, columnspan=2, rowspan=2, padx=5, pady=5,)
label_file_explorer.grid(column=1, row=1)
c = Button(master, text="Apply", command=change_wallpaper, bg="white")
c.grid(row=2, column=2, columnspan=2, rowspan=2, padx=5, pady=5,)
mainloop()
|
1d01da0f3867b5d86f5cabbacbdb505c50a137f4 | tobhuber/rateme | /core/Song.py | 1,332 | 3.578125 | 4 | class Song:
def __init__(self, name = "", album = None, raters = {}, rating = -1):
self.name = name
self.album = album
self.rating = rating
self.raters = raters
self.hash = f"{self.name}#{self.album.interpret[0]}"
self.updateRating()
def __str__(self):
return f"""
Song object with:
name: {self.name}
album: {self.album.title}
rating: {self.rating}
raters: {self.raters}
hash: {self.hash}
"""
def updateRating(self):
result = 0
for rating in self.raters.values():
result += rating
self.rating = -1 if len(self.raters) == 0 else round(result / len(self.raters), 2)
def addRating(self, rater, rating):
if rater not in self.raters:
self.raters[rater] = rating
self.updateRating()
self.album.addRater(rater)
self.album.updateRating()
else:
self.raters[rater] = rating
self.updateRating()
self.album.updateRating()
def removeRater(self, rater):
if rater in self.raters:
del self.raters[rater]
self.updateRating()
self.album.updateRating()
self.album.updateRaters()
|
a4d6aa8406a45aa04ec44f12bea28c132fc0adb5 | ZL-Zealous/ZL-study | /py_study_code/循环/while.py | 211 | 3.734375 | 4 | prompt='\n please input something:'
prompt+='\n enter "quit" to end\n'
message=''
active=True
while active:
message=input(prompt)
if message=='quit':
active=False
else:
print(message) |
58c1b6b2a960dcedfa0317f9276b87daa6dc895e | ZL-Zealous/ZL-study | /py_study_code/文件与异常/json.number.py | 273 | 3.578125 | 4 | import json
filename='number.json'
try:
with open(filename) as f_obj:
a=json.load(f_obj)
print("i konw the number is "+a)
except:
number = input('enter your favorite number:\n')
with open(filename,'w') as f_obj:
json.dump(number,f_obj)
|
fdad762c31dc9a9b52f9c0fe9f5e2fb333faa415 | gokulmurali/sicp_exercises | /sicp/1-17.py | 314 | 3.8125 | 4 |
def double(x):
return x + x
def halve(x):
return (x/2)
def even(x):
if x % 2 == 0: return True
else: return False
def mul(a, b):
if b == 0:
return 0
elif even(b):
return (double(a * halve(b)))
else:
return (a + (a * (b-1)))
print mul(2, 3)
print mul(2, 4)
|
a474bbf23356b820d0ec28c9d5616fc996c9a964 | gokulmurali/sicp_exercises | /sicp/1-18.py | 384 | 3.765625 | 4 |
def double(x):
return x + x
def halve(x):
return (x / 2)
def even(x):
if x % 2 == 0:return True
else:return False
def muliter(a, b, aa):
if b == 0:
return aa
elif even(b):
return muliter(double(a), halve(b), aa)
else:
return muliter(a, b-1, (aa + a))
def mul(a, b):
return muliter(a, b , 0)
print mul(2, 3)
print mul(2, 4)
|
6c77d7dc7e8f789dab2c2aefdf4f2f0f16ac9352 | luisfrancisco62/Transparent-Splash-Screen-Tk | /splash.py | 640 | 3.796875 | 4 | """
Splash Screen Demonstration
Author: Israel Dryer
Modified: 2020-05-22
"""
import tkinter as tk
# create the main window
root = tk.Tk()
# disable the window bar
root.overrideredirect(1)
# set trasparency and make the window stay on top
root.attributes('-transparentcolor', 'white', '-topmost', True)
# set the background image
psg = tk.PhotoImage(file='splash-logo.png')
tk.Label(root, bg='white', image=psg).pack()
# move the window to center
root.eval('tk::PlaceWindow . Center')
# schedule the window to close after 4 seconds
root.after(4000, root.destroy)
# run the main loop
root.mainloop()
|
3d2826426b2a6328fc4d5e63ca958c554d722cc2 | La-Ola/Year-10- | /driving.py | 897 | 3.984375 | 4 | print (" Welcome to DVLA driving test.")
print ("**************************************************************")
years = int(input("How many years have you been driving for?"))
points = int(input("How many penalty point do you have?"))
if years <=2 and points >=6: #engulfs numbers including and below 2 and including and above 6
print("-------------LICENCE SUMMARY-------------")
print(" YOUR LICENCE HAS BEEN DISQUALIFIED.")
print("-----------------------------------------")
elif years >=2 and points >=12:
print("-------------LICENCE SUMMARY-------------")
print(" YOUR LICENCE HAS BEEN TIME-BANNED.")
print("-----------------------------------------")
else:
print("-------------LICENCE SUMMARY-------------")
print(" YOUR LICENCE IS OKAY, CONTINUE.")
print("-----------------------------------------")
|
6f8cb30a116ef9a5ccaf5a33177ef512790e78ae | La-Ola/Year-10- | /ODDS AND EVENS.py | 367 | 4.03125 | 4 | #Odds and Evens
print ("*****ODDS AND EVENS BETWEEN YOUR CHOSEN NUMBER AND 50*****")
num = int(input("Choose a number between 1 and 50."))
print("****THE EVENS****")
x = num
while x < 50:
if x%2 == 0:
print (x)
x = x + 1
print("****AND NOW THE ODDS****")
x = num
while x < 50:
if x%2 == 1:
print (x)
x = x + 1
|
9d364d2297350eb501de9c099b8f20c6b2502435 | WolfAuto/Maths-Pro | /NEA Programming/random.py | 3,204 | 3.78125 | 4 | import tkinter as tk # python3
TITLE_FONT = ("Helvetica", 18, "bold")
class SampleApp(tk.Tk): # create a class that takes in a parameter of a tkinter GUI screen
def __init__(self, *args, **kwargs): # instalise the class with the parameters self with
tk.Tk.__init__(self, *args, **kwargs)
# the container is where we'll stack a bunch of frames
# on top of each other, then the one we want visible
# will be raised above the others
container = tk.Frame(self)
container.pack(side="top", fill="both", expand=True)
container.grid_rowconfigure(0, weight=1)
container.grid_columnconfigure(0, weight=1)
self.frames = {}
self.frames["StartPage"] = StartPage(parent=container, controller=self)
self.frames["PageOne"] = PageOne(parent=container, controller=self)
self.frames["PageTwo"] = PageTwo(parent=container, controller=self)
self.frames["StartPage"].grid(row=0, column=0, sticky="nsew")
self.frames["PageOne"].grid(row=0, column=0, sticky="nsew")
self.frames["PageTwo"].grid(row=0, column=0, sticky="nsew")
self.show_frame("StartPage")
def show_frame(self, page_name):
'''Show a frame for the given page name'''
frame = self.frames[page_name]
frame.tkraise()
class StartPage(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
self.controller = controller
self._canvas = tk.Canvas(self, bg='blue', width=900, height=900,
scrollregion=(0, 2800, 100, 800))
self._canvas.pack()
self._canvas.create_text(100, 10, fill="darkblue", font="Times 20 italic bold",
text="Click the bubbles that are multiples of two.")
label = tk.Label(self, text="This is the start page", font=TITLE_FONT)
label.pack(side="top", fill="x", pady=10)
button1 = tk.Button(self, text="Go to Page One",
command=lambda: controller.show_frame("PageOne"))
button2 = tk.Button(self, text="Go to Page Two",
command=lambda: controller.show_frame("PageTwo"))
button1.pack()
button2.pack()
class PageOne(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
self.controller = controller
label = tk.Label(self, text="This is page 1", font=TITLE_FONT)
label.pack(side="top", fill="x", pady=10)
button = tk.Button(self, text="Go to the start page",
command=lambda: controller.show_frame("StartPage"))
button.pack()
class PageTwo(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
self.controller = controller
label = tk.Label(self, text="This is page 2", font=TITLE_FONT)
label.pack(side="top", fill="x", pady=10)
button = tk.Button(self, text="Go to the start page",
command=lambda: controller.show_frame("StartPage"))
button.pack()
if __name__ == "__main__":
app = SampleApp()
app.mainloop()
|
8de6eedf90b3c7fd5ff34e0780ee44240049d0ef | WolfAuto/Maths-Pro | /NEA Testing/remake_register.py | 9,940 | 3.65625 | 4 | from tkinter import messagebox # module for error messages on the tkinter page
import string
import re
import bcrypt
from validate_email import validate_email
import yagmail
from create_connection import cursor, cursor1, db
shared_data = {"firstname": "blank", # dictionary that stores the user register information
"surname": "blank", # through using the controller we can pass these variables
"age": 0, # to different frames
"Class": "blank",
"gender": "blank", }
create_student_table = ("""CREATE TABLE IF NOT EXISTS Students(ID INTEGER PRIMARY KEY,
Forename VARCHAR(30),
Surname VARCHAR(30) , Age INTEGER ,
class VARCHAR (3), Gender VARCHAR (30) ,
Username VARCHAR(30),Password VARCHAR(80), Email VARCHAR(30))""")
create_teacher_table = ("""CREATE TABLE IF NOT EXISTS Teachers( ID INTEGER PRIMARY KEY,
Forename VARCHAR(30) ,
Surname VARCHAR(30) , Age INTEGER ,
Class VARCHAR (3) , Gender VARCHAR (30),
Username VARCHAR(30), Password VARCHAR(80), Email VARCHAR(30))""")
# Sql statment to create the table where the user information will be stored
cursor.execute(create_student_table) # executes the sql statement
# Sql statment to create the table where the user information will be stored
cursor.execute(create_teacher_table) # executes the sql statement
db.commit() # saves changes made to the sql file
def register1(firstname, surname, age, school_class, var, var1): # Function for registration
if firstname.isalpha() is True:
firstname.title()
if surname.isalpha() is True:
surname.title()
try:
age1 = int(age)
if school_class.isalnum() is True:
if var == 1: # changing the var to a gender either male or female depending on value
if (var1 == 1) or (var1 == 2):
shared_data["firstname"] = firstname
shared_data["surname"] = surname
shared_data["age"] = age1
shared_data["gender"] = "Male"
shared_data["Class"] = school_class
return True
else:
messagebox.showerror(
"School", "Please choose either Student or Teacher")
return False
elif var == 2:
if (var1 == 1) or (var1 == 2):
shared_data["firstname"] = firstname
shared_data["surname"] = surname
shared_data["age"] = age1
shared_data["gender"] = "Female"
shared_data["Class"] = school_class
return True
else:
messagebox.showerror(
"School", "Please choose either Student or Teacher")
return False
else:
messagebox.showerror("Gender", "Gender option cannot be left blank")
return False
else:
messagebox.showerror("Class", "Class option cannot be left blank")
except ValueError:
messagebox.showerror("Age", "Please enter a number")
else:
messagebox.showerror("Surname", "Please enter a Proper Surname")
else:
messagebox.showerror("First Name", "Please enter a proper First Name")
def username_check(username): # function for username vaildation
# Checking the length of username is more than 6 charcters
if len(username) >= 6:
# sql statement for checking existing users
# Checks student database for username
fetchstudents = ("SELECT DISTINCT Students.Username from Students WHERE Username = ?")
# Checkes teacher databaase for username
fetchteachers = ("SELECT DISTINCT Teachers.Username from Teachers WHERE Username = ?")
cursor.execute(fetchstudents, [(username)]) # executes the above query on the student table
cursor1.execute(fetchteachers, [(username)]) # execute the above query on the teacher table
checking = cursor.fetchall() # stores the result of sql search
checking1 = cursor1.fetchall()
if checking or checking1:
messagebox.showerror("Username", "That username has been taken please try another one")
else:
return True
else:
messagebox.showerror(
"Username", "Username has to be 6 or more characters")
def password_check(password, password_confirm): # function for password vaildation
if password == password_confirm:
if len(password) >= 8: # checks whether the password length is 8 chracterslong
# checks for letters in the password
if len(set(string.ascii_lowercase).intersection(password)) > 0:
# checks for numbers or special characters in the password
if (len(set(string.ascii_uppercase).intersection(password)) > 0):
# checks for uppercase characters
if (len(set(string.digits).intersection(password))) > 0:
if (len(set(string.punctuation).intersection(password))) > 0:
return True
else:
messagebox.showerror(
"Password", "Password doesn't contain a special character")
return False
else:
# tkinter error message
messagebox.showerror(
"Password", "Password don't contain numbers")
return False
else:
messagebox.showerror(
"Password", "Password don't contain any uppercase characters") # tkinter error message
return False
else:
messagebox.showerror(
"Password", "Password don't contain any lowercase letters") # tkinter error message
return False
else:
messagebox.showerror(
"Password", "Password is not 8 characters long") # tkinter error message
return False
else:
messagebox.showerror(
"Password", "Password don't match") # tkinter error message
return False
def email_check(email): # function for email vaildation
match = re.match(
'^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})$', email)
is_valid = validate_email(email, verify=True)
if match is None:
messagebox.showerror("Email", "Please enter a valid email address ")
if is_valid is not True:
messagebox.showerror(
"Email", "Email address doesn't exist please try another email address")
else:
return True
def register2(username, password, confirm_password, email, var1):
# checks whether a existing username with the username enter exists
if username_check(username):
# ensures the password passes all the vaildations
if password_check(password, confirm_password):
password_store = bcrypt.hashpw(password.encode("utf8"), bcrypt.gensalt())
if email_check(email): # ensures the email passes the vaildation
if var1 == 1: # inserts one whole record into student table
insert_student = (
"INSERT INTO Students(Forename,Surname,Age,Class,Gender,Username,Password,Email) VALUES (?, ?, ?, ?, ?, ?, ?, ?)")
cursor.execute(insert_student, [(shared_data["firstname"]), (shared_data["surname"]),
(shared_data["age"]), (shared_data["Class"]),
(shared_data["gender"]), (username), (password_store), (email)])
send_email(email, username)
elif var1 == 2: # inserts one whole record into the teacher table
insert_teacher = (
"INSERT INTO Teachers(Forename,Surname,Age,Class,Gender,Username,Password,Email) VALUES (?, ?, ?, ?, ?, ?, ?, ?)")
cursor.execute(insert_teacher, [(shared_data["firstname"]), (shared_data["surname"]),
(shared_data["age"]), (shared_data["Class"]),
(shared_data["gender"]), (username), (password_store), (email)])
send_email(email, username)
db.commit() # saves the changes to the database file
return True
else:
return False
else:
return False
else:
return False
def send_email(email, username):
yag = yagmail.SMTP("mathspro0@gmail.com", oauth2_file="~/oauth2_creds1.json")
send_mail = (" Email Confirmation From Maths Pro",
" First Name:" + shared_data["firstname"],
"Surname:" + shared_data["surname"],
" Age:" + str(shared_data["age"]),
"Class: " + shared_data["Class"],
"Gender:" + shared_data["gender"],
"username:" + username)
yag.send(to=email, subject="Maths Pro Email Confirmation", contents=send_mail)
|
9907161a049b3e6088bd04f1f807fc2b2664b087 | WolfAuto/Maths-Pro | /Maths-Pro-NEA-TESTING/NEA Testing/login page.py | 7,788 | 3.8125 | 4 | import sqlite3
import tkinter as tk
from tkinter import ttk
title_font = ("Times New Roman", 50)
medium_font = ("Times New Roman", 26)
class MathsPro(tk.Tk): # Creating a class that inherits from tk.Tk
def __init__(self, *args, **kwargs): # intialises the object
# intialises the object as a tkinter frame
tk.Tk.__init__(self, *args, **kwargs)
# tk.Tk.iconbitmap(self, default="")
# Sets the title of each page to be Maths Pro
tk.Tk.wm_title(self, "Maths Pro")
# defined a container for all the framesto be kept
container = tk.Frame(self)
# The containter is filled with a bunch of frames
container.pack(side="top", fill="both", expand=True)
container.grid_rowconfigure(0, weight=1)
# After the page being packed this allows it to be displayed correctly
container.grid_columnconfigure(0, weight=1)
self.frames = {} # Empty dictionary where all the frames are kept
# contains all the pages being used #this will not work without pages
for F in (Main_Menu, StudentArea, TeacherArea):
# Defines the frame from the for loop which contains all the pages
frame = F(container, self)
# Sets the top frame to be the current frame
self.frames[F] = frame
# This allows the frame to be displayed and streched
frame.grid(row=0, column=0, sticky="nsew")
# sets the first frame to be shown is a register page
self.show_frame(Main_Menu)
def show_frame(self, cont): # method that takes in cont as a controller
# Defines the frame from the chosen frame in the dictionary
frame = self.frames[cont]
frame.tkraise() # Brings the frame to the top for the user to see
class Main_Menu(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
label = tk.Label(self, text="Maths Pro", bg="blue", font=title_font)
label.pack(pady=10, padx=10)
label_1 = tk.Label(self, text="Username")
label_1.pack()
username_entry = tk.StringVar()
entry_1 = tk.Entry(self, textvariable=username_entry)
entry_1.pack()
label_2 = tk.Label(self, text="Password")
label_2.pack()
password_entry = tk.StringVar()
entry_2 = tk.Entry(self, textvariable=password_entry)
entry_2.pack()
button = ttk.Button(self, text="Login")
button.pack()
button1 = ttk.Button(self, text="Student Area",
command=lambda: controller.show_frame(StudentArea))
button1.pack()
button2 = ttk.Button(self, text="Teacher Area",
command=lambda: controller.show_frame(TeacherArea))
button2.pack()
photo = tk.PhotoImage(file="button.png")
help_button = tk.Button(self, text="Help Button", image=photo)
help_button.config(border="0")
help_button.place(x=0, y=730)
help_button.image = photo
logout_button = tk.Button(self, text="Log out",
command=lambda: controller.show_frame(Main_Menu))
logout_button.config(height=3, width=10, bg="blue", fg="white")
logout_button.place(x=1050, y=750)
quit_button = tk.Button(self, text="Exit", command=lambda: quit(self))
quit_button.config(fg="white", bg="blue", height=3, width=10)
quit_button.place(x=1200, y=750)
def vaildate_account(self, controller, username, password):
if vaildate_account(username, password) == True:
pass
class StudentArea(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
tk.Frame.config(self, bg="grey")
label = tk.Label(self, text="Student Area", font=title_font)
label.config(bg="blue", fg="white")
label.pack(pady=10, padx=10, side="top", anchor="nw")
teacher_button = tk.Button(self, text="Teacher Area",
command=lambda: controller.show_frame(TeacherArea))
teacher_button.pack(side="right", anchor="e")
info_text = tk.Label(
self, text="Welcome Student please choose from the following", font=medium_font, bg="grey")
info_text.place(x=350, y=100)
account_button = tk.Button(self, text="View Account Infomation")
account_button.config(height=5, width=30, bg="blue")
account_button.place(x=400, y=450)
info_button = tk.Button(self, text="View Maths Information")
info_button.config(height=5, width=30, bg="blue")
info_button.place(x=750, y=450)
math_button1 = tk.Button(self, text="AS Maths")
math_button1.config(height=5, width=30, bg="blue")
math_button1.place(x=400, y=250)
math_button2 = tk.Button(self, text="A2 Maths")
math_button2.config(height=5, width=30, bg="blue")
math_button2.place(x=750, y=250)
help_button = tk.Button(self, text="Help Button")
help_button.config(height=3, width=10, bg="blue")
help_button.place(x=0, y=750)
logout_button = tk.Button(self, text="Log out",
command=lambda: controller.show_frame(Main_Menu))
logout_button.config(height=3, width=10, bg="blue", fg="white")
logout_button.place(x=1050, y=750)
quit_button = tk.Button(self, text="Exit", command=lambda: quit(self))
quit_button.config(height=3, width=10, bg="blue")
quit_button.place(x=1200, y=750)
class TeacherArea(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
tk.Frame.config(self, bg="grey")
label_text = tk.Label(self, text="Teacher Area", font=title_font)
label_text.config(bg="blue", fg="white")
label_text.pack(pady=10, padx=10, anchor="nw")
info_text = tk.Label(
self, text="Welcome Teacher please choose from the following", font=medium_font, bg="grey")
info_text.place(x=350, y=100)
button1 = tk.Button(self, text="Student Area",
command=lambda: controller.show_frame(StudentArea))
button1.pack()
button2 = tk.Button(self, text="View Account Information")
button2.config(height=5, width=30, bg="blue", fg="white")
button2.place(x=750, y=450)
button3 = tk.Button(self, text="View Student/Class Information")
button3.place(x=400, y=250)
button3.config(height=5, width=30, bg="blue", fg="white")
button4 = tk.Button(self, text="View Flagged Students")
button4.place(x=750, y=250)
button4.config(height=5, width=30, bg="blue", fg="white")
button5 = tk.Button(self, text="Set Test Date")
button5.place(x=400, y=450)
button5.config(height=5, width=30, bg="blue", fg="white")
help_button = tk.Button(self, text="Help Button")
help_button.config(height=3, width=10, bg="blue", fg="white")
help_button.place(x=0, y=750)
logout_button = tk.Button(self, text="Log out",
command=lambda: controller.show_frame(Main_Menu))
logout_button.config(height=3, width=10, bg="blue", fg="white")
logout_button.place(x=1050, y=750)
quit_button = tk.Button(self, text="Exit", command=lambda: quit(self))
quit_button.config(fg="white", bg="blue", height=3, width=10)
quit_button.place(x=1200, y=750)
root = MathsPro() # this runs the Maths Pro class
root.geometry("1280x800") # changes the size of the window
root.resizable(width=False, height=False)
root.mainloop() # As MathsPro inherited from tkinter this function can be moved
|
00d264591a57a5b69b759be8d6ac75b603ee0a5f | WolfAuto/Maths-Pro | /Maths-Pro-NEA-TESTING/NEA Programming/Stage 1 Creating GUI/learning.py | 1,589 | 3.890625 | 4 | import random
import sqlite3
with sqlite3.connect("datalearn.db") as db:
cursor = db.cursor()
cursor.execute("CREATE TABLE IF NOT EXISTS details(userID INTEGER PRIMARY KEY, firstname VARCHAR(30) NOT NULL, surname VARCHAR(30) NOT NULL , age INTEGER NOT NULL, class VARCHAR(3) NOT NULL, school VARCHAR(20) NOT NULL, username VARCHAR(20) NOT NULL, password VARCHAR(20) NOT NULL);")
cursor.execute("INSERT INTO details(firstname,surname,age,class,school,username,password)VALUES('testname','name',21,'12D','Student','test_user','test_password')")
db.commit()
listfirst = ["john", "mary", "alice", "rias", "sam", "luke", "gerald"]
listsurname = ["Sky", "Mac", "Smith", "Snow", "Stark", "Jona", "Scarlet"]
listage = [18, 21, 49, 30, 25, 16, 17]
listclass = ["13C", "12A", "12B", "12C", "13L", "13D", "13A"]
listschool = ["Student", "Teacher"]
listuser = ["test1", "test2", "test3", "test4", "test5", "test6", "test7"]
listpassword = ["pass1", "pass2", "pass3", "pass4", "pass5", "pass6", "pass7"]
def dynamic_entry():
a = random.randint(0, 6)
b = random.randint(0, 1)
first= str(listfirst[a])
surname = str(listsurname[a])
age= int(listage[a])
clas = str(listclass[a])
school = str(listschool[b])
user = str(listuser[a])
passw = str(listpassword[a])
cursor.execute("INSERT INTO details(firstname, surname, age , class, school, username, password) VALUES (?, ?, ?, ?, ?, ?, ?)",
(first, surname, age, clas, school, user, passw))
for i in range(10):
dynamic_entry()
cursor.close()
db.close()
|
d57a13ede4aba6274abe58dc902d09d61261acfa | seansaito/Number-Theory | /pingala.py | 816 | 3.921875 | 4 | import sys
def main(argv):
a = int(argv[0])
e = int(argv[1])
m = int(argv[2])
print pingala(a,e,m)
# Computes a to the power of e in mod m context
def pingala(a,e,m):
# Converts the exponent into a binary form
e_base2 = bin(e)[2:]
# This keeps track of the final answer
answer = 1
# A for loop that iterates through each digit
# of the binary form of the exponent
for t in range(len(e_base2)):
signal = e_base2[t]
# Squares the current answer
answer = answer**2
# If the current digit of the binary form
# is "on" (or equal to one), then multiply
# answer by a
if signal == '1':
answer = answer*a
#Return the answer in modulo
return answer % m
if __name__ == '__main__':
main(sys.argv[1:]) |
ac73ef5689da1cc08123d76dcb3d1edc31d05ec5 | drbuche/HackerRank | /Python/01_Introduction/005_Write_a_function.py | 355 | 3.921875 | 4 | # Problem : https://www.hackerrank.com/challenges/write-a-function/problem
# Score : 10 points(MAX)
def is_leap(year):
"""
:param year: Recebe um valor referente ao ano.
:return: Retorna se o ano é bissexto ou não em forma de boolean.
"""
return year % 4 == 0 and (year % 100 != 0 or year % 400 == 0)
print(is_leap(int(input())))
|
70bb2017ba78e0cd36a3fc50e6dbd59403c20001 | drbuche/HackerRank | /Python/01_Introduction/001_Python_If_Else.py | 477 | 4.03125 | 4 | # Problem : https://www.hackerrank.com/challenges/py-if-else/problem
# Score : 10 points(MAX)
def wierd(n):
"""
:param n: Recebe um valor inteiro 'n'
:return: Retona um print contendo 'Weird' caso o numero seja impar ou esteja entre 6 e 20.
Caso contrario retorna 'Not Weird'.
"""
print('Weird' if (n % 2 == 1) or (6 <= n <= 20) else 'Not Weird')
wierd(int(input())) # Executa a função 'wierd' utilizando como parametro um input inteiro.
|
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()
|
18e86788373b6bbba4cbd1d8e2084caebcb9dee5 | drbuche/HackerRank | /Python/04_Sets/003_Set.add().py | 426 | 3.75 | 4 | # Problem : https://www.hackerrank.com/challenges/py-set-add/problem
# Score : 10 points(MAX)
loops = input() # Quantidade de valores que entrarão
grupo = [] # Grupo para alocar esses valores
[grupo.append(input()) for i in range(int(loops))] # para cada loop adicione a palavra no grupo dist
print(len(set(grupo))) # Transforme a lista em um set para remover os valores repetidos e depois retorne o tamanho do set
|
98cf8b7d7a5f6c0753fc8812a38eb3e7a8b52590 | dsiah/Villanova-Python-Workshop | /scripts/maleGenerator.py | 628 | 3.90625 | 4 | """
A male first name generator.
The program sifts through a list of about 3,800 male names from
english speaking countries. User is asked to enter the (integer)
number of first names they would like to have generated.
Credit for the list of names goes to Grady Ward (Project Gutenberg)
See the aaPG-Readme.txt in the directory for more information.
David Siah 5/29/14
"""
import random
lines = open('MaleNames.txt').read().splitlines()
def chooseM(iter):
for i in range(iter):
chosenName = random.choice(lines)
print chosenName
raw = int(raw_input("How many first names would you like?\n"))
chooseM(raw)
|
7f0539c1b232551296487c24c5a1885a73c8b42a | dsiah/Villanova-Python-Workshop | /Python-Exercises/regex.py | 951 | 3.953125 | 4 | import re
"""
pattern = 'this'
text = 'Does this text match the pattern?'
match = re.search(pattern, text)
s = match.start()
e = match.end()
print 'Found "%s"\nin "%s"\nfrom %d to %d("%s")' %\
(match.re.pattern, match.string, s, e, text[s:e])
regexes = [re.compile(p)
for p in ["this", "that"]
]
print 'Text: %r\n' % text
for regex in regexes:
print "Searching for", regex.pattern
if regex.search(text):
print 'Match!'
else:
print 'No match!'
"""
newString = 'This is the best string ever!'
def seeker(patt):
thePattern = patt
Chill = re.search(thePattern, newString)
if Chill:
print '%r is in the string!' % thePattern
elif not Chill:
print '%r is not in the string :(' % thePattern
print "This is the string you are going to search through:\n"
print newString, '\n'
entry = raw_input('What would you like to search this string for?\n')
seeker(entry)
|
b4bc00af23adb5e933ca8429a6ef53e079ac3b86 | dsiah/Villanova-Python-Workshop | /scripts/howto.py | 669 | 3.984375 | 4 | # how to snippets of code that serve as patterns to use when programming
condition = True
condition2 = False
#if
if (condition):
#do stuff
print "Stuff"
#if/elif/else
if (condition):
print condition
elif (condition2):
print condition2
else:
print "Catch all"
#defining functions
def nameofFunc (argument):
# argument is optional
# do stuff with argument
print argument
# This can get confusing -- a list can hold lists and dictionaries
# they index at 0
list1 = ["hi", [1, 2, 3], 4]
# Woah this is a pretty loaded expression
# for [ variable name ] in [ set ]:
# do stuff --> then x gets incremented
for x in range(0, len(list1)):
print list1[x] |
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))
|
e8042f82196ee8eaecf800fc86ab3e04c788510a | yangahh/daliy-algorithm | /week04/answer04.py | 171 | 3.5 | 4 | def maxSubArray(nums):
dp = [0] * len(nums)
dp[0] = nums[0]
for i in range(1, len(nums)):
dp[i] = max(dp[i-1] + nums[i], nums[i])
return max(dp)
|
f71257aa717a5d2684f65505c488f1d9b6262e67 | yangahh/daliy-algorithm | /week05/answer03.py | 124 | 4 | 4 | def reverseString(str):
if len(str) == 1:
return str
else:
return str[-1] + reverseString(str[:-1])
|
25e1b8449981327950a7895d0f16d56c4a045065 | Vkomini/cs181-s18-homeworks | /T3/code/problem2.py | 1,464 | 3.515625 | 4 | # CS 181, Harvard University
# Spring 2016
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.colors as c
from Perceptron import Perceptron
# Implement this class
class KernelPerceptron(Perceptron):
def __init__(self, numsamples):
self.numsamples = numsamples
# Implement this!
# def fit(self, X, Y):
# Implement this!
# def predict(self, X):
# Implement this class
class BudgetKernelPerceptron(Perceptron):
def __init__(self, beta, N, numsamples):
self.beta = beta
self.N = N
self.numsamples = numsamples
# Implement this!
# def fit(self, X, Y):
# Implement this!
# def predict(self, X):
# Do not change these three lines.
data = np.loadtxt("data.csv", delimiter=',')
X = data[:, :2]
Y = data[:, 2]
# These are the parameters for the models. Please play with these and note your observations about speed and successful hyperplane formation.
beta = 0
N = 100
numsamples = 20000
kernel_file_name = 'k.png'
budget_kernel_file_name = 'bk.png'
# Don't change things below this in your final version. Note that you can use the parameters above to generate multiple graphs if you want to include them in your writeup.
k = KernelPerceptron(numsamples)
k.fit(X,Y)
k.visualize(kernel_file_name, width=0, show_charts=True, save_fig=True, include_points=True)
bk = BudgetKernelPerceptron(beta, N, numsamples)
bk.fit(X, Y)
bk.visualize(budget_kernel_file_name, width=0, show_charts=True, save_fig=True, include_points=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")
|
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)) |
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)
|
16631b78995f655cf7a84b6628f19c067d42680e | abhaj2/Phyton | /cycle-2/19.py | 164 | 3.890625 | 4 | import math
num1=int(input("Enter the 1st number\n"))
num2=int(input("Enter the 2st number\n"))
g=math.gcd(num1,num2)
print("The greatest common divisor is", g) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.