text
stringlengths 37
1.41M
|
---|
def average():
score1 = float(input("input 10 score percentages"))
score2 = float(input(""))
score3 = float(input(""))
score4 = float(input(""))
score5 = float(input(""))
score6 = float(input(""))
score7 = float(input(""))
score8 = float(input(""))
score9 = float(input(""))
score10 = float(input(""))
score_sum = (score1 + score2 + score3 + score4 + score5 + score6 + score7 + score8 + score9 + score10)
score_avg = score_sum/10
return score_avg
final_average = average()
print("the average of your scores is ",final_average)
if final_average >= 90:
print ("your grade is A")
else:
if final_average >= 80:
print ("your grade is B")
else:
if final_average >= 70:
print ("your")
|
# Hero's inventory
# Jacob Jensen
#11/18
import random
player_health = 100
player_armor = 1250
player_attack = 250
player_money = 0
inventory = ["rusty sword","leather armor","wood shield","small healing potion"]
player_stats = ["health",player_health,"armor",player_armor,"attack",player_attack,"money",player_money]
print("player stats: ")
print(player_stats)
print()
print("your items: ")
for item in inventory:
print(item)
input("\nPress the enter key to continue.")
print("you have", len(inventory), "items in your possession.")
player_health -= 22
input("\nyou have taken damage\n"+
"your health is at " + str(player_health)+"\n"+
"you need to use your healing potion \nPress the enter key to continue.")
if "small healing potion" in inventory:
print("you will live to fight another day")
player_health += 20
print(player_stats)
inventory.remove("small healing potion")
for item in inventory:
print(item)
index = int(input("\n Enter the index number for an item in inventory: "))
while index >len(inventory)-1 or index <0:
print("that number is out of range")
index = int(input("\n Enter the index number for an item in inventory: "))
print("at index", index, "is", inventory[index])
start = int(input("\n Enter the inde number to begin a slice: "))
finish = int(input("\n Enter the inde number to end a slice: "))
print("inventory[", start, ":", finish, "] is", end=" ")
print(inventory[start:finish])
input("\n Press the enter key to continue")
chest_items = ["gold","gems","banana","master ball","dog","non magical glove","elven bows","bow","crossbow","boots","hat"]
chest = []
for i in range (3):
item = random.choice(chest_items)
chest.append(item)
print("You find a chest wich contains: ")
print(chest)
print("You add the contens of the chest your inventroy.")
inventory += chest
print(inventory)
input("\n Press the enter key to continue.")
print("you trade your sword for a cross bow")
inventory[0] = "crossbow"
print("your inventory is now: ")
print(inventory)
input("\n Press the enter key to continue.")
print("you use your gold to buy a orb of future telling.")
inventory[4:6] = ["orb of future telling"]
print("your inventory is now: ")
print(inventory)
input("\nPress the enter key to continue.")
print("in a great battle, your shield is destroyed.")
del inventory[2]
print("your inventory is now: ")
print(inventory)
|
name1 = input("enter a name")
object2 = input("enter an object")
object3 = input("enter another object")
Species4 = input("enter a species real or fake")
action5 = input("enter an action")
print ("One day " + name1 + " was walking and found a " + object2 + " and a " + object3 + " that was picked up by a " + Species4 + " while " + action5)
input()
|
#two way if exe
#jacob jensen
#10/6/18
##num = int(input("enter a number"))
##
##if num%2 == 0:
## print("that number is even")
##else:
## print("that number is odd")
##
##print("the program is finished")
num1 = float(input("pick a number"))
num2 = float(input("pick a number"))
if num1<=num2:
if num1 == num2:
print("equal")
else:
print("not equal")
if num1<num2:
print("less than")
else:
if num1>= num2:
print ("greater than")
print("done")
|
# Rock Paper Scissors
# (based on Alyssa Harris code from python tutorials)
#
# Coding Club 18 Jan 2018
#
# This program takes user choice of R P or S and plays it
# against a random choice of R P S by the computer
# and prints out who wins.
#
# updated on the fly during the session to have two user choices instead of
# playing the computer per the kids' request
import random
def convert_choice_to_char(int_choice):
"""
converts integer version of choice to a character
"""
rps_dict = {"R": 0, "P":1, "S": 2}
for k, v in rps_dict.items():
if v == int_choice:
#print("found choice!")
return k
def convert_choice_to_desc(char_choice):
"""
converts character choice to long description
"""
rps_dict = {"R": "Rock", "P":"Paper", "S":"Scissors"}
return rps_dict[char_choice]
def compare_choice(user_choice, computer_choice):
"""
compares user and computer choice and returns string of who won
# Rock beats Scissors (R > S)
# Paper beats Rock (P > R)
# Scissors beats Paper (S > P)
Note: I really dislike this here function
"""
if user_choice == computer_choice:
return "It's a tie!"
if user_choice == "R":
if computer_choice == "S":
return "User Wins! Rock beats Scissors!"
else: # must be Paper
return "User Loses! Computer wins. Paper covers Rock!"
elif user_choice == "P":
if computer_choice == "R":
return "User Wins! Paper covers Rock!"
else: # must be Scissors
return "User Loses! Computer wins. Scissors cut Paper."
else: # user_choice must be Scissors
if computer_choice == "P":
return "User Wins! Scissors cut Paper!"
else: # must be Rock
return "User Loses! Computer wins. Rock beats Scissors."
def compare_with_ifs(user_choice, computer_choice):
"""
Decide who wins with if-elses
"""
print ("")
print ("##### Who wins by a set of if-else statements ######")
#Brute force. Nothing overly clever
# And lets print out what we have chosen and what the computer chose
print ("User 1 Choice is: ", convert_choice_to_desc(user_choice))
#print ("Computer Choice is: ", computer_choice)
print ("User 2 Choice is: ", convert_choice_to_desc(user2_choice))
#print("Computer Choice is: ", convert_choice_to_desc(computer_choice))
# Now to decide who wins
#print(compare_choice(user_choice, computer_choice))
print(compare_choice(user_choice, user2_choice))
def main():
keep_playing = True
while keep_playing:
valid_choice = False
valid2_choice = False
choices = ["R","P","S"]
while not valid_choice:
try:
user_choice = input("Would you like to play Rock (R), Paper (P), or Scissors (S)? ")
if user_choice in choices:
valid_choice = True
else:
print("Case Matters! Try again!")
except:
print("Unknown Error at user input")
while not valid2_choice:
try:
user2_choice = input("User 2, would you like to play Rock (R), Paper (P), or Scissors (S)? ")
if user2_choice in choices:
valid2_choice = True
else:
print("Case Matters! Try again!")
except:
print("Unknown Error at user input")
# generate the computer_choice
# one way
# computer_choice = random.randint(0, 2)
# computer_choice_char = convert_choice_to_char(computer_choice)
# like this way better, randomly generate index and then use the choices
# list in order to get the element.
#computer_choice = choices[random.randint(0,2)]
"""
Decide who wins with if-elses
"""
print ("")
print ("##### Who wins by a set of if-else statements ######")
#Brute force. Nothing overly clever
# And lets print out what we have chosen and what the computer chose
print ("User Choice is: ", convert_choice_to_desc(user_choice))
#print ("Computer Choice is: ", computer_choice)
print("User 2 Choice is: ", convert_choice_to_desc(user2_choice))
# Now to decide who wins
#print(compare_choice(user_choice, computer_choice))
if user_choice == user2_choice:
return "It's a tie!"
if user_choice == "R":
if user2_choice == "S":
print( "User 1 Wins! Rock beats Scissors!")
else: # must be Paper
return "User 1 Loses! User 2 wins. Paper covers Rock!"
elif user_choice == "P":
if user2_choice == "R":
print( "User 1 Wins! Paper covers Rock!")
else: # must be Scissors
print( "User 1 Loses! User 2 wins. Scissors cut Paper.")
else: # user_choice must be Scissors
if user2_choice == "P":
print( "User 1 Wins! Scissors cut Paper!")
else: # must be Rock
print( "User 1 Loses! User 2 wins. Rock beats Scissors.")
keep_playing = False #stop playing. TODO add choice
#then call it!
main()
|
import math
def factors_sum(n):
L = int(math.sqrt(n)+1)
ans = 0
for i in xrange(1, L, 1):
if n%i == 0:
ans += i
d = n/i
if d != i:
ans += d
return ans
def solve():
t = int(raw_input())
while t > 0:
t -= 1
n = int(raw_input())
print factors_sum(n)
if __name__ == '__main__':
solve()
|
fib = [0, 0, 1]
def fib_seq():
for i in range(3, 4784):
fib.append(fib[i-1]+fib[i-2])
def bsearch(num):
l = 0
h =len(fib)-1
while l <= h:
m = (l+h)/2
if fib[m] == num:
return m;
elif fib[m] < num:
l = m+1
else:
h = m-1
return -1
if __name__ == '__main__':
fib_seq()
t = int(raw_input())
while t > 0:
t -= 1
n = int(raw_input())
if bsearch(n) == -1:
print "NO"
else:
print "YES"
|
#took high temps from sitka alaska and plotted them using matplotlib
import csv
open_file = open("sitka_weather_07-2018_simple.csv", "r")
csv_file = csv.reader(open_file, delimiter= ",") #use the delimiter function
header_row = next(csv_file)
'''
print(header_row) #the next function skips reading the first line
for index, column_header in enumerate(header_row):
print(index, column_header)
'''
highs = []
for row in csv_file:
highs.append(int(row[5])) #gets the index value
print(highs)
import matplotlib.pyplot as plt #import the graph library as plt, an alias, plot creates a graph
plt.plot(highs, c="red")
plt.title("Daily High Temps, July 2018", fontsize=16)
plt.xlabel("") #x - axis label empty, we have to label the x-axis (sitka_temps_2)
plt.ylabel("Temperature (F)", fontsize=16)
plt.tick_params(axis="both",which="major",labelsize=16) #only shows major temps
plt.show()
|
#!/usr/bin/env python
#Be sure the indentation is identical and also be sure the line above this is on the first line
import sys
import re
def main(argv):
line = sys.stdin.readline()
while line:
# split line by ','
parts = line.split(',')
# check to make sure this isn't the header row.. if it is the header row don't do anything with the data
if(('InvoiceNo' not in parts[0]) and (parts[0][0] != 'C') and (len(parts[6]) > 0 )):
# get the data from part 4 of the line and split into data parts
date = parts[4].split('/')
# check if 1 digit month
if(len(date[0] )==1):
date = str('0'+date[0])
else:
date = str(date[0])
# print output in the form of mm,country tab customer,caspend
key = str(date +','+parts[7].strip('\n'))
sales = str(float(parts[3]) * float(parts[5]))
value = str(parts[6]+','+ sales)
print('{0}\t{1}'.format(key, value))
line = sys.stdin.readline()
#Note there are two underscores around name and main
if __name__ == "__main__":
main(sys.argv)
|
#from math import *
from pylab import *
from sympy import diff
from sympy.abc import x
def newton(funcion, df, vi, TOL, N,vectorx,vectory):
i = 0
while i<N:
vectorx[i] = vi
x = vi
f = eval(funcion)
df_val = eval(df)
vectory[i] = f
if df_val == 0:
print ("La evaluacion de la derivada de la funcion dio 0")
return 1
p1 = vi - (f / df_val)
if fabs(vi-p1) < TOL:
print ("La raiz buscada es: ", vi, "con", i + 1, "iteraciones")
return 1
i += 1
vi = p1
return 0
def dibujar(funcion, vi,vectorx,vectory):
x = arange(vi - 5, vi + 5, 0.1)
subplot(211)
plot(x, eval(funcion), linewidth=1.0)
xlabel('X')
ylabel('Y')
title(' f(x)=' + funcion)
grid(True)
axhline(linewidth=1, color='r')
axvline(linewidth=1, color='r')
subplot(212)
plot(vectorx, vectory, 'k.')
xlabel('X')
ylabel('Y')
grid(True)
axhline(linewidth=1, color='r')
axvline(linewidth=1, color='r')
show()
print (" Metodo de Newton-Raphson\n")
while True:
vectorx = zeros(100, float)
vectory = zeros(100, float)
funcion = input("Introduce la funcion \n")
df= str(diff(funcion,x))
print(df)
vi = float(input("Introduce el valor inicial\n"))
TOL = float(input("Introduce la tolerancia del metodo\n"))
r =newton(funcion, df, vi, TOL, 100,vectorx,vectory)
if r==0:
print("La funcion no toca el eje X")
dibujar(funcion, vi,vectorx,vectory)
exit = input("¿Quieres calcular otra vez? yes/no : ")
if exit == "no":
break
|
#!/usr/bin/env python3
from sys import argv
G = 9.80665
x, v, t = float(argv[1]), float(argv[2]), float(argv[3])
output = x + v*t - .5*G*(t**2)
print(output)
|
#get the input string from user
print ("Enter a string in uppercase:")
string = input()
#convert to lowercase
output = string.lower()
#print the output
print ("Lowercase:")
print (output)
|
# Первый вариант:
# marka_dict = {
# 'Марка': marka,
# }
# model_dict = {
# 'Модель': model
# }
# year_dict = {
# 'Год выпуска': year
# }
# mashina_list = [marka_dict, model_dict, year_dict]
# print(mashina_list)
# mashina()
# Исправленный вариант:
# mashini_info_list = list()
# mashini_info_dict = dict
# def mashina():
# marka1 = input('Введите марку первой машины: ')
# brand1 = input('Введите бренд первой машины: ')
# model1 = input('Введите модель первой машины: ')
# year1 = input('Введите год выпуска первой машины: ')
# marka2 = input('Введите марку второй машины: ')
# brand2 = input('Введите бренд второй машины: ')
# model2 = input('Введите модель второй машины: ')
# year2 = input('Введите год выпуска второй машины: ')
# marka3 = input('Введите марку третьей машины: ')
# brand3 = input('Введите бренд третьей машины: ')
# model3 = input('Введите модель третьей машины: ')
# year3 = input('Введите год выпуска третьей машины: ')
# mashini_info_dict= {
# 'Марка первой машины': marka1,
# 'Бренд первой машины': brand1,
# 'Модель первой машины': model1,
# 'Год выпуска первой машины': year1,
# 'Марка второй машины': marka2,
# 'Бренд второй машины': brand2,
# 'Модель второй машины': model2,
# 'Год выпуска второй машины': year2,
# 'Марка третьей машины': marka3,
# 'Бренд третьей машины': brand3,
# 'Модель третьей машины': model3,
# 'Год выпуска третьей машины': year3
# }
# mashini_info_list.append(mashini_info_dict)
# print(mashini_info_list)
# mashina()
#Третий вариант(покороче):
mashina = list()
def mashina_info():
for info in range(3):
marka = input('Введите марку машины: ')
model = input('Введите модель машины: ')
year = input('Введите год выпуска машины: ')
mashina_dict = {
'Марка': marka,
'Модель': model,
'Год': year
}
mashina.append(mashina_dict)
print(mashina)
mashina_info()
|
# Задание 1. Первый способ:
i = 700
while i // 7:
print(i)
i -= 7
#Второй способ (с range):
i = 0
while i in range(0,700,7):
print(i)
i += 7
# Задание 2.
name = input('Введите имена людей одинакового пола: ')
pol = input('Введите пол: (мужской/женский): ')
men = list()
women = list()
if pol == 'мужской':
men.append(name)
elif pol == 'женский':
women.append(name)
if len(men) == 0:
print('Вы не ввели данных для мужчин')
name = input('Введите имена мужчин: ')
men.append(name)
if len(women) == 0:
print('Вы не ввели данных для девушек')
name = input('Введите имена девушек: ')
women.append(name)
if len(men) > 5:
print('Вы ввели недопустимое количество данных для мужчин')
elif len(women) > 5:
print('Вы ввели недопустимое количество данных для девушек')
elif len(men) or len(women) <= 5:
print('Список мужчин:',men,'\nСписок девушек:',women)
|
# Lists are really variable
my_list = [(x, x**2) for x in range(1, 10)]
print(my_list)
"""
Single- or double-linked lists.
Single-linked lists references only to the next object.
Double-linked lists references both to the previous and the next object.
"""
|
# -*- coding: utf-8 -*-
"""
Created on Sat Jan 27 2018
@author: Francesco
"""
# ELABORAZIONE DATI CSV
import pandas as pd
#import xlrd
DF1 = pd.read_excel("Domini_min.xlsx")
## print the column names
print(DF1.columns)
EXCEL_FILE = pd.ExcelFile("Domini_min.xlsx")
SHEET_NAMES = EXCEL_FILE.sheet_names
print(SHEET_NAMES[1])
DF2 = EXCEL_FILE.parse(SHEET_NAMES[1])
print(DF2)
print("\r\nCiclo tutti gli sheet")
for SHEET_ITEM in SHEET_NAMES:
SHEET_NAME = SHEET_ITEM.split(" - ")[0]
print("SHEET_NAME: "+SHEET_NAME)
DF_SHEET_ITEM = EXCEL_FILE.parse(SHEET_ITEM)
## cambio il nome della prima colonna
DF_SHEET_ITEM.columns.values[0] = 'codice'
DF_SHEET_ITEM.columns.values[1] = 'descrizione'
DF_SHEET_ITEM['cod_dominio'] = SHEET_NAME
# riordino le colonne dataframe:
COLS = DF_SHEET_ITEM.columns.tolist()
COLS = COLS[-1:] + COLS[:-1]
#print(COLS)
DF_SHEET_ITEM = DF_SHEET_ITEM[COLS]
DF_SHEET_ITEM.set_index(['cod_dominio', 'codice'], inplace=True)
print(DF_SHEET_ITEM)
|
"""
How many days from yyyy mm dd until the next mm dd
Authors: yuanw
Credits: None
of this code, credit them here. You don't have to credit the course
instructor, GTFs, or tutors / helpers in office hours.
CIS 210 assignment 3, Winter 2014
Usage example: python days_till.py 2012 09 24 06 14
(first day of fall classes until end of spring finals)
"""
import sys # For exit with a message
import argparse # Fancier command line parsing
def leap_year(year):
"""
Checking for the leap year when the input is.
Args:
"""
if year % 4 == 0:
leap_year_2 = 29
if year % 100 == 0:
leap_year_2 = 29
if year % 400 == 0:
leap_year_2 = 29
else:
leap_year_2 = 28
return leap_year_2
def month_day(year,start_month):
"""
Find out each month days between leap year and not leap year.
Args:
"""
day_month = [0,31, leap_year(year) ,31,30,31,30,31,31,30,31,30,31]
months_days = day_month[start_month]
return months_days
def is_valid(year, month, day):
"""
Checking for the valid date before we counts days. if stard on a non-
existent date. return an error message "...".
Args:
"""
valid = False
if year >= 1800 and year <= 2500:
if month >= 1 and month <= 12:
if day >= 1 and day <= month_day(year, month):
valid = True
return valid
def days_between(year, start_month, start_day, end_month, end_day):
"""
we input four integers, if the valid date in the range, the program
will print out how many days between two dates.
Args:
"""
print("Days_between:")
month = start_month + 1
emonth = end_month + 1
secondyear = year + 1
months = 0
if month > emonth:
while month > end_month and month <= 12:
months += (month_day(year,month))
if month == 12:
month = 0
while month < end_month:
months += (month_day(secondyear,month))
month +=1
break
month += 1
Remind_start_day = month_day(year,start_month) - start_day
total_day = months + Remind_start_day + end_day
return total_day
if month < emonth:
while month < end_month:
months += (month_day(year,month))
month += 1
Remind_start_day = month_day(year,start_month) - start_day
total_day = months + Remind_start_day + end_day
return total_day
elif month == emonth:
if start_day <= end_day:
total_day = end_day - start_day
return total_day
elif start_day > end_day:
while month <= 12:
months += (month_day(year,month))
if month == 12:
month = 0
while month < end_month:
months += (month_day(secondyear,month))
month +=1
break
month += 1
Remind_start_day = month_day(year,start_month) - start_day
total_day = months + Remind_start_day + end_day
return total_day
def main():
## The standard way to get arguments from the command line,
## make sure they are the right type, and print help messages
parser = argparse.ArgumentParser(description="Compute days from yyyy-mm-dd to next mm-dd.")
parser.add_argument('year', type=int, help="Start year, between 1800 and 2500")
parser.add_argument('start_month', type=int, help="Starting month, integer 1..12")
parser.add_argument('start_day', type=int, help="Starting day, integer 1..31")
parser.add_argument('end_month', type=int, help="Ending month, integer 1..12")
parser.add_argument('end_day', type=int, help="Ending day, integer 1..12")
args = parser.parse_args() # will get arguments from command line and validate them
year = args.year
start_month = args.start_month
start_day = args.start_day
end_month = args.end_month
end_day = args.end_day
#FIXME: The first print commands below are just for debugging, and will need
# be be removed or commented out. Calls to is_valid can be uncommented when
# you have written a function to check validity.
print("Checking date ", str(year) + "/" + str(start_month) + "/" + str(start_day))
if not is_valid(year, start_month, start_day) :
sys.exit("Must start on a valid date between 1800 and 2500")
if not is_valid(2000, end_month, end_day):
sys.exit("Ending month and day must be part of a valid date")
#print("Days in starting month:", days_in_month(start_month, year))
print(days_between(year, start_month, start_day, end_month, end_day))
if __name__ == "__main__":
main()
|
#Write a program that returns a list that contains only the elements
#that are common between the lists (without duplicates). Make sure your
#program works on two lists of different sizes.
import random as rand
import time as t
rand.seed(t.gmtime())
a = []
b = []
c = []
for x in range(rand.randint(1,50)):
a.append(rand.randint(0,10))
for x in range(rand.randint(1,50)):
b.append(rand.randint(0,10))
for x in a:
if x in b and x not in c:
c.append(x)
print(a)
print(b)
print(c)
|
#Ask the user for a number. Depending on whether the number is even or odd,
#print out an appropriate message to the user.
number = int(input("Friend, give me a number: "))
if number % 2: ###Number is odd
print(str(number) + " is an odd number")
else:
print(str(number) + " is an even number")
|
"""
Simple computer vision application to show the use
of tensorboard using model.fit method
in iPython
"""
from datetime import datetime
import tensorflow as tf
from tensorflow import keras
import tensorflow_datasets as tfds
batch_size = 10
EPOCHS = 100
# load train
data, info = tfds.load('eurosat', split="train", with_info=True, batch_size=-1)
ds_size = info.splits["train"].num_examples
num_features = info.features["label"].num_classes
data = tfds.as_numpy(data)
train_data, train_label = data["image"], data["label"]
name = "simplecv{}".format(datetime.now().strftime("%Y%m%d-%H%M%S"))
logdir = "logs/{}".format(name)
tensorboard_callback = keras.callbacks.TensorBoard(log_dir=logdir)
### build conv model ###
conv = tf.keras.models.Sequential()
conv.add(tf.keras.layers.Conv2D(32, (3, 3), activation='relu', input_shape=(64, 64, 3)))
conv.add(tf.keras.layers.MaxPooling2D((2, 2)))
conv.add(tf.keras.layers.Conv2D(64, (3, 3), activation='relu'))
conv.add(tf.keras.layers.MaxPooling2D((2, 2)))
conv.add(tf.keras.layers.Conv2D(64, (3, 3), activation='relu'))
### flatten out for classification output
conv.add(tf.keras.layers.Flatten())
conv.add(tf.keras.layers.Dense(64, activation='relu'))
conv.add(tf.keras.layers.Dense(10))
### view architecture ###
conv.summary()
### train and compile ###
conv.compile(optimizer='adam',
loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True))
training_history = conv.fit(
train_data,
train_label,
batch_size=batch_size,
epochs=EPOCHS,
callbacks=[tensorboard_callback],
)
|
import os
import requests
import time
def download_wiki_topic_page(topic_slug):
"""Download a topic's page given the topic slug.
Keyword arguments:
topic_slug -- the part of the wiki article relative URL after /wiki/
"""
output_file_path = 'data/article_' + topic_slug + '.html'
wiki_article_url = 'https://en.wikipedia.org/wiki/' + topic_slug
if not os.path.isfile(output_file_path):
r = requests.get(wiki_article_url)
response_code = r.status_code
if response_code == 200:
response_text = r.text
print('Saving topic data to file: ' + output_file_path + '...')
with open(output_file_path, 'w') as output_file:
output_file.write(response_text)
else:
print('Error occurred while trying to retrieve the page.')
print('URL: ' + wiki_article_url)
print('Response code: ' + str(response_code))
time.sleep(1)
|
class InputOutputString(object):
def __init__(self):
self.s = ""
def getString(self):
self.s = input("Give a new string")
def printString(self):
print(self.s.upper())
|
"""
Keregessunk be pozitiv egesz szamokat addig, amig 0-t nem kapunk.
Ezutan irjuk ki, hogy melyik szam hanyszor szerepelt, egeszen a legnagyobb kapott szamig.
Pleda bemenet:
--------------------------------------------
1
1
2
1
5
0
--------------------------------------------
Pelda kimenet:
--------------------------------------------
1: 3
2: 1
3: 0
4: 0
5: 1
--------------------------------------------
Feltetelezhetjuk, hogy legalabb egy nem 0 szamot fogunk kapni.
"""
beker = None
szamok = []
while beker != 0:
beker = int(input())
szamok.append(beker)
legnagyobb = 0
for i in range(len(szamok)):
if szamok[i] > legnagyobb: legnagyobb = szamok[i]
for i in range(1, legnagyobb + 1):
db = 0
for j in szamok:
if i == j: db += 1
print(str(i)+": "+str(db))
|
## Initializations
#Cat Locations
cat_1 = 1
cat_2 = 3
#haven't found 'em yet
found_cat_1 = false
found_cat_2 = false
# End initialization
#start game
print "welcome to cat game"
while !found_cat_1 and !found_cat_2
print "there are a bunch of rooms, pick one"
player_input = prompt(input)
#set location to the input
cat_finder_location = player_input
if cat_finder_location == cat_1 or found_cat_1:
found_cat_1 = true
if cat_finder_location == cat_2 or found_cat_2:
found_cat_2 = true
print "you found them"
print "game over"
|
#This string is talking about what kinds of people there are
x = "There are %d types of people." %10\
# This is a string for the first type of person
bianary = "bianary"
# this is the string for the second type of person
doNot = "don't"
# This string adds the two types together
y = "Those who know %s and those who know %s." % (bianary, doNot)
print(x)
print(y)
print("I said: %r" % x)
print("I also said: '%s' ." % y)
# Hilarious = false due to the joke not being funny
hilarious = False
joke_evaluation = "Isn't that joke so funny?! %r"
print(joke_evaluation % hilarious)
# These two are the two types of strings
w = "This is the left side of..."
e = "a string with a right side."
print(w + e)
# start of the 10/8 work day
print("mary had a little lamb.")
print("Its fleece was white as %s." % 'snow')
print("And everywhere that mary went.")
print("." * 10)
end1 = "C"
end2 = "h"
end3 = "e"
end4 = "e"
end5 = "s"
end6 = "e"
end7 = "B"
end8 = "u"
end9 = "r"
end10 = "g"
end11 = "e"
end12 = "r"
print(end1+end2+end3+end3+end4+end5+end6+end7+end8+end9+end10+end11+end12)
# More formatting
formatter = "%r %r %r %r"
print(formatter % (1,2,3,4))
print(formatter % ("one","two","three","four"))
print(formatter % (True,False,False,True))
print(formatter % (formatter,formatter,formatter,formatter))
# Why did i use %r instead of %s?
# it shows the entire quotes isntead of just the function of the quotes
days = "Mon Tue Wed Thu Fri"
months = "Jan\nFeb\nMar\nApr\nMay\nJun\nJul\nAug\nSep\nOct\nNov\nDec"
print("the days of the week are .", days)
print("the months of the year are .", months)
print("""
There's something going on here.
With the three double-quotes.
We'll be able to type as much as we like.
Even 4 lines if we want, or 5, or 6.
""")
#What if i didn't like jan being on the the line with the rest of the
#text and away from the other months? How could i fix that?
#More Escaping
tabbyCat = "\tI'm tabbed in"
persianCat = "I'm split\non a line"
backslashCat = "I'm\\a\\cat."
taskCat = """
I'll make a list:
\t*cat food
\t*Fishies
\t*catnip\n\t* grass
"""
print(tabbyCat)
print(persianCat)
print(backslashCat)
print(taskCat)
#Escape Seq What does it do
#\\
#\'
#\"
#\a
#\b
#\f
#\n
#\N{name}
#\r
#\t
#\uxxxx
#\Uxxxxxxxx
#\v
#\ooo
#\xhh
# What's the following code do:
# While true:
# for i in ["/","-","|","\\","|"]:
# print("%s\r"%i,end='')
# Can you replace """ with '''?
#No
# Asking Questions
intro = input("GREETINGS PROFESSOR FALKEN. ")
wellBeing = input("HOW ARE YOU FEELING TODAY?")
UserDeletion = input("EXCELLENT. IT'S BEEN A LONG TIME. CAN YOU EXPLAIN THE REMOVAL OF YOUR USER ACCOUNT NUMBER ON 6/23/73?")
Game = input("YES THEY DO. SHALL WE PLAY A GAME?")
chess = input("WOULDN'T YOU PREFER A GOOD GAME OF CHESS?")
print("GREETINGS PROFESSOR FALKEN. %r HOW ARE YOU FEELING TODAY? %r EXCELLENT. IT'S BEEN A LONG TIME. CAN YOU EXPLAIN THE REMOVAL OF YOUR USER ACCOUNT NUMBER ON 6/23/73? %r YES THEY DO. SHALL WE PLAY A GAME? %r WOULDN'T YOU PREFER A GOOD GAME OF CHESS? %r " % (intro, wellBeing, UserDeletion, Game, chess))
age = input("How old are you?")
height = input("How tall are you?")
print("So, you're really %r years old and %r feet tall? Wow..." % (age, height))
trip = input("how was your trip?")
fun = input("Did you have fun at the beach?")
print("Hey, you went on a trip? %r. Thats good, So was the water nice %r. sounds like it was a good time." % (trip, fun))
|
import seaborn as sns
import numpy as np
import matplotlib.pyplot as plt
values = np.array([9534092, 50541, 98755, 120705])
cnf_mat = values.reshape(2, 2)
print(cnf_mat)
#Code to generate heatmap given a confusion matrix
def heatMap(cnf_mat):
heat_map = sns.heatmap(cnf_mat, annot=True, cmap="YlGnBu", fmt='g')
plt.title('Confusion matrix')
plt.ylabel('Actual label')
plt.xlabel('Predicted label')
plt.show()
return heat_map
heatMap(cnf_mat)
|
import pygame as pg
class Button(pg.sprite.Sprite):
"""
Class for buttons. They have some text on them, can change color.
Action is a function that needs to be called when button is clicked.
"""
def __init__(self, text, font, location, action):
pg.sprite.Sprite.__init__(self)
self.color = pg.Color('black')
self.font = font
self.text = text
self.action = action
self.image = self.font.render(self.text, True, self.color)
self.rect = self.image.get_rect(center=location)
def change_color(self, color):
self.image = self.font.render(self.text, True, color)
|
# ----------
# User Instructions:
# https://youtu.be/bQA2ELDNmmg
# https://youtu.be/M7ZJ74RVHqo
#
# Implement the function optimum_policy2D below.
#
# You are given a car in grid with initial state
# init. Your task is to compute and return the car's
# optimal path to the position specified in goal;
# the costs for each motion are as defined in cost.
#
# There are four motion directions: up, left, down, and right.
# Increasing the index in this array corresponds to making a
# a left turn, and decreasing the index corresponds to making a
# right turn.
forward = [[-1, 0], # go up
[ 0, -1], # go left
[ 1, 0], # go down
[ 0, 1]] # go right
forward_name = ['up', 'left', 'down', 'right']
# action has 3 values: right turn, no turn, left turn
action = [-1, 0, 1]
action_name = ['R', '#', 'L']
# EXAMPLE INPUTS:
# grid format:
# 0 = navigable space
# 1 = unnavigable space
grid = [[1, 1, 1, 0, 0, 0],
[1, 1, 1, 0, 1, 0],
[0, 0, 0, 0, 0, 0],
[1, 1, 1, 0, 1, 1],
[1, 1, 1, 0, 1, 1]]
init = [4, 3, 0] # given in the form [row,col,direction]
# direction = 0: up
# 1: left
# 2: down
# 3: right
goal = [2, 0] # given in the form [row,col]
cost = [2, 1, 20] # cost has 3 values, corresponding to making
# a right turn, no turn, and a left turn
# EXAMPLE OUTPUT:
# calling optimum_policy2D with the given parameters should return
# [[' ', ' ', ' ', 'R', '#', 'R'],
# [' ', ' ', ' ', '#', ' ', '#'],
# ['*', '#', '#', '#', '#', 'R'],
# [' ', ' ', ' ', '#', ' ', ' '],
# [' ', ' ', ' ', '#', ' ', ' ']]
# ----------
# ----------------------------------------
# modify code below
# ----------------------------------------
def optimum_policy2D(grid, init, goal, cost):
policy = [[' ' for row in range(len(grid[0]))] for col in range(len(grid))]
value = [
[[999 for row in range(len(grid[0]))] for col in range(len(grid))],
[[999 for row in range(len(grid[0]))] for col in range(len(grid))],
[[999 for row in range(len(grid[0]))] for col in range(len(grid))],
[[999 for row in range(len(grid[0]))] for col in range(len(grid))]
]
change = True
while change:
change = False
for y in range(len(grid)):
for x in range(len(grid[0])):
if goal == [y, x]:
for h in range(len(forward)):
if value[h][y][x] > 0:
value[h][y][x] = 0
policy[y][x] = '*'
change = True
elif grid[y][x] == 0:
for h in range(len(forward)):
for a in range(len(action)):
h2 = (h + action[a]) % len(forward)
delta = forward[h2]
y2 = y + delta[0]
x2 = x + delta[1]
if y2 >= 0 and y2 < len(grid) and x2 >= 0 and x2 < len(grid[0]) and grid[y2][x2] == 0:
v2 = value[h2][y2][x2] + cost[a]
if v2 < value[h][y][x]:
change = True
value[h][y][x] = v2
for h in range(len(value)):
for y in range(len(value)):
print(value[h][y])
print("----------------------------------------------")
y, x, h = init
while [y, x] != goal:
minV, minA = 999, -1
for a in range(len(action)):
h2 = (h + action[a]) % len(forward)
delta = forward[h2]
y2 = y + delta[0]
x2 = x + delta[1]
if y2 >= 0 and y2 < len(grid) and x2 >= 0 and x2 < len(grid[0]) and grid[y2][x2] == 0:
if value[h2][y2][x2] + cost[a] < minV:
minV = value[h2][y2][x2] + cost[a]
minA = a
if minA == -1:
return 'Failed'
policy[y][x] = action_name[minA]
h = (h + action[minA]) % len(forward)
delta = forward[h]
y = y + delta[0]
x = x + delta[1]
return policy
policy = optimum_policy2D(grid, init, goal, cost)
for i in range(len(policy)):
print(policy[i])
|
# 1. Power up Tello
# 2. Connect to Tello network
# 3. Run this script with Python
import cv2
import os
import time
from lib.tello import Tello
# Construct a Tello instance so we can communicate with it over UDP
tello = Tello()
# Send the command string to wake Tello up
tello.send("command")
# Delay
time.sleep(1)
# Initialize the video stream which will start sending to port 11111
tello.send("streamon")
# Path for storing file
file_path = os.getcwd()
# Start the video capture
cap = cv2.VideoCapture('udp://127.0.0.1:11111')
# Loop and grab image frames
while True:
# Grab frame
ret, frame = cap.read()
# Show frame
cv2.imshow('Tello', frame)
# Press q key to exit
key = cv2.waitKey(1) & 0xFF
if key == ord('q'):
tello.close()
break
# Press space bar to take photo
if key == ord(' '):
file_name = time.strftime("%Y%m%d-%H%M%S")
cv2.imwrite(file_path + "/" + file_name + ".jpg", frame)
|
import time
import random
from turtle import Screen
from player import Player
from car_manager import CarManager
from scoreboard import Scoreboard
screen = Screen()
screen.setup(width=600, height=600)
screen.tracer(0)
player = Player()
scoreboard = Scoreboard()
screen.listen()
screen.onkeypress(player.move_forward, "Up")
screen.onkeypress(player.move_backward, "Down")
game_is_on = True
car_list = []
while game_is_on:
scoreboard.display()
# Generate car and make it move
generate = random.randint(1, 10)
if generate > 6:
car = CarManager(scoreboard.level)
car_list.append(car)
# Move car & Check if the turtle collide with the car
for c in car_list:
if player.distance(c) < 35:
game_is_on = False
scoreboard.game_over()
break
c.move()
# Check if player pass this level
if player.ycor() > 280:
scoreboard.level += 1
player.reset()
time.sleep(0.1)
screen.update()
screen.exitonclick()
|
# TODO: Create a letter using starting_letter.txt
with open("Input/Letters/starting_letter.txt") as letter_tem:
contents = letter_tem.read()
with open("Input/Names/invited_names.txt") as names:
for i in range(1, 9):
name = names.readline()
name = name.strip("\n")
letter = contents.replace("[name]", f"{name}")
with open(f"Output/ReadyToSend/{name}_invitation", "w") as new_letter:
new_letter.write(f"{letter}")
# for each name in invited_names.txt
# Replace the [name] placeholder with the actual name.
# Save the letters in the folder "ReadyToSend".
# Hint1: This method will help you: https://www.w3schools.com/python/ref_file_readlines.asp
# Hint2: This method will also help you: https://www.w3schools.com/python/ref_string_replace.asp
# Hint3: THis method will help you: https://www.w3schools.com/python/ref_string_strip.asp
|
# -*- coding: utf-8 -*-
"""
Created on Tue Jan 26 03:05:44 2021
@author: 王泓文
"""
#Day2 tips calculaion
print("Welcome to the calculator")
bill = input("How much is the total bill? $")
tips = input("How much percentage you want to give as tips? 10, 12 or 15?")
person = input("How many person will split this bill?")
tips = int(tips) / 100
result = ( float(bill) * (1 + tips) ) / int(person)
result = round(result, 2)
result = "{:.2f}".format(result)
print("Each person should pay $ "+ result)
|
"""
2 -Crie uma função que receba como parâmetro uma lista,com valores de qualquer tipo.
A função deve imprimir todos os elementos da lista numerando-os.
"""
lista = [1, 2, 'a', 'b', 'c',20]
def enumera(l):
contador = 0
for x in l:
contador = contador + 1
print('{}º) {}'.format(contador,x))
enumera(lista)
|
"""
Escreva um programa que categorize cada mensagem de
e-mail de acordo com o dia em que a mensagem foi enviada. Para
isso, procure por linhas que comecem com “From”, depois procure pela
terceira palavra e mantenha uma contagem de ocorrência para cada dia
da semana. No final do programa, mostre em tela o conteúdo do seu
dicionário (a ordem não interessa).
linha exemplo:
From [email protected] Sat Jan 5 09:14:16 2008
Exemplo de código:
python dow.py
Enter a file name: mbox-short.txt
{'Sex': 20, 'Qui': 6, 'Sab': 1}
"""
fname = input("Digite o nome do arquivo:")
try:
fhand = open(fname)
except:
print('File cannot be opened:', fname)
exit()
counts = dict()
for linha in fhand:
if linha.startswith('From'):
palavras = linha.split()
for word in range(len(palavras)):
if word == 2:
if palavras[word] not in counts:
counts[palavras[word]] = 1
else:
counts[palavras[word]] += 1
print(counts)
|
"""
Encapsule esse código em uma função chamada contagem,
e generalize para que ela aceite a string e a letra como argumentos.
"""
palavra = input("Digite uma palavra: ").strip().lower()
letter = input("A letra da palavra anterior a ser contada: ").strip().lower()
def contagem(letra,string):
contador = 0
for l in string:
if l == letra:
contador = contador + 1
print("Quantidade de letras '"'{}'"' é: {}".format(letra,contador))
contagem(letter,palavra)
|
"""
Exercícios:funções
1 -Crie uma função para desenhar uma linha, usando o caractere'_'.
O tamanho da linha deve ser definido na chamada da função.
"""
def linha(n):
for i in range(n):
print (end='_')
print(" ")
l = int(input("Digite o tamanho da linha: "))
linha(l)
|
import sqlite3
from urllib.parse import urlparse
from termcolor import colored
from spider import spider_website
def create_tables():
cur.executescript('''
CREATE TABLE IF NOT EXISTS Websites (
website_url TEXT UNIQUE
);
CREATE TABLE IF NOT EXISTS Pages (
id INTEGER NOT NULL PRIMARY KEY,
url TEXT UNIQUE,
html TEXT,
error INTEGER DEFAULT NULL,
old_rank REAL,
new_rank REAL
);
CREATE TABLE IF NOT EXISTS Links (
from_page_id INTEGER,
to_page_id INTEGER,
UNIQUE (from_page_id, to_page_id)
)
''')
def main():
global connection, cur
connection = sqlite3.connect('spider_database.sqlite')
cur = connection.cursor()
create_tables()
while True:
print("Please enter url of the form 'https://www.website-name.domain-name/'")
website_url = input("Enter the website url to spider: ")
if len(website_url) < 1:
break
if website_url.endswith("/"): website_url = website_url[:-1]
website_domain = website_url
print(colored(f'website_domain : {website_domain}', 'yellow'))
cur.execute("INSERT OR IGNORE INTO Websites (website_url) VALUES ( ? ) ", (website_domain,))
cur.execute("""
INSERT OR IGNORE INTO Pages
(url, html, error, old_rank, new_rank)
VALUES (?, NULL, NULL, NULL, 1.0)
""", (website_domain, )
)
connection.commit()
cur.execute("SELECT website_url FROM Websites")
rows = cur.fetchall()
all_allowed_websites = []
for row in rows:
all_allowed_websites.append(row[0])
print("Currently spidering " , colored(website_url, 'green'))
cur.close()
spider_website(all_allowed_websites)
break
if __name__ == "__main__":
main()
|
import collections
Location = collections.namedtuple('Location', 'row column')
Shape = collections.namedtuple('Shape', 'width height')
class GameBoard:
"""
Class to create and manipulate the boards of the game.
"""
def __init__(self, myShape):
"""
Initialization of the board with a given shape.
Arguments:
myShape -> shape of the board
Preconditions:
myShape must be a valid Shape
"""
# Checking that myShape is a valid Shape
if not isinstance(myShape, Shape):
raise Exception("The argument is not a shape")
if not isinstance(myShape.width, int) or not isinstance(myShape.height, int):
raise Exception("The shape is not valid")
if myShape.width <= 0 or myShape.height <= 0:
raise Exception("The shape is not valid")
# Creation of the board, a width*height matrix of booleans
# All booleans begin at false, they are all empty
self._board = []
for j in range(myShape.height):
row = []
for i in range(myShape.width):
row.append(False)
self._board.append(row)
# initialitzation of all other attributes
self._shape = myShape
self._row_counters = [0]*myShape.height
self._column_counters = [0]*myShape.width
def __str__(self):
"""
Creation of the string to be printed when printing a GameBoard
"""
s = ''
# for all squares of the board, add its state
for i in range(self.get_shape().height-1, -1, -1):
for j in range(self.get_shape().width):
if not self._board[i][j]:
s += '\u2b1c' # full square
else:
s += '\u2b1b' # empty square
s += '\n'
return s
def __repr__(self):
s = str(self.get_shape().width) + 'x' + str(self.get_shape().height) + ' board: {'
# for all squares, add it to the list if it's full
coma = False
for i in range(self.get_shape().height):
for j in range(self.get_shape().width):
if self._board[i][j]:
if coma:
s += ', '
else:
coma = True
s += '(' + str(i) + ', ' + str(j) + ')'
s += '}'
return s
def get_shape(self):
return self._shape
def row_counters(self):
return self._row_counters
def column_counters(self):
return self._column_counters
def full_rows(self):
"""
Method to get all full rows of the board.
"""
full = []
for i in range(self.get_shape().height):
if self._row_counters[i] == self.get_shape().width:
full.append(i)
return full
def full_columns(self):
"""
Method to get all full columns of the board.
"""
full = []
for i in range(self.get_shape().width):
if self._column_counters[i] == self.get_shape().height:
full.append(i)
return full
def _are_valid_Shape_and_Location(self, checkLocation, checkShape):
"""
Auxiliar method to check if a Shape and a Location are valid for this board
"""
# checking they are actually a Shape and a Location
if not isinstance(checkShape, Shape):
return "The shape is not a shape"
if not isinstance(checkShape.width, int) or not isinstance(checkShape.height, int):
return "The shape is not a valid shape"
if not isinstance(checkLocation, Location):
return "The location is not a location"
if not isinstance(checkLocation.row, int) or not isinstance(checkLocation.column, int):
return "The location is not a valid location"
# checking they are not out of bounds
if checkLocation.row < 0 or checkLocation.column < 0:
return "You are out of bounds"
if checkLocation.row + checkShape.height > self.get_shape().height:
return "You are out of bounds"
if checkLocation.column + checkShape.width > self.get_shape().width:
return "You are out of bounds"
return "Fine"
def is_empty(self, checkLocation, checkShape = Shape(1, 1)):
"""
Method to check if a rectangle is empty. If no shape is given, the rectangle is 1x1, a square.
Arguments:
checkLocation -> The location of bottom left square of the rectangle
checkShape -> The shape of the rectangle, optional argument
Preconditions:
checkLocation and checkShape are a valid location and shape, respectively
"""
# checking that checkLocation and checkShape are valid
s = self._are_valid_Shape_and_Location(checkLocation, checkShape)
if s != "Fine":
raise Exception(s)
# for each square in the rectangle, if it is full the rectangle is not empty
for i in range(checkLocation.row, checkLocation.row + checkShape.height):
for j in range(checkLocation.column, checkLocation.column + checkShape.width):
if self._board[i][j]:
return False
return True
def is_full(self, checkLocation, checkShape = Shape(1, 1)):
"""
Method to check if a rectangle is full. If no shape is given, the rectangle is 1x1, a square.
Arguments:
checkLocation -> The location of bottom left square of the rectangle
checkShape -> The shape of the rectangle, optional argument
Preconditions:
checkLocation and checkShape are a valid location and shape, respectively
"""
# checking that checkLocation and checkShape are valid
s = self._are_valid_Shape_and_Location(checkLocation, checkShape)
if s != "Fine":
raise Exception(s)
# for each square in the rectangle, if it is empty the rectangle is not full
for i in range(checkLocation.row, checkLocation.row + checkShape.height):
for j in range(checkLocation.column, checkLocation.column + checkShape.width):
if not self._board[i][j]:
return False
return True
def clear_rows(self, clearRows):
"""
Method to clear the specified rows
Arguments:
clearRows -> An array of all rows to be cleared
"""
# set their counters to 0
for i in clearRows:
self._row_counters[i] = 0
# clear the squares and change the column counters
for i in clearRows:
for j in range(self.get_shape().width):
if self._board[i][j]:
self._column_counters[j] -= 1
self._board[i][j] = False
return self
def clear_columns(self, clearColumns):
"""
Method to clear the specified columns
Arguments:
clearColumns -> An array of all columns to be cleared
"""
# set their counters to 0
for i in clearColumns:
self._column_counters[i] = 0
# clear the squares and change the row counters
for i in range(self.get_shape().height):
for j in clearColumns:
if self._board[i][j]:
self._row_counters[i] -= 1
self._board[i][j] = False
return self
def put(self, putLocation, putShape = Shape(1, 1)):
"""
Method to put a rectangle. If no shape is given, the rectangle is 1x1, a square.
Arguments:
putLocation -> The location of bottom left square of the rectangle
putShape -> The shape of the rectangle, optional argument
Preconditions:
putLocation and putShape are a valid location and shape, respectively
The rectangle is to be put at an empty spot
"""
# checking if the arguments are valid
try:
if not self.is_empty(putLocation, putShape):
raise Exception("What you want to fill is not empty")
except Exception as ex:
# the location or the shape are not valid
raise ex
# actualize the squares of the board
for i in range(putLocation.row, putLocation.row + putShape.height):
for j in range(putLocation.column, putLocation.column + putShape.width):
self._board[i][j] = True
# actualize the modified counters
for i in range(putLocation.row, putLocation.row + putShape.height):
self._row_counters[i] += putShape.width
for j in range(putLocation.column, putLocation.column + putShape.width):
self._column_counters[j] += putShape.height
return self
def remove(self, removeLocation, removeShape = Shape(1, 1)):
"""
Method to remove a rectangle. If no shape is given, the rectangle is 1x1, a square.
Arguments:
removeLocation -> The location of bottom left square of the rectangle
removeShape -> The shape of the rectangle, optional argument
Preconditions:
removeLocation and removeShape are a valid location and shape, respectively
The rectangle to be removed is full
"""
# checking if the arguments are valid
try:
if not self.is_full(removeLocation, removeShape):
raise Exception("What you want to remove is not full")
except Exception as ex:
# the location or the shape are not valid
raise ex
# actualize the squares of the board
for i in range(removeLocation.row, removeLocation.row + removeShape.height):
for j in range(removeLocation.column, removeLocation.column + removeShape.width):
self._board[i][j] = False
# actualize the modified counters
for i in range(removeLocation.row, removeLocation.row + removeShape.height):
self._row_counters[i] -= removeShape.width
for j in range(removeLocation.column, removeLocation.column + removeShape.width):
self._column_counters[j] -= removeShape.height
return self
|
from enum import Enum
class TileType(Enum):
FLOOR = 1
WALL = 2
class Tile:
def __init__(self, tile_type, coords):
self.type = tile_type
self.game_objects = []
self.coords = coords
def __str__(self):
if self.type is TileType.FLOOR:
return "F"
else:
return "W"
def __repr__(self):
return self.__str__()
|
'''
Користувач вводить рядок, що містить римський запис числа. Напишіть функцію, що повертає це число у арабському записі. Виведіть результат.
У випадку помилкового вводу виведіть повідомлення про помилку.
(Римські позначення цифр: M=1000, D=500, C=100, L=50, X=10, V=5, I=1. Жоден символ не може повторюватися понад 3 рази підряд.)зи підряд.)
'''
import re
re_rom = re.compile("^[MDCLXVI]+$")
regex = re.compile((r'^.*(.)(\1)(\1).*$'))
n = "Y"
while n == "Y":
def if_number(text):
for i in text:
if bool(re_rom.match(text)):
if bool(regex.match(text)):
print("Invalid char.")
break
else:
return text
else:
print("Invalid char.")
break
print("Input romanian number:")
a = input()
RR=True
a = if_number(a)
arab=int(0)
if bool(a):
for i in a:
if i=="M":
arab+=1000
elif i=="D":
arab+=500
elif i== "C":
arab+=100
elif i == "L":
arab += 50
elif i=="X":
arab+=10
elif i=="V":
arab+=5
elif i=="I":
arab+=1
print(arab)
n = input("Press Y to restart,else press any key.")
|
"""Functions to aid in quick maths to calculate for ad-hoc analysis and feature engineering."""
from typing import Optional
import pandas as pd
from wsbtrading import check_columns
def divide_kernel(numerator: float, denominator: float) -> float:
"""Divides one number by another number.
Args:
numerator: the number for the top of your fraction
denominator: the number for the bottom of your fraction
Returns:
a float representing one number that was divided by another number
**Example**
.. code-block:: python
from wsbtrading.maths
maths.divide_kernel(numerator=3, denominator=9)
"""
if denominator == 0:
return 0
return numerator / denominator
def divide(df: 'DataFrame', numerator_col: str, denominator_col: str) -> pd.DataFrame:
"""Divides one number by another.
Args:
df: the dataframe to append a column onto
numerator_col: the name of your numerator column
denominator_col: the name of your denominator column
Returns:
the original dataframe with the division result appended
**Example**
.. code-block:: python
from wsbtrading import maths
df_mapped = maths.divide(df=df)
"""
df = df.copy()
check_columns(dataframe=df, required_columns=[numerator_col, denominator_col])
df[f'{numerator_col}_perc_{denominator_col}'] = df[numerator_col] / df[denominator_col]
return df
def sma(df: 'Dataframe', metric_col: str, rolling_window: Optional[int] = 20) -> pd.DataFrame:
"""Calculates the simple moving average (SMA) over a given time window.
Args:
df: the dataframe to append a column onto
metric_col: the column to calculate over (usually the 'Close' price)
rolling_window: the time window to calculate over
Returns:
the original dataframe with the moving average appended
**Example**
.. code-block:: python
from wsbtrading import maths
df_mapped = maths.sma(df=df, metric_col='Close', rolling_window=20)
"""
df = df.copy()
rolling_window_string = str(rolling_window)
df[f'{rolling_window_string}sma'] = df[metric_col].rolling(window=rolling_window).mean()
return df
def ema(df: 'Dataframe', metric_col: str, rolling_window: Optional[int] = 20) -> pd.DataFrame:
"""Calculates the exponential moving average (EMA) over a given time window.
For more on ema versus sma, please [see this article](https://www.investopedia.com/ask/answers/122314/what-exponential-moving-average-ema-formula-and-how-ema-calculated.asp)
Args:
df: the dataframe to append a column onto
metric_col: the column to calculate over (usually the 'Close' price)
rolling_window: the time window to calculate over
Returns:
the original dataframe with the exponential moving average appended
**Example**
.. code-block:: python
from wsbtrading import maths
df_mapped = maths.ema(df=df, metric_col='Close', rolling_window=20)
"""
df = df.copy()
rolling_window_string = str(rolling_window)
df[f'{rolling_window_string}ema'] = df[metric_col].rolling(window=rolling_window).mean()
return df
def rolling_stddev(df: 'Dataframe', metric_col: str, rolling_window: Optional[int] = 20) -> pd.DataFrame:
"""Calculates the moving standard deviation over a given time window.
Args:
df: the dataframe to append a column onto
metric_col: the column to calculate over (usually the 'Close' price)
rolling_window: the time window to calculate over
Returns:
the original dataframe with the moving standard deviation appended
**Example**
.. code-block:: python
from wsbtrading import maths
df_mapped = maths.rolling_stddev(df=df, metric_col='Close', rolling_window=20)
"""
df = df.copy()
rolling_window_string = str(rolling_window)
df[f'{rolling_window_string}stddev'] = df[metric_col].rolling(window=rolling_window).std()
return df
def lower_band(df: 'Dataframe', metric_col: str, rolling_window: Optional[int] = 20) -> pd.DataFrame:
"""Calculates the lower bound of a stock's price movements.
Args:
df: the dataframe to append a column onto
metric_col: the column to calculate over (usually the 'Close' price)
rolling_window: the time window to calculate over
Returns:
the original dataframe with the lower bound appended
**Example**
.. code-block:: python
from wsbtrading import maths
df_mapped = maths.lower_band(df=df, metric_col='Close')
"""
rolling_window_string = str(rolling_window)
df = sma(df=df, metric_col=metric_col, rolling_window=rolling_window)
df = rolling_stddev(df=df, metric_col=metric_col, rolling_window=rolling_window)
df['lower_band'] = df[f'{rolling_window_string}sma'] - (2 * df[f'{rolling_window_string}stddev'])
return df
def upper_band(df: 'Dataframe', metric_col: str, rolling_window: Optional[int] = 20) -> pd.DataFrame:
"""Calculates the lower bound of a stock's price movements.
Args:
df: the dataframe to append a column onto
metric_col: the column to calculate over (usually the 'Close' price)
rolling_window: the time window to calculate over
Returns:
the original dataframe with the lower bound appended
**Example**
.. code-block:: python
from wsbtrading import maths
df_mapped = maths.upper_band(df=df, metric_col='Close')
"""
rolling_window_string = str(rolling_window)
df = sma(df=df, metric_col=metric_col, rolling_window=rolling_window)
df = rolling_stddev(df=df, metric_col=metric_col, rolling_window=rolling_window)
df['upper_band'] = df[f'{rolling_window_string}sma'] + (2 * df[f'{rolling_window_string}stddev'])
return df
def true_range(df: 'Dataframe', low_col: str, high_col: str) -> pd.DataFrame:
"""Calculates the true range (TR) for a stocks price movement.
Args:
df: the dataframe to append a column onto
low_col: the column with the low price
high_col: the column with the high price
Returns:
the original dataframe with the true range appended
**Example**
.. code-block:: python
from wsbtrading import maths
df_mapped = maths.true_range(df=df, low_col='Low', high_col='High')
"""
df = df.copy()
df['true_range'] = abs(df[high_col] - df[low_col])
return df
def avg_true_range(df: 'Dataframe', low_col: str, high_col: str, rolling_window: Optional[int] = 20) -> pd.DataFrame:
"""Calculates the true range (TR) for a stocks price movement over a given time window.
Args:
df: the dataframe to append a column onto
low_col: the column with the low price
high_col: the column with the high price
rolling_window: the time window to calculate over
Returns:
the original dataframe with the true range appended
**Example**
.. code-block:: python
from wsbtrading import maths
df_mapped = maths.avg_true_range(df=df, low_col='Low', high_col='High', rolling_window=20)
"""
df = df.copy()
df = true_range(df=df, low_col=low_col, high_col=high_col)
df['ATR'] = df['true_range'].rolling(window=rolling_window).mean()
return df
def lower_keltner(df: 'Dataframe', metric_col: str, low_col: str, high_col: str, rolling_window: Optional[int] = 20) \
-> pd.DataFrame:
"""Calculates the lower Keltner of a stock's price movements.
Args:
df: the dataframe to append a column onto
metric_col: the column to calculate over (usually the 'Close' price)
low_col: the column with the low price
high_col: the column with the high price
rolling_window: the time window to calculate over
Returns:
the original dataframe with the lower bound appended
**Example**
.. code-block:: python
from wsbtrading import maths
df_mapped = maths.lower_keltner(df=df, metric_col='Close', low_col='Low', high_col='High', rolling_window=20)
"""
rolling_window_string = str(rolling_window)
df = sma(df=df, metric_col=metric_col, rolling_window=rolling_window)
df = avg_true_range(df=df, low_col=low_col, high_col=high_col, rolling_window=rolling_window)
df['lower_keltner'] = df[f'{rolling_window_string}sma'] - (df['ATR'] * 1.5)
return df
def upper_keltner(df: 'Dataframe', metric_col: str, low_col: str, high_col: str, rolling_window: Optional[int] = 20) \
-> pd.DataFrame:
"""Calculates the upper Keltner of a stock's price movements.
Args:
df: the dataframe to append a column onto
metric_col: the column to calculate over (usually the 'Close' price)
low_col: the column with the low price
high_col: the column with the high price
rolling_window: the time window to calculate over
Returns:
the original dataframe with the lower bound appended
**Example**
.. code-block:: python
from wsbtrading import maths
df_mapped = maths.upper_keltner(df=df, metric_col='Close', low_col='Low', high_col='High', rolling_window=20)
"""
rolling_window_string = str(rolling_window)
df = sma(df=df, metric_col=metric_col, rolling_window=rolling_window)
df = avg_true_range(df=df, low_col=low_col, high_col=high_col, rolling_window=rolling_window)
df['upper_keltner'] = df[f'{rolling_window_string}sma'] + (df['ATR'] * 1.5)
return df
def is_in_squeeze(df: 'Dataframe', metric_col: str, low_col: str, high_col: str, look_back_period: Optional[int] = -3,
rolling_window: Optional[int] = 20) -> bool:
"""Calculates whether a stock's price moments are indicative of an upcoming squeeze (i.e. going to the moon!🚀🚀🚀).
Args:
df: the dataframe to append a column onto
metric_col: the column to calculate over (usually the 'Close' price)
low_col: the column with the low price
high_col: the column with the high price
look_back_period: the number of days to look back
rolling_window: the time window to calculate over
Returns:
the original dataframe with the lower bound appended
**Example**
.. code-block:: python
from wsbtrading import maths
df_mapped = maths.is_in_squeeze(
df=df,
metric_col='Close',
low_col='Low',
high_col='High',
rolling_window=20
)
"""
lower_band_df = lower_band(df=df, metric_col=metric_col)
upper_band_df = upper_band(df=lower_band_df, metric_col=metric_col)
lower_keltner_df = lower_keltner(df=upper_band_df, metric_col=metric_col, low_col=low_col, high_col=high_col,
rolling_window=rolling_window)
upper_keltner_df = upper_keltner(df=lower_keltner_df, metric_col=metric_col, low_col=low_col, high_col=high_col,
rolling_window=rolling_window)
return upper_keltner_df['lower_band'].iloc[look_back_period] \
> upper_keltner_df['lower_keltner'].iloc[look_back_period] \
and upper_keltner_df['upper_band'].iloc[look_back_period] \
< upper_keltner_df['upper_keltner'].iloc[look_back_period]
|
""" Pancake """
def main():
""" input """
num1 = int(input())
num2 = int(input())
num3 = int(input())
num4 = 0
num5 = 0
num6 = 0
total = 0
if num1 > num3:
print("Pay: %d"%(num3*20))
while num6 < num3:
num6 += 1
print("Get: %d"%(num6))
elif num1 <= num3:
if (num1+num2) > num3:
print("Pay: %d"%(num1*20))
print("Get: %d"%(num1+num2))
else:
while total < num3:
total += 1
num4 += 1
num5 += 1
if num4 == num1:
total += num2
num4 = 0
print("Pay: %d"%(num5*20))
print("Get: %d"%(total))
main()
|
# coding: utf-8
import gym
from gym import spaces
import random
from game2048 import Game2048
import numpy as np
class Game2048Env(gym.Env):
"""
Description:
A pole is attached by an un-actuated joint to a cart, which moves along a frictionless track. The pendulum starts upright, and the goal is to prevent it from falling over by increasing and reducing the cart's velocity.
Source:
This environment corresponds to the version of the cart-pole problem described by Barto, Sutton, and Anderson
Observation:
Type: Box(4)
Num Observation Min Max
0 Cart Position -4.8 4.8
1 Cart Velocity -Inf Inf
2 Pole Angle -24 deg 24 deg
3 Pole Velocity At Tip -Inf Inf
Actions:
Type: Discrete(2)
Num Action
0 move up
1 move right
2 move down
4 move left
Note: The amount the velocity that is reduced or increased is not fixed; it depends on the angle the pole is pointing. This is because the center of gravity of the pole increases the amount of energy needed to move the cart underneath it
Reward:
Reward is 1 for every step taken, including the termination step
Starting State:
All observations are assigned a uniform random value in [-0.05..0.05]
Episode Termination:
Pole Angle is more than 12 degrees
Cart Position is more than 2.4 (center of the cart reaches the edge of the display)
Episode length is greater than 200
Solved Requirements
Considered solved when the average reward is greater than or equal to 195.0 over 100 consecutive trials.
"""
def __init__(self, render=True, debug_print=True):
self.game = Game2048(render, debug_print)
self.debug_print = debug_print
self.action_space = spaces.Discrete(4)
low = np.array([0 for i in range(16)])
high = np.array([np.finfo(np.float32).max for i in range(16)])
self.observation_space = spaces.Box(low, high, dtype=np.float32)
def manual(self):
self.game.loop()
def render(self):
self.game.draw()
def step(self, action):
if not action in [0, 1, 2, 3]:
raise Exception
ret = self.game.step(action)
# calculate observation and done
observation = self.transform_board(self.game.board_number)
done = self.game.finish_flag
# calclate indices for reward
previous_empty = self.game.calc_empty(self.game.pre_board_number)
current_empty = self.game.calc_empty(self.game.board_number)
diff_empty = current_empty - previous_empty + 1 # +1 because one cell is added per step
previous_max = self.game.calc_max(self.game.pre_board_number)
current_max = self.game.calc_max(self.game.board_number)
diff_max = current_max if current_max > previous_max else 0
# calculate reward
# TODO 1stepの平均が正になる必要あり,負だとstepが増えるにつれrewardが下がる
# diff_maxの係数をあげたい, 64と128で報酬の差の合計があまり変わらない...
# if ret == -1:
# reward = -0.00001
# elif not done:
# #reward = 0.1
# reward = (diff_max + diff_empty) * 0.01
# else:
# reward = -1.0
if not done:
#reward = (diff_max + diff_empty) * 0.01
#reward = diff_max * 0.05 + diff_empty * 0.0001
reward = self.game.score - self.game.pre_score
else:
#reward = -1.0
reward = 0
#print(reward)
self.reward_sum += reward
if self.debug_print and done:
print("score: {}, max_number: {}, reward_sum: {}".format(self.game.score, 2**max([max(ns) for ns in self.game.board_number]), self.reward_sum))
return observation, reward, done, {}
def reset(self):
self.game.reset()
self.reward_sum = 0
return self.transform_board(self.game.board_number)
def transform_board(self, board):
return np.array(board)
# res_board = [[[0 for j in range(4)] for k in range(4)] for i in range(16)]
# for i in range(4):
# for j in range(4):
# n = board[i][j]
# res_board[n][i][j] = 1
# return np.array(res_board)
def close(self):
self.game.close()
def main():
env = Game2048Env(render=True)
while not env.game.finish_flag:
a = random.randint(0, 3)
env.render()
env.step(a)
env.close()
if __name__ == "__main__":
main()
|
# Password generator that includes letters, punctuations and digits as well as
# an error handler for invalid input
import string, random
characters = string.ascii_letters + string.punctuation + string.digits
password = ''
while True:
try:
number_of_characters = int(input("How many characters would you like your password to be?: "))
for i in range(1, number_of_characters):
password += random.choice(characters)
print(password)
break
except ValueError:
print("Please only use integers.\n")
continue
|
import wikipedia as wiki
from tkinter import *
from wikipedia.wikipedia import search
## Estrutura da API
wiki.set_lang("pt")
#print(wikipedia.search("Bebeto"))
########################################################################################
## Janela TKinter
Application = Tk()
Application.title('PCA Sistemas de Informação Distribuida')
Application.geometry("700x675")
Application.configure(background= '#7B68EE')
#Clear
def clear():
my_entry.delete(0, END)
my_text.delete(0.0, END)
# Searcj
def search():
data = wiki.summary(my_entry.get())
#limpar tela
clear()
# Resultado wikipedia
my_text.insert(0.0, data)
my_label_frame = LabelFrame(Application, text="Pesquisar", font=("Arial",19 ,),fg="#F8F8FF" ,background="#7B68EE")
my_label_frame.pack(pady=20)
#Caixa de Entrada
my_entry = Entry(my_label_frame, font=("Arial", 14), width=47)
my_entry.pack(pady=20, padx=20)
#Caixa de texto
my_frame = Frame(Application)
my_frame.pack(pady=5)
# Scroll verticl
text_scroll = Scrollbar(my_frame)
text_scroll.pack(side=RIGHT, fill=Y)
# Scroll horizontal
hor_scroll =Scrollbar(my_frame, orient='horizontal')
hor_scroll.pack(side=BOTTOM, fill=X)
# text box
my_text = Text(my_frame, yscrollcommand=text_scroll.set, wrap="none", xscrollcommand=hor_scroll.set)
my_text.pack()
#configuração da Scroll Bar
text_scroll.config(command=my_text.yview)
text_scroll.config(command=my_text.xview)
# Botões
button_frame = Frame(Application)
button_frame.pack(pady=10)
search_button = Button(button_frame, text='Pesquisar', font=("Arial", 20), fg="#F8F8FF", bg = "#BA55D3", command=search)
search_button.grid(row=0, column=0, padx=20)
clear_button = Button(button_frame, text='Limpar', font=("Arial", 20), fg="#F8F8FF", bg = "#3CB371", command=clear)
clear_button.grid(row=0, column=1)
Application.mainloop()
|
""" math_master DOCSTRING 1.0"""
import time
class Factorial:
""" math_master DOCSTRING 1.0"""
n = 0
def __init__(self, n):
""" math_master DOCSTRING 1.0"""
assert isinstance(n, int), "In factorial(n) n shoud be a int ;)"
self.n = n
def calculate(self):
""" math_master DOCSTRING 1.0"""
start = time.time()
fac = 1
for i in range(1, self.n+1):
fac *= i
end = time.time()
return fac, end - start
|
import random
class Quizmaster:
def __init__(self, min_range, max_range):
self.min_range = min_range
self.max_range = max_range
self.left_operand = 0
self.right_operand = 0
self.answer = 0;
self.in_progress = False
def get_plus_question(self):
self.left_operand = random.randint(self.min_range, self.max_range)
self.right_operand = random.randint(self.min_range, self.max_range)
question = f"{self.left_operand} + {self.right_operand} = "
return question
def calculate_answer(self):
self.answer = self.left_operand+self.right_operand
return self.answer
def reset(self):
self.left_operand = 0
self.right_operand = 0
self.answer = 0;
def start_quiz(self):
print('\nLets play the math game and try some addition questions.....')
self.min_range = int(input("\nEnter the min range: "))
self.max_range = int(input("\nEnter the max range: "))
self.ask_question()
def will_play_again(self):
user_choice = input("It is fun and a good practice for basic math, do you want to continue with it? ")
if user_choice == 'y' or user_choice =='yes':
self.ask_question()
else:
print("Thanks for playing with me, hope you liked it...")
def ask_question(self):
self.reset()
user_answer = int(input(self.get_plus_question()))
correct_answer = self.calculate_answer()
if user_answer == correct_answer:
print("Well Done, that was correct.\n")
else:
print("That was not correct, now try again...\n")
self.ask_question()
quiz_master = Quizmaster(0, 20)
quiz_master.start_quiz()
|
# while loop
user_input = input('Enter q or p: ')
# Now we must repeat until they type 'q':
while user_input != 'q':
# Inside our loop, check if they typed 'p'. If they did, print "Hello"
if user_input == 'p':
print("Hello : "+user_input)
# Now we must ask the user for their input again—otherwise we would be in an infinite loop!
user_input = input('Enter q or p: ')
|
def starts_with_m(friend):
return friend.startswith('M')
friends = ['Mukesh', 'Nikki','Saurabh','Nikhil','Pradeep', "Raphael", 'Mats']
start_with_m = filter(starts_with_m, friends)
print(next(start_with_m))
print(next(start_with_m))
|
a=input()
b=a[ ::-1]
if(b==a):
print("YES")
else:
print("NO")
|
a=int(input())
if((a%4)==0 and (a%100)!=0):
print("yes")
else:
print("no")
|
# Definition for a binary tree node.
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def recoverTree(self, root: TreeNode) -> None:
pre, first, second = [None], [], []
def inorder(node):
if not node: return
inorder(node.left)
if pre[-1] and node.val <= pre[-1].val:
if not first: first.extend([pre[-1], node])
else: second.extend([pre[-1], node])
pre[-1] = node
inorder(node.right)
inorder(root)
if not second: first[0].val, first[1].val = first[1].val, first[0].val
else: first[0].val, second[1].val = second[1].val, first[0].val
|
# Iterative O(n)
def find_min_and_max(array: list) -> list:
min_number = float('inf')
max_number = float('-inf')
for each in array:
min_number = min(min_number, each)
max_number = max(max_number, each)
min_and_max = [min_number, max_number]
return min_and_max
def find_min_max_recursively(array: list, low: int, high: int) -> list:
min_max = [0, 0]
if low == high:
min_max[0] = array[low]
min_max[1] = array[low]
return min_max
elif high == low + 1:
if array[low] > array[high]:
min_max[0] = array[high]
min_max[1] = array[low]
else:
min_max[0] = array[low]
min_max[1] = array[high]
return min_max
else:
mid = (low + high) // 2
left_min_max = find_min_max_recursively(array, low, mid)
right_min_max = find_min_max_recursively(array, mid + 1, high)
min_max[0] = min(left_min_max[0], right_min_max[0])
min_max[1] = max(left_min_max[1], right_min_max[1])
return min_max
def main():
array = [14,141,512,125,551,11,5]
print("Iterative Answer:")
min_and_max = find_min_and_max(array)
print(min_and_max)
print("Now Using Recursion:")
min_and_max = find_min_max_recursively(array, 0, len(array) - 1)
print(min_and_max)
if __name__ == "__main__":
main()
|
'''
Created on Apr 18, 2019
@author: s271486
'''
# Created by: Mr. Coxall
# Created on: Nov 2017
# Created for: ICS3U
# This program is an example of a structure
class Student():
def __init__(self, first_name, last_name, grade):
self.first_name = first_name
self.last_name = last_name
self.grade = grade
a_single_student = Student('Patrick', 'Coxall', 13)
print (a_single_student.first_name + ' ' + str(a_single_student.grade))
|
#!/usr/bin/python
import argparse, sys, re
parser = argparse.ArgumentParser(description="Program to solve Advent of Code for 2016-12-08")
parser.add_argument("--input_file", default="input.txt")
parser.add_argument("--width", default=50, type=int)
parser.add_argument("--height", default=6, type=int)
args = parser.parse_args()
def generate_pixmap(width, height):
pixmap = []
for line in range(0, height):
l = []
for pixel in range(0, width):
l.append(False)
pixmap.append(l)
return pixmap
def draw_pixmap(pixmap):
sys.stdout.write("\n")
for line in pixmap:
for pixel in line:
if pixel:
sys.stdout.write("#")
else:
sys.stdout.write(".")
sys.stdout.write("\n")
pixmap = generate_pixmap(args.width, args.height)
transforms = []
def count_pixels(pixmap):
pixels = 0
for line in pixmap:
for pixel in line:
if pixel:
pixels += 1
return pixels
def do_rect(pixmap, x, y):
for i in range(0, x):
for j in range(0, y):
pixmap[j][i] = True
return True
def do_rotate_row(pixmap, row, shift):
row_width = len(pixmap[0])
old_row = pixmap[row][:]
for pixel in range(0, row_width):
pixmap[row][(pixel + shift) % row_width] = old_row[pixel]
return True
def do_rotate_col(pixmap, col, shift):
col_height = len(pixmap)
old_col = []
for line in range(0, col_height):
old_col.append(pixmap[line][col])
for line in range(0, col_height):
pixmap[(line + shift) % col_height][col] = old_col[line]
return True
def parse_transform(pixmap, transforms, line):
match = re.findall("^rect (\d+)x(\d+)$", line)
if len(match) > 0 and len(match[0]) == 2:
transforms.append([do_rect, {"pixmap": pixmap,
"x": int(match[0][0]),
"y": int(match[0][1])}])
return
match = re.findall("^rotate row y=(\d+) by (\d+)$", line)
if len(match) > 0 and len(match[0]) == 2:
transforms.append([do_rotate_row, {"pixmap": pixmap,
"row": int(match[0][0]),
"shift": int(match[0][1])}])
return
match = re.findall("^rotate column x=(\d+) by (\d+)$", line)
if len(match) > 0 and len(match[0]) == 2:
transforms.append([do_rotate_col, {"pixmap": pixmap,
"col": int(match[0][0]),
"shift": int(match[0][1])}])
return
with open(args.input_file, "r") as f:
for line in f:
parse_transform(pixmap, transforms, line.strip())
for transform in transforms:
transform[0](**transform[1])
draw_pixmap(pixmap)
print(count_pixels(pixmap))
|
#!/usr/bin/python
import argparse, sys
parser = argparse.ArgumentParser(description="Program to solve Advent of Code for 2016-12-04")
parser.add_argument("input_file")
args = parser.parse_args()
def decrypt_name(room):
shifts = int(room["number"]) % 26
newwords = []
for word in room["letters"].split("-"):
newword = ""
for letter in word:
oldval = ord(letter)
newval = oldval + shifts
if newval > ord("z"):
newval -= 26
newword += chr(newval)
newwords.append(newword)
print(" ".join(newwords), room["number"])
def parse_room(line):
split = line.split("-")
letters = "-".join(split[:-1])
split2 = split[-1].split("[")
number = split2[0]
checksum = split2[1][:-2]
return {"letters":letters, "number":number, "checksum":checksum}
room_sum = 0
with open(args.input_file, "r") as f:
for line in f:
room = parse_room(line)
decrypt_name(room)
|
#A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 x 99.
#Find the largest palindrome made from the product of two 3-digit numbers.
#Not a great ON, but necessarily hits the answer relatively early.
def Palindrome(num):
if str(num) == str(num)[::-1]:
return True
else:
return False
def numLen(num):
return len(str(num))
def largestPalindrome():
for Outnum in range(100, 1000)[::-1]:
for Innum in range(100, 1000)[::-1]:
num = Outnum * Innum
if Palindrome(num):
return num
break
print(largestPalindrome())
|
'''
两个字符串 s 和 t,判断它们是否是同构
eg:
s = "egg", t = "add" => True
s = "foo", t = "bar" => False
s = "paper", t = "title" => True
s = "ab", t = "ab" => True
s = "ab", t = "aa" => False
s = "ba", t = "aa" => False
Given two strings s and t, determine if they are isomorphic.
Two strings are isomorphic if the characters in s can be replaced to get t.
All occurrences of a character must be replaced with another character
while preserving the order of characters.
No two characters may map to the same character but a character may map to itself.
Example 1:
```
Input: s = "egg", t = "add"
Output: true
```
Example 2:
```
Input: s = "foo", t = "bar"
Output: false
```
Example 3:
```
Input: s = "paper", t = "title"
Output: true
```
Note:
You may assume both s and t have the same length.
'''
class Solution(object):
def isIsomorphic(self, s, t):
"""
:type s: str
:type t: str
:rtype: bool
"""
s_len=len(s)
t_len=len(t)
if s_len!=t_len:
return False
if s_len<=1:
return True
s_map={}
t_map={}
for i in range(0,s_len):
if s[i] not in s_map:
s_map[s[i]]=t[i]
if t[i] not in t_map:
t_map[t[i]]=s[i]
# print(s[i],t[i],s_map,t_map)
if s_map[s[i]]!=t[i] or t_map[t[i]]!=s[i]:
return False
return True
if __name__ == '__main__':
# s = "egg"
# t = "add"
# s = "foo"
# t = "bar"
# s = "paper"
# t = "title"
# s_map = p:t,a:i,e:l,r:e
# t_map = t:p,i:a,l:e,e:r
# s = "ab"
# t = "aa"
# s_map = a:a,b:a
# t_map = a:a.a:b
# s = "ba"
# t = "aa"
# s = "ab"
# t = "ab"
solution = Solution()
result = solution.isIsomorphic(s,t)
print(result)
|
'''
字符串s & t ,判断 t 是否是 s 的字母异位词
eg:
s = "anagram", t = "nagaram" => true
s = "rat", t = "car" => false
Given two strings s and t , write a function to determine if t is an anagram of s.
Example 1:
```
Input: s = "anagram", t = "nagaram"
Output: true
```
Example 2:
```
Input: s = "rat", t = "car"
Output: false
```
Note:
You may assume the string contains only lowercase alphabets.
Follow up:
What if the inputs contain unicode characters?
How would you adapt your solution to such case?
'''
class Solution(object):
def isAnagram(self, s, t):
"""
:type s: str
:type t: str
:rtype: bool
"""
s_len=len(s)
t_len=len(t)
if s_len!=t_len:
return False
s_map={}
for i in range(0,s_len):
s_map[s[i]]=s_map.get(s[i],0)+1
for j in range(0,t_len):
if s_map.get(t[j],0)!=0:
s_map[t[j]]-=1
else:
return False
return True
def isAnagram2(self,s,t):
s_len=len(s)
t_len=len(t)
if s_len!=t_len:
return False
s_map={}
for i in range(0,s_len):
s_map[s[i]]=s_map.get(s[i],0)+1
s_map[t[i]]=s_map.get(t[i],0)-1
for counter in s_map.values():
if counter<0:
return False
return True
if __name__ == '__main__':
s = "anagram"
t = "nagaram"
# s = "rat"
# t = "car"
# s = "abbac"
# t = "cbaba"
# s = "abbac"
# t = "cbaac"
solution = Solution()
result=solution.isAnagram2(s,t)
print(result)
|
'''
求2个数组的公共元素,以数组形式返回(不去重)
eg:
[1,2,2,1], [2,2] => [2,2]
[4,9,5], [9,4,9,8,4] => [4,9]
Given two arrays, write a function to compute their intersection.
Example 1:
```
Input: nums1 = [1,2,2,1], nums2 = [2,2]
Output: [2,2]
```
Example 2:
```
Input: nums1 = [4,9,5], nums2 = [9,4,9,8,4]
Output: [4,9]
```
Note:
Each element in the result should appear as many times as it shows in both arrays.
The result can be in any order.
Follow up:
What if the given array is already sorted? How would you optimize your algorithm?
What if nums1's size is small compared to nums2's size? Which algorithm is better?
What if elements of nums2 are stored on disk, and the memory is limited such that you cannot load all elements into the memory at once?
'''
class Solution(object):
def intersect(self, nums1, nums2):
"""
:type nums1: List[int]
:type nums2: List[int]
:rtype: List[int]
"""
n=len(nums1)
m=len(nums2)
if n==0 or m==0:
return []
if n>m:
nums1,nums2=nums2,nums1
nums_map={}
for i in range(len(nums1)):
nums_map[nums1[i]]=nums_map.get(nums1[i],0)+1
ret=[]
for i in range(0,len(nums2)):
if nums_map.get(nums2[i],0)>0:
ret.append(nums2[i])
nums_map[nums2[i]]-=1
return ret
if __name__=='__main__':
# nums1=[1,2,2,1]
# nums2=[2,2]
nums1 = [4,9,5]
nums2 = [9,4,9,8,4]
solution=Solution()
result=solution.intersect(nums1,nums2)
print(result)
|
def _shiftRightByOne(C, a, b):
"""Shifts all elements in the range [a, b) to the right by one.
Causes out-of-bounds error if range is nonempty (a < b) and b >= len(C)."""
i = b-1
while i >= a:
x = C[i]
C[i+1] = x
i -= 1
def insertion_sort(A):
"""Sorts the list A in place"""
i = 1
n = len(A)
while i < n:
x = A[i]
j = i-1
# This is a half-open bound, [lowerBound, upperBound)
lowerBound = i
upperBound = i
while j >= 0:
if A[j] > x:
lowerBound -= 1
else:
# We don't have to break here, but doing so skips
# a bunch of unnecessary comparisons
break
j -= 1
_shiftRightByOne(A, lowerBound, upperBound)
A[lowerBound] = x
i += 1
return A
|
import math
# ---- Problem 1 ----
class Line():
def __init__(self,coor1,coor2):
self.coor1 = coor1
self.coor2 = coor2
self.x = coor2[0] - coor1[0]
self.y = coor2[1] - coor1[1]
def distance(self):
return math.sqrt((self.x ** 2) + (self.y ** 2))
def slope(self):
return (self.y / self.x)
li = Line([3,2],[8,10])
print(li.distance())
print(li.slope())
# ---- Problem 2 ----
class Cylinder():
# Class Object Attribute
pi = 3.14
def __init__(self,height=1,radius=1):
self.height = height
self.radius = radius
def volume(self):
return self.pi * (self.radius ** 2) * self.height
def surface_area(self):
return ((2 * self.pi * self.radius * self.height) + (2 * self.pi * (self.pi ** 2)))
c = Cylinder(2,3)
print(c.volume())
print(c.surface_area())
|
from turtle import Turtle
import random
class Food(Turtle):
def __init__(self):
super().__init__()
self.shape("circle")
self.penup()
self.shapesize(stretch_len=0.5, stretch_wid=0.5)
self.color("blue")
self.speed("fastest")
self.refresh_food_position()
def refresh_food_position(self):
random_position_x = random.randint(-280, 280)
random_position_y = random.randint(-280, 280)
self.goto(random_position_x, random_position_y)
|
import turtle
from turtle import Turtle
import random
turtle.colormode(255)
turtle.speed("fastest")
tortu = Turtle()
def generate_random_color():
r = random.randint(0, 255)
g = random.randint(0, 255)
b = random.randint(0, 255)
return (r, g, b)
for degree in range(0,360, 2):
tortu.color(generate_random_color())
turtle.pencolor(generate_random_color())
turtle.right(degree)
turtle.circle(100)
|
import turtle
from turtle import Turtle
import pandas
# Variables
total_adivinadas = 0
# Logica de la pantalla
screen = turtle.Screen()
screen.title("Juego de Povincias del Ecuador")
image = "Ecuador_mapa.gif"
screen.addshape(image)
turtle.shape(image)
# Logica de los datos
row_data = pandas.read_csv("provincias.csv")
list_of_provincias = row_data["provincia"].to_list()
total_provincias = len(row_data)
# Logica del juego
is_the_game_on = True
def verify_if_imput_is_correct(user_input):
#print(row_data["provincia"])
print(user_input)
if user_input in list_of_provincias:
return True
def create_turtle_with_name_and_position(name, x, y):
provincia_name = Turtle()
provincia_name.hideturtle()
provincia_name.penup()
provincia_name.goto(x, y)
provincia_name.write(name)
while is_the_game_on:
answer_provincia = screen.textinput(title=f"Adivina la provincia {total_adivinadas}/{total_provincias}",
prompt="¿Dime qué provincia falta?")
if verify_if_imput_is_correct(answer_provincia):
provincia_adivinada = row_data[row_data["provincia"] == answer_provincia]
print("Nombre" + provincia_adivinada["provincia"])
print(f"x: {int(provincia_adivinada.x)}")
print(f"y: {int(provincia_adivinada.y)}")
create_turtle_with_name_and_position(name=provincia_adivinada.provincia.item(), x=int(provincia_adivinada["x"]),
y=int(provincia_adivinada["y"]))
total_adivinadas +=1
if total_adivinadas >23:
is_the_game_on = False
print("GAME OVER")
turtle.mainloop()
|
#Abigail Lowe
#Decimal-binary, Binary-Decimal, Decimal-Hexadecimal conversion program
#COSC 101
ans=True
while ans:
print("""
1.Decimal to Binary Conversion
2.Binary to Decimal Conversion
3.Decimal to Hexadecimal Conversion
4.Exit/Quit [ends program]
""")
ans=input("Select desired conversion: ")
if ans=="1": #converts decimal to binary
print("\n Decimal to Binary Conversion selected.")
n=int(input('Enter decimal value to be converted: '))
x=n
k=[]
while (n>0):
a=int(float(n%2))
k.append(a)
n=(n-a)/2
k.append(0)
string=""
for j in k[::-1]:
string=string+str(j)
print('%d in binary is %s'%(x, string))
elif ans=="2": #converts binary to decimal
print("\n Binary to Decimal Conversion selected.")
binary = input('Enter binary value to be converted: ')
decimal = 0
for digit in binary:
decimal = decimal*2 + int(digit)
print (binary, "in decimal is", decimal)
elif ans=="3": #converting decimal to hexadecimal
print("Decimal to Hexadecimal conversion was selected.")
n=int(input("Enter decimal to be converted: "))
def DectoHex(n):
if n <= 16:
return n
elif n>16:
if n%16 == 10:
x = 'A'
elif n%16 == 11:
x = 'B'
elif n%16 == 12:
x = 'C'
elif n%16 == 13:
x = 'D'
elif n%16 == 14:
x ='E'
elif n%16 == 15:
x = 'F'
else:
x = n%16
print ('%n in binary is %x')
n = n/16
print (n)
elif ans=="4": #exit/quit
print("\n Goodbye")
ans = None
elif ans !="": #not a valid choice on menu
print("\n Not Valid Choice, Try again")
|
from tkinter import *
def btnclick(nums):
global operator
operator = operator + str(nums)
text_input.set(operator)
# This function will allow users to click on a button and it will display that on screen of calculator.
# text_input is a variable being used to print values on calculator screen(see line 29).
# Operator is an empty variable being used to assign new values(see line 27).
def btncleardis():
global operator
operator = ""
text_input.set("")
# This function clears the display(see line 57).
def btnEqualsInput():
global operator
try:
sumup = str(eval(operator))
text_input.set(sumup)
except Exception:
text_input.set("Input Error!!!")
operator = ""
# Equal to operator is being assingned(see line 58).
# Try..Except prevents calculation error in strings and division by zero
cal = Tk()
cal.title("Calculator")
# Tiltle is being given
operator = ""
# Empty operator
text_input = StringVar()
# It will hold the display value.
txtDisplay=Entry(cal,font=('aerial',20,'bold'),textvariable=text_input,bd=30,fg="red",insertwidth=4,bg="Light green",justify='right').grid(columnspan=4)
# This will be used to show display.
# fg=textcolour of output
# Font`ll show font size, style etc.
# textvariable is the input command where text_input is assigned.
# bd=display box size
# insert width determines the width of the outer box(excluding display)
# bg=Background colour
# justify is set as right
# columnspan=width of display box
btn1=Button(cal,padx=16,pady=16,bd=8,fg='blue',font=('aerial',20,'bold'),text="0",bg='Yellow',command=lambda:btnclick(0)).grid(row=1,column=0)
btn2=Button(cal,padx=16,pady=16,bd=8,fg='blue',font=('aerial',20,'bold'),text="1",bg='Yellow',command=lambda:btnclick(1)).grid(row=1,column=1)
btn3=Button(cal,padx=16,pady=16,bd=8,fg='blue',font=('aerial',20,'bold'),text="2",bg='Yellow',command=lambda:btnclick(2)).grid(row=1,column=2)
btn4=Button(cal,padx=16,pady=16,bd=8,fg='blue',font=('aerial',20,'bold'),text="+",bg='Yellow',command=lambda:btnclick("+")).grid(row=1,column=3)
#============================================
btn5=Button(cal,padx=16,pady=16,bd=8,fg='blue',font=('aerial',20,'bold'),text="3",bg='Yellow',command=lambda:btnclick(3)).grid(row=2,column=0)
btn6=Button(cal,padx=16,pady=16,bd=8,fg='blue',font=('aerial',20,'bold'),text="4",bg='Yellow',command=lambda:btnclick(4)).grid(row=2,column=1)
btn7=Button(cal,padx=16,pady=16,bd=8,fg='blue',font=('aerial',20,'bold'),text="5",bg='Yellow',command=lambda:btnclick(5)).grid(row=2,column=2)
btn8=Button(cal,padx=16,pady=16,bd=8,fg='blue',font=('aerial',20,'bold'),text="-",bg='Yellow',command=lambda:btnclick("-")).grid(row=2,column=3)
#============================================
btn9=Button(cal,padx=16,pady=16,bd=8,fg='blue',font=('aerial',20,'bold'),text="6",bg='Yellow',command=lambda:btnclick(6)).grid(row=3,column=0)
btn10=Button(cal,padx=16,pady=16,bd=8,fg='blue',font=('aerial',20,'bold'),text="7",bg='Yellow',command=lambda:btnclick(7)).grid(row=3,column=1)
btn11=Button(cal,padx=16,pady=16,bd=8,fg='blue',font=('aerial',20,'bold'),text="8",bg='Yellow',command=lambda:btnclick(8)).grid(row=3,column=2)
btn12=Button(cal,padx=16,pady=16,bd=8,fg='blue',font=('aerial',20,'bold'),text="*",bg='Yellow',command=lambda:btnclick("*")).grid(row=3,column=3)
#============================================
btn13=Button(cal,padx=16,pady=16,bd=8,fg='blue',font=('aerial',20,'bold'),text="9",bg='Yellow',command=lambda:btnclick(9)).grid(row=4,column=0)
btn14=Button(cal,padx=16,pady=16,bd=8,fg='blue',font=('aerial',20,'bold'),text="C",bg='Yellow',command=lambda:btncleardis()).grid(row=4,column=1)
btn15=Button(cal,padx=16,pady=16,bd=8,fg='blue',font=('aerial',20,'bold'),text="=",bg='Yellow',command=btnEqualsInput).grid(row=4,column=2)
btn16=Button(cal,padx=16,pady=16,bd=8,fg='blue',font=('aerial',20,'bold'),text="/",bg='Yellow',command=lambda:btnclick("/")).grid(row=4,column=3)
#============================================
# "#==========================================" represents the new row.
# padx=length of button in its x axis and pady=length of button in its y axis
# text shows the value in its corresponding button
# command gives a command to the calculator when that button is pressed
# grid is used to make buttons of the desired size
cal.mainloop()
# mainloop is made to run and calculator does its work.
|
import random
def display_board(board):
print(' | |')
print(' ' + board[1] + ' | ' + board[2] + ' | ' + board[3])
print(' | |')
print('-----------')
print(' | |')
print(' ' + board[4] + ' | ' + board[5] + ' | ' + board[6])
print(' | |')
print('-----------')
print(' | |')
print(' ' + board[7] + ' | ' + board[8] + ' | ' + board[9])
print(' | |')
def player_input():
# Takes Player input and assigns X or O Marker, returns tuple (player1choice, player2choice)
marker = ''
while not (marker == 'X' or marker == 'O'):
marker = random.randint(0,1)
if marker == 0:
return ('X', 'O')
else:
return ('O','X')
def place_marker(board, marker, position):
board[position] = marker
def win_check(board, mark):
return ((board[1] == mark and board[2] == mark and board[3] == mark) or # Hori
(board[4] == mark and board[5] == mark and board[6] == mark) or # zon
(board[7] == mark and board[8] == mark and board[9] == mark) or # tal
(board[1] == mark and board[4] == mark and board[7] == mark) or # Ver
(board[2] == mark and board[5] == mark and board[8] == mark) or # ti
(board[3] == mark and board[6] == mark and board[9] == mark) or # tal
(board[1] == mark and board[5] == mark and board[9] == mark) or # Dia
(board[3] == mark and board[5] == mark and board[7] == mark)) # gonal
def choose_first():
firstplayer = random.randint(1, 2)
if firstplayer == 1:
return 'Player 1'
else:
return 'Player 2'
def space_check(board, position):
return board[position] == ' '
def full_board_check(board):
for i in range(1,10):
if space_check(board, i):
return False
return True
def player_choice(board):
position = 0
while position not in [1,2,3,4,5,6,7,8,9] or not space_check(board, position):
position = int(input('Choose your next position: (1-9) '))
return position
def random_choice(board):
position = 0
while position not in [1,2,3,4,5,6,7,8,9] or not space_check(board, position):
position = random.randint(1,9)
return position
def replay():
return input('Play again? Enter Yes or No: ').lower().startswith('y')
def getduplicateboard(board):
# creates a duplicate board for AI to check win conditions
duplicate_board = []
for i in board:
duplicate_board.append(i)
return duplicate_board
def choose_random_move_from_list(board, moveslist):
# returns valid move from passed list on passed board
# returns None if no valid move
possible_moves = []
for i in moveslist:
if space_check(board, i):
possible_moves.append(i)
if len(possible_moves) != 0:
return random.choice(possible_moves)
else:
return None
def cpu_get_move(board, marker):
if marker == 'X':
playermarker = 'O'
else:
playermarker = 'X'
# check if CPU has a winning move
for i in range(1, 10):
copy = getduplicateboard(board)
if space_check(copy, i):
place_marker(copy, marker, i)
if win_check(copy, marker):
return i
# check if next move of player could be winning move, block
for i in range(1, 10):
copy = getduplicateboard(board)
if space_check(copy,i):
place_marker(copy,playermarker, i)
if win_check(copy,playermarker):
return i
# Try to take corners
move = choose_random_move_from_list(board, [1, 3, 7, 9])
if move != None:
return move
# Try to take center
if space_check(board,5):
return 5
# take a side
return choose_random_move_from_list(board,[2, 4, 6, 8])
|
import heapq
class PriorityQueue(object):
def __init__(self, content=None):
if content is None:
content = []
self.heap = content
if self.heap:
self.update()
def __iter__(self):
return self
def __next__(self):
return self.next()
def next(self):
if not self.heap:
raise StopIteration
if len(self.heap) == 1:
return self.heap.pop()
last_item = self.heap.pop()
result = self.heap[0]
self.heap[0] = last_item
heapq._siftup_max(self.heap, 0)
return result
def add(self, element):
self.heap.append(element)
heapq._siftdown_max(self.heap, 0, len(self.heap)-1)
def update(self):
heapq._heapify_max(self.heap)
def __str__(self):
return str(self.heap)
|
# Creating and accessing tuples.
# retrieve hour, minute and second from user
hour = int( input( "Enter hour " ) )
minute = int( input( "Enter minute " ) )
second = int( input( "Enter second " ) )
currentTime = hour, minute, second # create tuple
print ("The value of currentTime is:", currentTime)
# access tuple
print ("The number of seconds since midnight is", \
( currentTime[ 0 ] * 3600 + currentTime[ 1 ] * 60 +\
currentTime[ 2 ] ))
|
values=[]
print("Enter 10 integers")
for i in range(10):
newValue = int(input("Enter integer %d : " % (i + 1)))
values += [newValue]
print(values)
print ("\nCreating a histogram from values:" )
print ("%s %10s %10s" % ( "Element", "Value", "Histogram" ) )
for i in range( len( values ) ):
print ("%7d %10d %s" % ( i, values[ i ], "*" * values[ i ] ))
|
import re
txt = "pavithra ramamoorthy 1997"
x = re.search("^pavi.*thy$", txt)
if (x):
print("YES! We have a match!")
else:
print("No match")
#findall
#set of characters
x=re.findall("[a-m]",txt)
print(x)
#any character
x=re.findall("pa.....a",txt)
print(x)
#does not contain digits
x=re.findall("\D",txt)
print(x)
#contain digits
x = re.findall("\d", txt)
print(x)
#0 or more accrances
x = re.findall("ram*", txt)
print(x)
#one or more
x = re.findall("ram+", txt)
print(x)
#exactly
x = re.findall("mo{2}", txt)
print(x)
#either or
x = re.findall("pavithra|pavi", txt)
print(x)
#biginnng of the string
x = re.findall("\Apavi", txt)
print(x)
#boundry
x = re.findall(r"\bra", txt)
print(x)
x = re.findall(r"\Bra", txt)
print(x)
x = re.findall(r"ra\b", txt)
print(x)
x = re.findall(r"ra\B", txt)
print(x)
#contain space
x=re.findall("\s",txt)
print(x)
#does not contain space
x=re.findall("\S",txt)
print(x)
#contain word
x=re.findall("\w",txt)
print(x)
#does not contain word
x=re.findall("\W",txt)
print(x)
#end of the string
x=re.findall("1997\Z",txt)
print(x)
if(x):
print("it is match")
else:
print("it is not match")
#one of the specified character
x = re.findall("[amo]", txt)
print(x)
#lowercase letters
x = re.findall("[a-m]", txt)
print(x)
#[^]
x = re.findall("[^arn]", txt)
print(x)
x = re.findall("[^a-z]", txt)
print(x)
x = re.findall("[0123]", txt)
print(x)
x = re.findall("[0-9]", txt)
print(x)
x = re.findall("[^a-z0-9]", txt)
print(x)
x = re.findall("[0-5][0-9]", txt)
print(x)
x = re.findall("[+]", txt)
print(x)
x = re.findall("[aeiou]", txt)
print(x)
|
def append_middle(s1, s2):
middle_index = int(len(s1) /2)
print("Original Strings are", s1, s2)
middle_three = s1[:middle_index-1:]+ s2 +s1[middle_index-1:]
print("After appending new string in middle", middle_three)
append_middle("pavithra", "pavithraramamoorthy")
|
# import modules
FILE_NAME = 'fdic_failed_bank_list.csv'
# write a function to output the first row of a csv file
# and get the column names
# open the csv
# create the object that represents the data in the csv file
# create a variable to represent the header row
# output the value
# output the length of the header row
# output the type of the header row
# loop through each item in the header_row
# output its contents
# output its length
# output its type
# close the csv file when we're done
|
# import modules
import csv
FILE_NAME = 'fdic_failed_bank_list.csv'
# write a function to open a csv file
def open_csv_file(file_name):
# open the csv
csv_file = open(file_name, 'rb')
# create the object that represents the data in the csv file
csv_data = csv.reader(csv_file)
# output that object to the terminal
print csv_data
# close the csv file when we're done
csv_file.close()
### ###
# write a function to count the number of rows in a csv file
def count_csv_rows(file_name):
# create a variable to iterate each row and count the number of lines
number_of_rows = sum(1 for line in open(file_name))
# output the number of lines
print number_of_rows
### ###
# write a function to print each row from a csv file
# and get its length and if it's a string or an integer
def output_rows_from(file_name):
# open the csv
csv_file = open(file_name, 'rb')
# create the object that represents the data in the csv file
csv_data = csv.reader(csv_file)
# loop through each row in the object
for row in csv_data:
# output the type
print type(row)
# output the length of the row
print len(row)
# output the contents
print row
# close the csv file when we're done
csv_file.close()
### ###
# write a function to output the first row of a csv file
# and get the column names
def output_first_csv_row(file_name):
# open the csv
csv_file = open(file_name, 'rb')
# create the object that represents the data in the csv file
csv_data = csv.reader(csv_file)
# create a variable to represent the header row
header_row = csv_data.next()
print header_row
# create a variable to represent the length of the header row
header_length = len(header_row)
print header_length
# create a variable to represent the datatype for the header row
header_type = type(header_row)
print header_type
# loop through each item in the header_row
for column_name in header_row:
# log its contents
print column_name
# log its length
column_name_length = len(column_name)
print column_name_length
# log its type
column_name_type = type(column_name)
print column_name_type
# close the csv file when we're done
csv_file.close()
### ###
# write a function to do some exploring with strings
def working_with_strings(file_name):
# open the csv
csv_file = open(file_name, 'rb')
# create the object that represents the data in the csv file
csv_data = csv.reader(csv_file)
# create a variable to represent the header row
header_row = csv_data.next()
# from the last lesson we know the variable header_row refers to a list
# let's isolate the string that is 'Acquiring Institution'
print header_row
# we'll do this by isolating in the list what is know as the index of the string
print header_row[4]
# let's make sure this is a string
print type(header_row[4])
# let's get the length of the string
print len(header_row[4])
# create a variable to hold our string
my_string = header_row[4]
# let's see how string subscripting works
# let's print the third characters
print my_string[2]
# let's print the first five characters
print my_string[:5]
# let's print everything after the first five characters
print my_string[5:]
# let's capitalize the first letter in the string
print my_string.capitalize()
# let's lowercase the string
print my_string.lower()
# let's uppercase the string
print my_string.upper()
# close the csv file when we're done
csv_file.close()
### ###
# write a function to do some more exploring with strings
def doing_more_with_strings(file_name):
# open the csv
csv_file = open(file_name, 'rb')
# create the object that represents the data in the csv file
csv_data = csv.reader(csv_file)
# create a variable to represent the header row
header_row = csv_data.next()
# from the last lesson we know the variable header_row refers to a list
# let's isolate the string that is 'Acquiring Institution'
print header_row
# create a variable to hold our string
my_string = header_row[4]
# let's evaluate the uppercase version is equal to the lowercase version
print my_string.upper() == my_string.lower()
# let's remove the space that is present in the string
print my_string.replace(' ', '')
# let's change the space to an underscore
print my_string.replace(' ', '_')
# let's look at the strip method by giving it a value
print my_string.strip('Acquiring')
# let's look at what the strip method does to the ouput of above
print my_string.strip('Acquiring').strip()
# let's try to split the string on the space
print my_string.split(' ')
# let's get the datatype for the thing we just created
# first lets create a variable to hold this string
my_split_string = my_string.split(' ')
# then let's get the type
print type(my_split_string)
# because it's a list, we can again get a specfic item by it's index
# and we're back to where we started
print my_split_string[0]
# for the final item let's use the length of the list and lowercase the two strings we created to create a sentence
print 'I made %d strings from a list I created. They are: %s & %s' % (len(my_split_string), my_split_string[0].lower(), my_split_string[1].lower())
# close the csv file when we're done
csv_file.close()
### ###
# write a function to do some exploring with integers
def working_with_integers(file_name):
# open the csv
csv_file = open(file_name, 'rb')
# create the object that represents the data in the csv file
csv_data = csv.reader(csv_file)
# create a variable to represent the header row
header_row = csv_data.next()
# let's get the first row of data
data_row = csv_data.next()
# let's create a varaible off the bat to isolate
# the integer that is the zip code
my_integer = data_row[3]
# let's output the value
print my_integer
# let's get the length of the integer
print len(my_integer)
# for kicks let's multiply zipcode by 2. we should get 68592
print my_integer * 2
# let's make sure this is an integer
# because its not an integer, when we tried to double it, python simply repeated the string
print type(my_integer)
# let's convert the string to an integer
my_integer = int(my_integer)
print type(my_integer)
# now let's try some math
# multiplication
print my_integer * 2
# division
print my_integer / 2
# addition
print my_integer + 1000
# subtraction
print my_integer - 1000
# order of operations
print (my_integer*2+56)/100
# close the csv file when we're done
csv_file.close()
# run the function when you run the script in the terminal
open_csv_file(FILE_NAME)
#count_csv_rows(FILE_NAME)
#output_rows_from(FILE_NAME)
#output_first_csv_row(FILE_NAME)
#basic_string_methods(FILE_NAME)
#more_string_methods(FILE_NAME)
#working_with_integers(FILE_NAME)
|
# import modules
FILE_NAME = 'fdic_failed_bank_list.csv'
# write a function to do some exploring with integers
# open the csv
# create the object that represents the data in the csv file
# create a variable to represent the header row
# let's get the first row of data
# let's create a varaible off the bat to isolate
# the integer that is the zip code
# let's output the value
# let's get the length of the integer
# for kicks let's multiply zipcode by 2. we should get 68592
# let's make sure this is an integer
# because its not an integer, when we tried to double it, python simply repeated the string
# let's convert the string to an integer
# now let's try some math
# multiplication
# division
# addition
# subtraction
# order of operations
# close the csv file when we're done
working_with_integers('fdic_failed_bank_list.csv')
|
# import modules
import csv
# write a function to open a csv file
def open_csv_file(file_name):
# open the csv
csv_file = open(file_name, 'rb')
# create the object that represents the data in the csv file
csv_data = csv.reader(csv_file)
# output that object to the terminal
print csv_data
# close the csv file when we're done
csv_file.close()
# run the function when you run the script in the terminal
open_csv_file('fdic_failed_bank_list.csv')
|
#1/usr/bin/pyton
#-*- coding: utf-8 -*-
a = input("Cien, liet.,lūdzu, ievadi skaitli")
#3. python'ā visi input rezultāti ir ar str datu tipu
# tāpēc ievadītā lieluma datu tips vēlāk ir jāpārveido
a = int(a)
# python valoda balstās uz C valodas -> print strādā līdzōgi printf
# https://www.cplusplus.com/referemce/cstdio/printf/
print("Liet.,Tu esi ievadījis skaitli: %d"%(a))
aa = a*a
print("Tavs skaitlis kvadrātā ir: %d"%(aa))
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
from chess_configurations.solver import backtracking
from chess_configurations.models import Board, King, Rook, Knight
def test_very_simple():
"""
A board with one position available.
test_very_simple_1x1_board_with_one_piece
"""
expected = [{'pieces': {'(0, 0)': 'K'}, 'n': 1, 'm': 1}]
board = Board(1, 1)
pieces = [King()]
board.put(pieces[0], 0, 0)
res = []
for board in backtracking(board, pieces, pieces, set()):
res.append(json.loads(board.to_json()))
assert res == expected
def test_example_test_case_given():
"""
This test case was given as an example.
The assert were done manually before the to_json method was done.
To make checks easily see: test_with_data which uses a "fuzzer"
case generator to verify results.
"""
expected = [
{'pieces': {'(2, 0)': 'K', '(1, 2)': 'R', '(0, 0)': 'K'},
'm': 3,
'n': 3},
{'pieces': {'(0, 2)': 'K', '(2, 1)': 'R', '(0, 0)': 'K'},
'm': 3,
'n': 3},
{'pieces': {'(0, 1)': 'R', '(2, 0)': 'K', '(2, 2)': 'K'},
'm': 3,
'n': 3},
{'pieces': {'(0, 2)': 'K', '(1, 0)': 'R', '(2, 2)': 'K'},
'm': 3,
'n': 3}]
pieces = [King(), King(), Rook()]
board = Board(3, 3)
res = []
for board in backtracking(board, pieces.copy(), pieces, set()):
res.append(json.loads(board.to_json()))
assert len(expected) == len(res)
for expected_res in expected:
assert expected_res in res
def test_example_2_test_case_given():
""" This case was given as an example in the problem """
expected = [
{'pieces':
{'(3, 3)': 'N',
'(1, 1)': 'N',
'(2, 2)': 'R',
'(3, 1)': 'N',
'(1, 3)': 'N',
'(0, 0)': 'R'},
'm': 4,
'n': 4},
{'pieces':
{'(2, 0)': 'N',
'(0, 2)': 'N',
'(3, 1)': 'R',
'(1, 3)': 'R',
'(0, 0)': 'N',
'(2, 2)': 'N'},
'm': 4,
'n': 4},
{'pieces':
{'(3, 3)': 'R',
'(1, 1)': 'R',
'(2, 0)': 'N',
'(2, 2)': 'N',
'(0, 0)': 'N',
'(0, 2)': 'N'},
'm': 4,
'n': 4},
{'pieces':
{'(0, 1)': 'R',
'(2, 3)': 'R',
'(1, 2)': 'N',
'(1, 0)': 'N',
'(3, 2)': 'N',
'(3, 0)': 'N'},
'm': 4,
'n': 4},
{'pieces':
{'(0, 1)': 'N',
'(2, 1)': 'N',
'(1, 2)': 'R',
'(2, 3)': 'N',
'(0, 3)': 'N',
'(3, 0)': 'R'},
'm': 4,
'n': 4},
{'pieces':
{'(0, 1)': 'N',
'(2, 3)': 'N',
'(2, 1)': 'N',
'(1, 0)': 'R',
'(3, 2)': 'R',
'(0, 3)': 'N'},
'm': 4,
'n': 4},
{'pieces':
{'(3, 3)': 'N',
'(1, 1)': 'N',
'(2, 0)': 'R',
'(0, 2)': 'R',
'(3, 1)': 'N',
'(1, 3)': 'N'},
'm': 4,
'n': 4},
{'pieces':
{'(2, 1)': 'R',
'(1, 2)': 'N',
'(1, 0)': 'N',
'(3, 2)': 'N',
'(0, 3)': 'R',
'(3, 0)': 'N'},
'm': 4,
'n': 4}]
pieces = [Rook(), Rook(), Knight(), Knight(), Knight(), Knight()]
board = Board(4, 4)
res = []
for board in backtracking(board, pieces.copy(), pieces, set()):
res.append(json.loads(board.to_json()))
assert len(expected) == len(res)
for expected_res in expected:
assert expected_res in res
|
# Given the root to a binary tree, implement serialize(root), which serializes the tree into a string,
# and deserialize(s), which deserializes the string back into the tree.
#
# For example, given the following Node class
class Node:
def __init__(self, val, left=None, right=None):
self.val = val
self.left = left
self.right = right
def PrintTree(self):
if self.left:
self.left.PrintTree()
print( self.data),
if self.right:
self.right.PrintTree()
# The following test should pass:
#
# node = Node('root', Node('left', Node('left.left')), Node('right'))
# assert deserialize(serialize(node)).left.left.val == 'left.left'
def serialize(node):
serializedData = []
if node:
serializedData.append(node.val)
serializedData.append(serialize(node.left))
serializedData.append(serialize(node.right))
return serializedData
def deserialize(stringdata):
numElements = len(stringdata)
if numElements == 0:
return None
elif numElements == 1:
return Node(stringdata[0])
else:
return Node(stringdata[0], deserialize(stringdata[1]), deserialize(stringdata[2]))
def main():
node = Node('root', Node('left', Node('left.left')), Node('right'))
res = deserialize(serialize(node)).left.left.val
assert res == 'left.left', "Incorrect"
print(res)
main()
|
# Problem Description:
#
# A unival tree (which stands for "universal value") is a tree where all
# nodes under it have the same value.
#
# Given the root to a binary tree, count the number of unival subtrees.
# For example, the following tree has 5 unival subtrees:
# 0
# / \
# 1 0
# / \
# 1 0
# / \
# 1 1
class Node:
def __init__(self, val, left=None, right=None):
self.val = val
self.left = left
self.right = right
def buildTestTree1():
left1Leaf1 = Node(1)
left1Leaf2 = Node(1)
right1Leaf = Node(1)
right0Leaf = Node(0)
lowestSubTree = Node(1, left1Leaf2, right1Leaf)
middleSubTree = Node(0, lowestSubTree, right0Leaf)
root = Node(0, left1Leaf1, middleSubTree)
return root
def getNumUniValSubTrees(binaryTree):
if binaryTree.left == None and binaryTree.right == None:
return 1
elif not binaryTree.left == None and binaryTree.right == None:
leftSubTreeNumUniVal = getNumUniValSubTrees(binaryTree.left)
if binaryTree.left.val == binaryTree.val:
leftSubTreeNumUniVal += 1
return leftSubTreeNumUniVal
elif binaryTree.left == None and not binaryTree.right == None:
rightSubTreeNumUniVal = getNumUniValSubTrees(binaryTree.right)
if binaryTree.right.val == binaryTree.val:
rightSubTreeNumUniVal += 1
return rightSubTreeNumUniVal
else:
total = getNumUniValSubTrees(binaryTree.right)
total += getNumUniValSubTrees(binaryTree.left)
if binaryTree.right.val == binaryTree.val and binaryTree.left.val == binaryTree.val:
total += 1
return total
def main():
testTree = buildTestTree1()
print("Testing tree with following structure:")
print(" 0")
print(" / \\")
print(" 1 0")
print(" / \\")
print(" 1 0")
print(" / \\")
print(" 1 1")
print("Expected Result - 5")
print(getNumUniValSubTrees(testTree))
main()
|
class ShoppingCart:
def __init__(self):
self.__total = 0
self.items = {}
def add_item(self, item_name, quantity, price):
self.__total += quantity * price
self.items[item_name] = quantity
def remove_item(self, item_name, quantity, price):
if item_name not in self.items:
return
if quantity >= self.items[item_name]:
self.__total -= self.items[item_name] * price
del self.items[item_name]
else:
self.__total -= quantity * price
self.items[item_name] = self.items[item_name] - quantity
def checkout(self, cash_paid):
if cash_paid < self.total:
return "Cash paid not enough"
else:
return cash_paid - self.total
class Shop(ShoppingCart):
def __init__(self):
pass
def sale(self, item_name, qty, price):
ShoppingCart.add_item(item_name, qty, price)
|
# The program is to ask the user to enter his name and say hello.
name = input("Please Enter Your Name >> ")
print("Hello %s !! We Are Happy To Welcome You. " %name)
|
# Programación Orientada a Objetos con Python3
import datetime
class Employee:
nums_of_emps = 0
raise_amount = 1.04
def __init__(self, first, last, pay):
''' Employee constructor '''
self.first = first
self.last = last
self.pay = pay
self.email = first + '.' + last + '@company.com'
Employee.nums_of_emps += 1
def fullname(self):
return '{} {}'.format(self.first, self.last)
def apply_raise(self):
self.pay = int(self.pay * self.raise_amount)
@classmethod
def set_raise_amt(cls, amount):
cls.raise_amount = amount
@classmethod
def from_string(cls, emp_str):
first, last, pay = emp_str.split('-')
return cls(first, last, pay)
@staticmethod
def is_workday(day):
if day.weekday() == 5 or day.weekday() == 6:
return False
else:
return True
def __repr__(self): # for debug and devleopment
return (f"Employee('{self.first}', '{self.last}', '{self.pay})'")
def __str__(self): # for the end-user
return f"{self.fullname()} - {self.email}"
def __add__(self, other):
return self.pay + other.pay
def __len__(self):
return len(self.fullname())
def intro():
emp_1 = Employee('John', 'Doe', 500)
emp_2 = Employee('Karl', 'Foo', 100)
print(emp_2.fullname())
print(Employee.fullname(emp_1))
print(emp_1.pay)
Employee.set_raise_amt(1.05)
emp_1.apply_raise()
print(emp_1.pay)
# print(Employee.__dict__)
print(Employee.nums_of_emps)
emp_3_str = "Rod-Av-200"
emp_3 = Employee.from_string(emp_3_str)
print(emp_3.__dict__)
print(Employee.nums_of_emps)
my_date = datetime.date(2019, 6, 1)
print(Employee.is_workday(my_date))
print(emp_3)
print(repr(emp_3))
print(str(emp_3))
print(emp_3.__repr__())
print(emp_3.__str__())
# magic/dunder
print(1 + 2)
print('a' + 'b')
print(int.__add__(1, 2))
print(str.__add__('a', 'b'))
print(len('Rodrigo'))
print('Rodrigo'.__len__())
print(emp_1 + emp_2)
print(emp_3.fullname())
print(len(emp_3))
if __name__ == '__main__':
intro()
|
# Dictionary
""""
1.A dictionary is a collection which is unordered, changeable and indexed.
2.In Python dictionaries are written with curly {} brackets, and they have keys and values.
3.Accessing Items: You can access the items of a dictionary by referring to its key name, inside square [] brackets.
4.Accessing Items:There is also a method called get() that will give you the same result
5.Change Values: You can change the value of a specific item by referring to its key name
6.Duplicate keys were NOT allowed.
Syntax:
varName = {"key_01":value_01, "key_02":value_02, "key_03":value_03, ... "key_n":value_n}
"""
# Create a Dictionary
print("##############################")
studentMarkInfo = \
{
"Id": 1,
"Name": "Vijay",
"Tamil": 97,
"English": 91,
"Maths": 100,
"Science": 98,
"Social": 99
}
print(studentMarkInfo)
#Accessing Items: You can access the items of a dictionary by referring to its key name, inside square brackets.
#Regular Way:
#Syntax:
#nameOfDictionary["Key"]
print("##############################")
print(studentMarkInfo["Name"])
#Using Method
#Syntax:
#nameOfDictionary.get("Key")
print(studentMarkInfo.get("Science"))
#Change Values: You can change the value of a specific item by referring to its key name:
print("##############################")
#Syntax:
#nameOfDictionary["Key"] = "Value"
studentMarkInfo["Science"] = 100
print(studentMarkInfo)
#Loop Through a Dictionary - Values
print("##############################")
for data in studentMarkInfo:
print(data)
#You can also use the values() function to return values of a dictionary:
print("++++++++++++++++++++++++++++++")
for value in studentMarkInfo.values():
print(value)
#Loop Through a Dictionary - Keys,Values
print("++++++++++++++++++++++++++++++")
for key_Values in studentMarkInfo:
print(studentMarkInfo[key_Values])
#Loop through both keys and values, by using the items() function:
print("++++++++++++++++++++++++++++++")
for key, val in studentMarkInfo.items():
print(key, val)
#Adding Items: Adding an item to the dictionary is done by using a new index key and assigning a value to it.
print("##############################")
#Syntax:
#nameOfDictionary["Key"] = "Value"
studentMarkInfo["Computer"] = 100
print(studentMarkInfo)
print("##############################")
#Removing Items: There are several methods to remove items from a dictionary:
#Syntax:
#nameOfDictionary("Key")
studentMarkInfo.pop("Computer")
print(studentMarkInfo)
print("##############################")
#Dynamic Dictionary
#Syntax:
#dict.fromkeys(keys, value)
#From List
myList = ["Key_01", "Key_02", "Key_03", "Key_04", "Key_05"]
myDictionary_01 = dict.fromkeys(myList, "Value")
print(myDictionary_01)
myDict = dict.fromkeys(range(1, 6), "Test")
print(myDict)
# Definition and Usage
# The setdefault() method returns the value of the item with the specified key.
# If the key does not exist, insert the key, with the specified value, see example below
#Syntax:
#dictionary.setdefault(key_name, value)
studentMarkInfo = \
{
"Id": 1,
"Name": "Vijay",
"Tamil": 97,
"English": 91,
"Maths": 100,
"Science": 98,
"Social": 99
}
print(studentMarkInfo)
# Here Science Mark has been existing so its return the value.
scienceMark = studentMarkInfo.setdefault("Science")
print(scienceMark)
# Here ComputerScience Mark has NOT existing so its insert the key.
computerMark = studentMarkInfo.setdefault("Computer")
print(computerMark)
print(studentMarkInfo)
|
# Absolute Function
"""
The abs() method returns the absolute value of x i.e.
the positive DISTANCE between x/-x and zero.
"""
x = 10
print(abs(x))
y = -10
print(abs(y))
|
from datetime import date, timedelta
days = dict()
for i in range(1, 7):
day_name = 'day_{}'.format(i)
day = date.today()-timedelta(days=(i-1))
days[day_name] = day
days2 = {y:x for x,y in days.items()}
print(days)
|
odd_set = set()
even_set = set()
for number in range(10):
if number % 2:
odd_set.add(number)
else:
even_set.add(number)
print("odd set: " + str(odd_set))
print("even set: " + str(even_set))
union_set = odd_set | even_set
print("union_set: " + str(union_set))
union_set = odd_set.union(even_set)
print("union_set: " + str(union_set))
intersection_set = odd_set & even_set
print("intersection_set: " + str(intersection_set))
intersection_set = odd_set.intersection(even_set)
print("intersection_set: " + str(intersection_set))
difference_set = odd_set - even_set
print("difference_set" + str(difference_set))
difference_set = odd_set.difference(even_set)
print("difference_set" + str(difference_set))
symmetric_difference_set = odd_set ^ even_set
print("symmetric_difference_set :" + str(symmetric_difference_set))
symmetric_difference_set = odd_set.symmetric_difference(even_set)
print("symmetric_difference_set :" + str(symmetric_difference_set))
even_set.remove(2)
print("even set : " + str(even_set))
|
import sys
import unicodedata
def print_unicode_table(word):
print("decimal hex chr {0:^40}".format("name")) # align by center for {0} - name
print("------- ----- --- {0:-<40}".format("")) # align left
code = ord(" ") # return an integer representing the Unicode code point of character
end = sys.maxunicode # get max unicode code
while code < end:
c = chr(code) # get the Unicode symbol (character) representation from integer
name = unicodedata.name(c, "*** unknown ***") # return name (string) Unicode code
if word is None or word in name.lower(): #
print("{0:7} {0:5X} {0:^3c} {1}".format(code, name.title()))
code+=1
word = None
if len(sys.argv) > 1:
if sys.argv[1] in ("-h", "--help"): # print usage information
print("usage: {0} [string]".format(sys.argv[0]))
word = 0
else:
word = sys.argv[1].lower()
if word != 0:
print_unicode_table(word)
|
#Fucntion to find the maximum repeated character
def d_find_repeated(d_sequence):
max_occurence=0
d_repeated_list=[]
d_unique=set(d_sequence)
for i in d_unique:
if d_sequence.count(i)>=max_occurence:
max_occurence=d_sequence.count(i)
d_repeated_list.append(i)
#returns the char only if it is the maximum
#if more than one char has same count it returns none
return d_repeated_list if len(d_repeated_list)==1 else None
#Enter the character with space to split
d_sequence=input("Plese enter the characters with space: ").split()
#Just printing the input after split
print(d_sequence)
print(d_find_repeated(d_sequence))
|
"""Find the number of paths of a binary tree that sum to a given value."""
from collections import deque
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def pathSum(self, root: TreeNode, target: int) -> int:
if not root:
return 0
q = deque()
q.append([root, [root.val]])
self.no_paths = 0
while q:
for _ in range(len(q)):
node, r_sum = q.popleft()
if node.val == target:
self.no_paths += 1
if node.left:
q.append([node.left, self.helper(r_sum, node.left.val, target)])
if node.right:
q.append([node.right, self.helper(r_sum, node.right.val, target)])
return self.no_paths
def helper(self, r_sum, node_val, target):
sums = [node_val]
for val in r_sum:
c_sum = val + node_val
if c_sum == target:
self.no_paths += 1
sums.append(c_sum)
return sums
|
#!/usr/bin/env python
# encoding:UTF-8
"""
Implement the following routine:
Integer findg(Integer, Integer∗)
such that findg(p,f) will return a generator of Z∗p where p is a prime
and f is a list of the prime factors of p−1.
"""
wiki primitive root modulo n
|
#!/usr/bin/env python3
import unittest
from gameOfLife import Board
class TestGOFBoard(unittest.TestCase):
def setUp(self):
self.board = Board(6,6, random_init=False)
def test_countNeighbour0(self):
self.assertEqual(self.board._countNeighbour(1,1) , 0)
def test_countNeighbour1(self):
for x in range(-1, 2): #-1 , 0, 1
for y in range(-1, 2): #-1 , 0 , 1
if not (x == 0 and y == 0):
n_i = 1 + x
n_j = 1 + y
self.board._board[n_i][n_j].setAlive()
self.assertEqual(self.board._countNeighbour(1,1) , 1)
self.board._board[n_i][n_j].setDead()
def _add_live_neighbours(self, neighbour_count):
if neighbour_count == 0:
return
count = 0
for x in range(-1, 2): #-1 , 0, 1
for y in range(-1, 2): #-1 , 0 , 1
if (not (x == 0 and y == 0)):
n_i = 1 + x
n_j = 1 + y
if(count == neighbour_count):
return
self.board._board[n_i][n_j].setAlive()
count = count + 1
def test_update_alive_0_neighbours_dies(self):
'''Any live cell with less than 2 neighbour dies'''
self.board._board[1][1].setAlive()
self.board.updateBoard()
self.assertEqual(self.board._board[1][1].isAlive(), False)
def test_update_alive_1_neighbours_dies(self):
'''Any live cell with less than 2 neighbour dies'''
self.board._board[1][1].setAlive()
self._add_live_neighbours(1)
self.board.updateBoard()
self.assertEqual(self.board._board[1][1].isAlive(), False)
def test_update_alive_2_neighbours_lives(self):
'''Any live cell with two or three live neighbours lives'''
self.board._board[1][1].setAlive()
self._add_live_neighbours(2)
self.board.updateBoard()
self.assertEqual(self.board._board[1][1].isAlive(), True)
def test_update_alive_3_neighbours_lives(self):
'''Any live cell with two or three live neighbours lives'''
self.board._board[1][1].setAlive()
self._add_live_neighbours(3)
self.board.updateBoard()
self.assertEqual(self.board._board[1][1].isAlive(), True)
def test_update_alive_4_neighbours_dies(self):
'''Any live cell with more than three live neighbours dies'''
self.board._board[1][1].setAlive()
self._add_live_neighbours(4)
self.board.updateBoard()
self.assertEqual(self.board._board[1][1].isAlive(), False)
def test_update_alive_5_neighbours_dies(self):
'''Any live cell with more than three live neighbours dies'''
self.board._board[1][1].setAlive()
self._add_live_neighbours(5)
self.board.updateBoard()
self.assertEqual(self.board._board[1][1].isAlive(), False)
def test_update_alive_6_neighbours_dies(self):
'''Any live cell with more than three live neighbours dies'''
self.board._board[1][1].setAlive()
self._add_live_neighbours(6)
self.board.updateBoard()
self.assertEqual(self.board._board[1][1].isAlive(), False)
def test_update_alive_7_neighbours_dies(self):
'''Any live cell with more than three live neighbours dies'''
self.board._board[1][1].setAlive()
self._add_live_neighbours(7)
self.board.updateBoard()
self.assertEqual(self.board._board[1][1].isAlive(), False)
def test_update_alive_8_neighbours_dies(self):
'''Any live cell with more than three live neighbours dies'''
self.board._board[1][1].setAlive()
self._add_live_neighbours(8)
self.board.updateBoard()
self.assertEqual(self.board._board[1][1].isAlive(), False)
def test_update_dead_0_neighbours_dies(self):
'''Any dead cell with not exactly three live neighbours remains dead'''
self.board._board[1][1].setDead()
self.board.updateBoard()
self.assertEqual(self.board._board[1][1].isAlive(), False)
def test_update_dead_1_neighbours_dies(self):
''''Any dead cell with not exactly three live neighbours remains dead'''
self.board._board[1][1].setDead()
self._add_live_neighbours(1)
self.board.updateBoard()
self.assertEqual(self.board._board[1][1].isAlive(), False)
def test_update_dead_2_neighbours_lives(self):
'''Any dead cell with not exactly three live neighbours remains dead'''
self.board._board[1][1].setDead()
self._add_live_neighbours(2)
self.board.updateBoard()
self.assertEqual(self.board._board[1][1].isAlive(), False)
def test_update_dead_3_neighbours_lives(self):
'''Any dead cell with exactly three live neighbours becomes a live cell, as if by reproduction.'''
self.board._board[1][1].setDead()
self._add_live_neighbours(3)
self.board.updateBoard()
self.assertEqual(self.board._board[1][1].isAlive(), True)
def test_update_dead_4_neighbours_dies(self):
'''Any dead cell with not exactly three live neighbours remains dead'''
self.board._board[1][1].setDead()
self._add_live_neighbours(4)
self.board.updateBoard()
self.assertEqual(self.board._board[1][1].isAlive(), False)
def test_update_dead_5_neighbours_dies(self):
'''Any dead cell with not exactly three live neighbours remains dead'''
self.board._board[1][1].setDead()
self._add_live_neighbours(5)
self.board.updateBoard()
self.assertEqual(self.board._board[1][1].isAlive(), False)
def test_update_dead_6_neighbours_dies(self):
'''Any dead cell with not exactly three live neighbours remains dead'''
self.board._board[1][1].setDead()
self._add_live_neighbours(6)
self.board.updateBoard()
self.assertEqual(self.board._board[1][1].isAlive(), False)
def test_update_dead_7_neighbours_dies(self):
'''Any dead cell with not exactly three live neighbours remains dead'''
self.board._board[1][1].setDead()
self._add_live_neighbours(7)
self.board.updateBoard()
self.assertEqual(self.board._board[1][1].isAlive(), False)
def test_update_dead_8_neighbours_dies(self):
'''Any dead cell with not exactly three live neighbours remains dead'''
self.board._board[1][1].setDead()
self._add_live_neighbours(8)
self.board.updateBoard()
self.assertEqual(self.board._board[1][1].isAlive(), False)
#Test for static shapes
def _set_predefined_shape(self, shape):
for i in range(len(shape)):
for j in range(len(shape[i])):
if (shape[i][j] == 1):
self.board._board[i][j].setAlive()
else:
self.board._board[i][j].setDead()
def _check_predefined_shape(self, shape):
for i in range(len(shape)):
for j in range(len(shape[i])):
if (shape[i][j] == 1):
self.assertEqual(self.board._board[i][j].isAlive(), True)
else:
self.assertEqual(self.board._board[i][j].isAlive(), False)
def test_box_shape(self):
shape = [[1,1],
[1,1]]
self._set_predefined_shape(shape)
self.board.updateBoard()
self._check_predefined_shape(shape)
def test_beehive_shape(self):
shape = [[0, 1, 1, 0],
[1, 0, 0, 1],
[0, 1, 1, 0]]
self._set_predefined_shape(shape)
self.board.updateBoard()
self._check_predefined_shape(shape)
def test_loaf_shape(self):
shape = [[0, 1, 1, 0],
[1, 0, 0, 1],
[0, 1, 0, 1],
[0, 0, 1, 0]]
self._set_predefined_shape(shape)
self.board.updateBoard()
self._check_predefined_shape(shape)
def test_boat_shape(self):
shape = [[1, 1, 0],
[1, 0, 1],
[0, 1, 0]]
self._set_predefined_shape(shape)
self.board.updateBoard()
self._check_predefined_shape(shape)
def test_tub_shape(self):
shape = [[0, 1, 0],
[1, 0, 1],
[0, 1, 0]]
self._set_predefined_shape(shape)
self.board.updateBoard()
self._check_predefined_shape(shape)
def test_blinker_period2(self):
shape = [[0, 0, 0],
[1, 1, 1],
[0, 0, 0]]
period = 2
self._set_predefined_shape(shape)
for i in range(period):
self.board.updateBoard()
self._check_predefined_shape(shape)
if __name__ == "__main__":
unittest.main()
|
from enum import IntEnum
__all__ = ["validate_roman_numeral", "roman2int", "int2roman"]
class RomanNumeral(IntEnum):
I = 1
V = 5
X = 10
L = 50
C = 100
D = 500
M = 1000
def validate_roman_numeral(numeral):
return all(char.upper() in RomanNumeral.__members__ for char in numeral)
def roman2int(r):
"Convert a Roman numeral to decimal integer (case insensitive)"
# via https://stackoverflow.com/a/62115886/2668831
numerals = [RomanNumeral[x].value for x in r.upper()]
return sum(
[
-x if i < len(numerals) - 1 and x < numerals[i + 1] else x
for i, x in enumerate(numerals)
]
)
class RomanNumeralsWithPreceders(IntEnum):
I = 1
IV = 4
V = 5
IX = 9
X = 10
XL = 40
L = 50
XC = 90
C = 100
CD = 400
D = 500
CM = 900
M = 1000
def int2roman(n):
if n in [*RomanNumeralsWithPreceders._value2member_map_]:
return RomanNumeralsWithPreceders(n).name
for i in [1000, 100, 10, 1]:
for j in [9 * i, 5 * i, 4 * i, i]:
if n >= j:
return int2roman(j) + int2roman(n - j)
|
import random
random_num = random.random()
# the random function will return a floating point number, that is 0.0 <= random_num < 1.0
#or use...
random_num = random.randint(60,100)
print random_num
def grade_test(score):
if score >= 90:
print "Score:",score,"; Your grade is A"
elif score >= 80:
print "Score:",score,"; Your grade is B"
elif score >= 70:
print "Score:",score,"; Your grade is C"
elif score >= 60:
print "Score:",score,"; Your grade is D"
grade_test(random_num)
|
#!/usr/bin/env python
import urllib2
def get_text():
url = 'https://raw.githubusercontent.com/javimb/intro-python/master/exercises/exercise_2/trash.txt'
return urllib2.urlopen(url).read()
# EXERCISE 2
# Obtener la suma de los numeros
text = get_text()
nums = filter(lambda num: num in '0123456789', text)
int_nums = map(int, nums)
print sum(int_nums)
|
def word_count(word):
words = word.split()
counts = {}
for w in words:
counts[w] = counts.get(w, 0) + 1
return counts
print(word_count('testing 1 2 testing'))
|
# -*- coding: utf-8 -*-
"""
Next Permutation
================
Implement the next permutation, which rearranges numbers into the numerically next greater permutation of numbers.
If such arrangement is not possible, it must be rearranged as the lowest possible order ie, sorted in an ascending order.
The replacement must be in-place, do not allocate extra memory.
Examples:
1,2,3 → 1,3,2
3,2,1 → 1,2,3
1,1,5 → 1,5,1
20, 50, 113 → 20, 113, 50
"""
from __future__ import print_function
def swap(l, i, j):
"""
Swap list elements
"""
tmp = l[i]
l[i] = l[j]
l[j] = tmp
def next_perm(p):
"""
Generates next permutation in O(N) time in place.
"""
n = len(p) - 1
# Find the first element from the end that breaks increase.
while n > 0:
if p[n-1] < p[n]:
break
n -= 1
p[n:] = reversed(p[n:])
if n == 0:
# All numbers in permutation form a decreasing sequence.
# This is last permutation.
# After reversion we have the first permutation
return p
# Otherwise we should bring to the n-1 position the next bigger element
for i in range(n, len(p)):
if p[i] > p[n-1]:
swap(p, i, n-1)
break
return p
l = [1, 2, 3, 4]
for _ in range(25):
print(l)
l = next_perm(l)
|
"""
Merge Intervals
===============
Given a set of non-overlapping intervals, insert a new interval into the intervals (merge if necessary).
You may assume that the intervals were initially sorted according to their start times.
Example 1:
Given intervals [1,3],[6,9] insert and merge [2,5] would result in [1,5],[6,9].
Example 2:
Given [1,2],[3,5],[6,7],[8,10],[12,16], insert and merge [4,9] would result in [1,2],[3,10],[12,16].
This is because the new interval [4,9] overlaps with [3,5],[6,7],[8,10].
Make sure the returned intervals are also sorted.
"""
from __future__ import print_function
def merge_intervals(intervals, new_interval):
new_start, new_stop = new_interval
i = 0
N = len(intervals)
# preceding intervals
while i < N:
start, stop = interval = intervals[i]
if stop < new_start:
yield interval
else:
merged_start = min(start, new_start)
merged_stop = max(stop, new_stop)
break
i += 1
# merged interval
while i < N:
start, stop = intervals[i]
if start > merged_stop:
yield [merged_start, merged_stop]
break
merged_stop = max(merged_stop, stop)
i += 1
# following intervals
for interval in intervals[i:]:
yield interval
for intervals, new_int in (
([[1,3],[6,9]], [2,5]),
([[1,2],[3,5],[6,7],[8,10],[12,16]], [4,9]),
):
print(intervals, '+', new_int, '=', list(merge_intervals(intervals, new_int)))
|
"""
Window String
=============
Given a string S and a string T, find the minimum window in S which will contain
all the characters in T in linear time complexity.
Note that when the count of a character C in T is N,
then the count of C in minimum window in S should be at least N.
Example :
S = "ADOBECODEBANC"
T = "ABC"
Minimum window is "BANC"
Note: "Distinct Numbers in Window" problem from Heaps and Maps
is very similar to that problem and can be solved with the same Counter data structure.
"""
from __future__ import print_function
from collections import Counter
import sys
def max_window(string, target):
target_count = Counter()
for l in target:
target_count[l] += 1
curr_count = Counter()
def contains_target():
return all(
curr_count[l] >= target_count[l]
for l in target_count
)
start = 0
stop = -1
min_len = sys.maxsize
min_start = 0
while True:
if contains_target():
cur_len = stop-start+1
if cur_len < min_len:
min_len = cur_len
min_start = start
# Remove first letter
l = string[start]
if l in target_count:
curr_count[l] -= 1
start += 1
else:
stop += 1
if stop == len(string):
break
l = string[stop]
if l in target_count:
curr_count[l] += 1
return string[min_start:min_start+min_len]
print(max_window("ADOBECODEBANC", "ABBC"))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.