text stringlengths 37 1.41M |
|---|
def avg(num1):
i=0
s=0
while i<num1:
num2=int(input("enter the number "))
s=s+num2
i=i+1
a=s/3
print(a)
avg(num1=3)
|
def sum_ques(nums):
i=0
s=0
while (i<len(nums)):
s=s+nums[i]
i=i+1
print(s)
sum_ques(nums=[1,2,3,4,5])
# SUM OF NUM IN FUNCTION
|
from fractions import Fraction
def expansion_binaria(fraccion):
#fraccion = str(input('Ingrese la fracción diadica en formato "1/denominador" : '))
try:
num_fraccion = fraccion.split('/')
numerador = float(num_fraccion[0])
denominador = float(num_fraccion[1])
except:
pass
#decimal_diadica = (numerador/denominador)
fraccion_diadica = Fraction(fraccion)
print(fraccion_diadica)
expansion_binaria = []
erres = []
r = fraccion_diadica
r = (r * 2)
first_r = r
while r not in erres:
if(r >= 1):
erres.append(r)
r = r - 1
expansion_binaria.append(1)
else:
erres.append(r)
expansion_binaria.append(0)
r = (r * 2)
erres.insert(0, first_r)
erres.pop(0)
period_start = erres.index(r) #repeated r
#print('erres : ', erres)
#print('expansion binaria : ', expansion_binaria, 'inicio del periodo en indice: ', period_start)
return expansion_binaria, period_start
#? ---START---
"""
n = int(input('Ingrese la cantidad de frecuencias a sacarles expansion binaria: '))
fracciones = []
for i in range(n):
f = str(input(f'#{i + 1} - Ingrese la fracción diadica en formato "1/denominador" : '))
fracciones.append(f)
for f in fracciones:
expansion_binaria(f)
""" |
x="5103720101070215"
card_number = list(x.strip())
# Remove the last digit from the card number
check_digit = card_number.pop()
# Reverse the order of the remaining numbers
card_number.reverse()
processed_digits = []
for index, digit in enumerate(card_number):
#store double of the number if even indexed.
if index % 2 == 0:
doubled_digit = int(digit) * 2
# Subtract 9 from any results that are greater than 9
if doubled_digit > 9:
doubled_digit = doubled_digit - 9
processed_digits.append(doubled_digit)
#store the number if odd indexed.
else:
processed_digits.append(int(digit))
#add the stored numbers.
total = int(check_digit) + sum(processed_digits)
# Verify that the sum of the digits is divisible by 10
if total % 10 == 0:
print("Valid card.")
else:
print("Invalid card.")
|
from turtle import Turtle
square_position =[(0, 0), (-20, 0), (-40, 0)]
UP = 90
DOWN = 270
RIGHT = 0
LEFT = 180
class Snake:
def __init__(self):
self.segments=[]
self.create_snake()
self.head = self.segments[0]
def create_snake(self):
for i in square_position:
self.add_segment(i)
def add_segment(self, i):
square = Turtle(shape="square")
square.color("white")
square.penup()
square.goto(i)
self.segments.append(square)
def extend_snake(self):
# adds new segment to the snake
self.add_segment(self.segments[-1].position())
def move(self):
for i in range(len(self.segments)-1, 0, -1):
new_x = self.segments[i-1].xcor()
new_y = self.segments[i-1].ycor()
self.segments[i].goto(new_x, new_y)
self.head.forward(20)
def up(self):
if(self.head.heading() != DOWN):
self.head.setheading(UP)
def down(self):
if (self.head.heading() != UP):
self.head.setheading(DOWN)
def left(self):
if (self.head.heading() != RIGHT):
self.head.setheading(LEFT)
def right(self):
if (self.head.heading() != LEFT):
self.head.setheading(RIGHT)
def reset(self):
for seg in self.segments:
seg.goto(1000, 1000)
self.segments.clear()
self.create_snake()
self.head = self.segments[0]
|
outFile = open("YOUR_ASSIGNMENT.txt", "w") # open the first text file in output mode first (create a new file)
print("Enter data for the first text file. Entering a $ shall result in termination of input\n")
someShit = input()
for matter in someShit:
# for every character in the input, write the character to outFile
outFile.write(matter)
print("Input accepted for YOUR_ASSIGNMENT. Can you please copy it to MY_ASSIGNMENT?\n")
outFile.close() # since data is now written to the first file successfully, we close it
inFile = open("YOUR_ASSIGNMENT.txt", "r") # notice that the first text file is now opened again, but in the input mode with inFile
outFile =open("MY_ASSIGNMENT.txt", "w") # create the second text file
# the following code actually copies the file
#while()
# we check if End of File is encountered. If not, data is read from the file
ch = inFile.read()
outFile.write(ch) # putc() puts the read character from YOUR_ASSIGNMENT.txt, to MY_ASSIGNMENT.txt which is pointed to by outFile
inFile.close();
outFile.close(); # close both the files
inFile = open("MY_ASSIGNMENT.txt", "r"); # open the second file in read (input) mode, since its contents have to be printed
print("The contents of MY_ASSIGNMENT.txt are:\n");
print(inFile.read()) # displaying contents to the console (i.e. hardware; here, monitor screen)
|
'''
Some starter code for your A* search ''
# for GUI things
'''
from tkinter import *
# for parsing XML
import xml.etree.ElementTree as ET
# for math
import math
import struct
import numpy as np
# some constants about the earth
MPERLAT = 111000 # meters per degree of latitude, approximately
MPERLON = MPERLAT * math.cos(42*math.pi/180) # meters per degree longitude at 42N
WINWIDTH = 200
WINHEIGHT = 200
decoded = []
class MyWin(Frame):
'''
Here is a Tkinter window with a canvas, a button, and a text label
It also includes a callback (event handler) on the button and one
on the canvas itself.
'''
def __init__(self,master,line,circle):
'''
you probably want to pass in your own data structures, but this shows
how to draw a line and a circle in the canvas, and also add widgets
args:
master: the Tk master object
line: a line that gets drawn
circle: a circle that gets drawn
'''
thewin = Frame(master)
w = Canvas(thewin, width=WINWIDTH, height=WINHEIGHT, cursor="crosshair")
# callbacks for mouse events in the window, if you want:
w.bind("<Button-1>", self.mapclick)
#w.bind("<Motion>", self.maphover)
# do whatever you need to do for this, lines are just defined by four pixel values
# x1 y1 x2 y2 (and can continue x3 y3 ...)
w.create_line(line[0], line[1], line[2], line[3])
w.create_line(20,20,40,40,30,60,70,90)
# same for circles (ovals), give the bounding box - for both circles and lines
# we can pass in a tuple directly for the coordinates.
w.create_oval(circle, outline='blue',fill='green',tag='greendot')
# by giving it a tag we can easily poke it later (see callback)
w.pack(fill=BOTH) # put canvas in window, fill the window
self.canvas = w # save the canvas object to talk to it later
cb = Button(thewin, text="Button", command=self.click)
# put the button in the window, on the right
# I really have not much idea how Python/Tkinter layout managers work
cb.pack(side=RIGHT,pady=5)
thewin.pack()
def click(self):
'''
Callback for the button.
'''
print ("Clicky!")
def mapclick(self,event):
'''
Callback for clicking on the canvas, click location is used
to redraw the circle at the location of the click
args:
event: click event, includes the x,y location of the click
'''
self.canvas.coords('greendot',event.x-5,event.y-5,event.x+5,event.y+5)
'''
Here are some other functions we will need:
'''
def read_elevations(efilename):
''' This reads in an HGT file of elevation data.
It is a little tricky since the file is a series of
raw 2-byte signed shorts.
args: filename - the name of an HGT file
'''
efile = open(efilename,"rb")
estr = efile.read()
elevs = []
for spot in range(0,len(estr),2):
# this magic builds a list of values (1-d, not 2-d!) and deals with the
# fact that the data file is given in big-endian format which is unusual these days...
# you may of course load this into some other data structure as you see best
elevs.append(struct.unpack('>h',estr[spot:spot+2])[0])
#for i in range (len(elevs)):
#print (elevs[i])
def read_xml(filename):
'''
This function reads in a piece of OpenStreetMap XML and prints
out all of the names of all of the "ways" (linear features).
You should replace the print with something that adds the way
to a data structure useful for searching.
'''
tree = ET.parse(filename)
root = tree.getroot()
for item in root:
# we will need nodes and ways, here we look at a way:
if item.tag == 'node':
latitude = item.get('lat')
longitude = item.get('lon')
for items in item:
if items.tag == 'tag' and items.get('k') == 'name':
name = items.get('v');
print("name: " + name )
print("lat: " + latitude)
print("long: " + longitude)
#if item.tag == 'way':
# in OSM data, most info we want is stored as key-value pairs
# inside the XML element (not as the usual XML elements) -
# so instead of looking for a tag named 'name', we look for a tag
# named 'tag' with a key inside it called 'name'
#for subitem in item: #for each tag in the tag xml
#print('id here: ' + item.get('id'));
#if subitem.tag == 'tag' and subitem.get('k') == 'name':
#if subitem.tag == 'nd':
#print(subitem.get('ref'));
# also note names are Unicode strings, depends on your system how
# they will look, I don't care too much.
#print ("Name is " + subitem.get('v'))
#break
###
def main():
read_xml("map_HARMONYDATA SET.osm")
master = Tk()
line = (60,10,70,20)
circle = (120,150,130,160)
thewin = MyWin(master,line,circle)
#f = open("n43_w114_1arc_v2.bil", "r")
#a = np.fromfile(f, dtype=np.uint32)
#print(a)
read_elevations("n43_w114_1arc_v2.bil")
# in Python you have to start the event loop yourself:
mainloop()
if __name__ == "__main__":
main()
|
# ----------[ 7 ]----------
# By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13.What is the
# 10 001st prime number?
num = 2
i = 1
while num < 10001:
i += 2
n = int(i ** 1 / 2)
if i % 5 == 0:
i += 2
n = int(i ** 1 / 2)
for j in range(3, n + 1):
if j == n:
num += 1
break
if i % j == 0:
break
print(i)
# 104759
|
print('Fibonacci Sequence')
a = int(input('Enter a Number: '))
b = 1
c = 0
e = 2
print(c)
print(b)
while e <= a:
d = b+c
print(d)
c = b
b = d
e += 1
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Sep 18 14:43:10 2019
@author: niang
"""
import numpy as np
import matplotlib as mpl
from matplotlib import pyplot as plt
fig = plt.figure(figsize=(8,8))
fig, ax = plt.subplots(1)
N=150
T=[]
def cercle(a,b,R):
for k in range(N+1):
T.append(2*np.pi*k/N)
xpoints=R*np.cos(T)+a
ypoints=R*np.sin(T)+b
ax.plot(xpoints,ypoints,color='green')
ax.set_aspect(1)
cercle(1,2,2)
cercle(2,3,1)
cercle(3,4,5)
|
# name: Persistent Bugger
# url: https://www.codewars.com/kata/55bf01e5a717a0d57e0000ec
# Write a function, persistence, that takes in a positive parameter num and returns its
# multiplicative persistence, which is the number of times you must multiply the digits
# in num until you reach a single digit.
def persistence(n):
if n < 10:
return 0
return persistence_recursive(n, 0)
def persistence_recursive(n, depth):
curr = n
result = 1
while curr >= 10:
result *= curr%10
curr = curr // 10
result *= curr
if result >= 10:
return persistence_recursive(result, depth+1)
return depth+1
if __name__ == "__main__":
print(persistence(25)) |
# name: Binary Addition
# url: https://www.codewars.com/kata/551f37452ff852b7bd000139
# Implement a function that adds two numbers together and returns their sum in binary.
# The conversion can be done before, or after the addition.
# The binary number returned should be a string
def add_binary(a,b):
mult = a + b
result = ""
while mult > 0:
result = ("1" if mult % 2 > 0 else "0") + result
mult //= 2
return result
if __name__ == '__main__':
print(add_binary(5, 9)) |
# Задание на оператор 'if'
# При решении задачи использовал исключительно оператор 'if'
# С циклами код был бы значительно короче
cities = ['Москва', 'Париж', 'Лондон']
users = [{'name': 'Иван', 'age': 35},
{'name': 'Мария', 'age': 22},
{'name': 'Соня', 'age': 20}]
tourists = [{'user': users[0], 'city': cities[2]},
{'user': users[1], 'city': cities[0]},
{'user': users[2], 'city': cities[1]}]
city = input('Введите город (Москва, Париж или Лондон): ')
message = '' # пустая строковая переменная для формирования отчета об отсутствии введенного города в списке
if city.lower() == cities[0].lower(): # проверка первого элемента в списке 'cities'
city_out = cities[0] # определение переменной города вывода для True
if city_out == tourists[0].get('city'): # проверка города вывода в первом справочнике списка 'tourists'
tourist_out = tourists[0] # определение переменной справочника с городом вывода для True
if (tourist_out.get('user')).get('name') == users[0].get('name'): # проверка наличия данных вывода в первом справочнике списка 'users'
user_out = users[0] # определение переменной справочника с данными юзера вывода для True
elif (tourist_out.get('user')).get('name') == users[1].get('name'): # проверка наличия данных вывода во втором справочнике списка 'users'
user_out = users[1] # определение переменной справочника с данными юзера вывода для True
else:
user_out = users[2] # определение переменной справочника с данными юзера вывода для предыдущих False
elif city_out ==tourists[1].get('city'): # проверка города вывода во втором справочнике списка 'tourists'
tourist_out = tourists[1] # определение переменной справочника с городом вывода для True
if (tourist_out.get('user')).get('name') == users[0].get('name'): # проверка наличия данных вывода в первом справочнике списка 'users'
user_out = users[0] # определение переменной справочника с данными юзера вывода для True
elif (tourist_out.get('user')).get('name') == users[1].get('name'): # проверка наличия данных вывода во втором справочнике списка 'users'
user_out = users[1] # определение переменной справочника с данными юзера вывода для True
else:
user_out = users[2] # определение переменной справочника с данными юзера вывода для предыдущих False
else:
tourist_out = tourists[2] # определение переменной справочника с городом вывода для предыдущих False
if (tourist_out.get('user')).get('name') == users[0].get('name'): # проверка наличия данных вывода в первом справочнике списка 'users'
user_out = users[0] # определение переменной справочника с данными юзера вывода для True
elif (tourist_out.get('user')).get('name') == users[1].get('name'): # проверка наличия данных вывода во втором справочнике списка 'users'
user_out = users[1] # определение переменной справочника с данными юзера вывода для True
else:
user_out = users[2] # определение переменной справочника с данными юзера вывода для предыдущих False
elif city.lower() == cities[1].lower(): # проверка второго элемента в списке 'cities'
city_out = cities[1] # далее структура логических условий аналогична предыдущей ветке
if city_out == tourists[0].get('city'):
tourist_out = tourists[0]
if (tourist_out.get('user')).get('name') == users[0].get('name'):
user_out = users[0]
elif (tourist_out.get('user')).get('name') == users[1].get('name'):
user_out = users[1]
else:
user_out = users[2]
elif city_out ==tourists[1].get('city'):
tourist_out = tourists[1]
if (tourist_out.get('user')).get('name') == users[0].get('name'):
user_out = users[0]
elif (tourist_out.get('user')).get('name') == users[1].get('name'):
user_out = users[1]
else:
user_out = users[2]
else:
tourist_out = tourists[2]
if (tourist_out.get('user')).get('name') == users[0].get('name'):
user_out = users[0]
elif (tourist_out.get('user')).get('name') == users[1].get('name'):
user_out = users[1]
else:
user_out = users[2]
elif city.lower() == cities[2].lower(): # проверка третьего элемента в списке 'cities'
city_out = cities[2] # далее структура логических условий аналогична предыдущим веткам
if city_out == tourists[0].get('city'):
tourist_out = tourists[0]
if (tourist_out.get('user')).get('name') == users[0].get('name'):
user_out = users[0]
elif (tourist_out.get('user')).get('name') == users[1].get('name'):
user_out = users[1]
else:
user_out = users[2]
elif city_out ==tourists[1].get('city'):
tourist_out = tourists[1]
if (tourist_out.get('user')).get('name') == users[0].get('name'):
user_out = users[0]
elif (tourist_out.get('user')).get('name') == users[1].get('name'):
user_out = users[1]
else:
user_out = users[2]
else:
tourist_out = tourists[2]
if (tourist_out.get('user')).get('name') == users[0].get('name'):
user_out = users[0]
elif (tourist_out.get('user')).get('name') == users[1].get('name'):
user_out = users[1]
else:
user_out = users[2]
else:
message = 'Указанный город не обнаружен в списке' # определение текста сообщения, если введенный город отсутствует в списке 'cities'
# вывод итогового отчета
if len(message) > 0:
print(message)
else:
print(f"Турист {user_out.get('name')} возраст {user_out.get('age')}. Посетил город {city}")
|
import name_tools as nt
import json
papers = {}
with open('papers.txt', encoding='utf-8-sig') as f:
papers = json.load(f)
def is_int(n):
try:
int(n)
return True
except ValueError:
return False
# name_tools.match is slow, so we use a preliminary check to reduce how often we have to call nt.match
def possible_match(name, last_name):
return last_name in name
# STEP 1: capitalize properly and remove non-alphabetic characters
replacements = {
' ': ' ', '-': ' ', '‐': ' ', '[': '', ']': '', '0': '', '1': '', '2': '', '3': '', '4': '', '5': '', '6': '', '7': '', '8': '', '9': '',
'á': 'a', 'é': 'e', 'í': 'i', 'ó': 'o', 'ú': 'u',
'à': 'a', 'è': 'e', 'ì': 'i', 'ò': 'o', 'ù': 'u',
'â': 'a', 'ê': 'e', 'î': 'i', 'ô': 'o', 'û': 'u',
'ä': 'a', 'ë': 'e', 'ï': 'i', 'ö': 'o', 'ü': 'u',
'ç': 'c',
}
def format_name(name):
# replace non-alphabetic characters
name = name.lower()
for r in replacements:
name = name.replace(r, replacements[r])
name = name.strip()
# capitalize properly
parts = name.split(' ')
name = ' '.join(i.capitalize() for i in parts)
if len(parts) == 2 and len(parts[0]) == 2:
# ex. Dj Rapa --> DJ Rapa
name = ' '.join([parts[0].upper(), parts[1].capitalize()])
name = name.strip()
return name
# format authors and coauthors in papers.txt
formatted_papers = {}
for name in papers:
formatted = format_name(name)
formatted_papers[formatted] = {paper: authors for paper, authors in papers[name].items()}
for name, pubs in formatted_papers.items():
for pub in pubs:
for i in range(1, len(pubs[pub])):
pubs[pub][i] = format_name(pubs[pub][i])
papers = formatted_papers
with open('papers.txt', 'w', encoding='utf-8') as f:
json.dump(papers, f, ensure_ascii=False, indent=4)
# format authors in names.txt
names = []
with open('names.txt', encoding='utf-8-sig') as f:
names = json.load(f)
formatted_names = []
for name in names:
formatted_names.append(name)
formatted_names[-1]['name'] = format_name(name['name'])
names = formatted_names
with open('names.txt', 'w', encoding='utf-8') as f:
json.dump(names, f, ensure_ascii=False, indent=4)
print('\n\n\nSTEP 1 COMPLETE: FORMATTED NAMES\n\n\n')
# STEP 2: remove the author's name from their own papers
counter = 0
for name, pubs in papers.items():
counter += 1
print(f'{counter} / {len(papers.items())}')
print('-~' * 10)
# name_tools splits into [prefix, first name plus initial, last name, suffix]
lowercase_name = format_name(name).lower() # important to format_name so author names have same formatting as coauthors
last_name = nt.split(name)[2].lower()
# store a set of ways to refer to the author so we save rechecking each time
variations = set()
variations.add(lowercase_name)
variations.add('')
for pub in pubs:
#print(f'{TEMP2} -/- {len(pubs)}')
authors = pubs[pub]
if len(authors) == 0 or (not is_int(authors[0]) and authors[0] != 'NO_YEAR'):
print(f'FLAG: {name} -/- {pub}\n{authors}\n--------')
continue
for i in range(1, len(authors)):
lowercase_author = authors[i].lower()
if lowercase_author in variations:
del authors[i]
break
if possible_match(lowercase_author, last_name):
# take advantage of short-circuit evaluation to typically not call nt.match, which is slow
if lowercase_author == lowercase_name or nt.match(lowercase_author, lowercase_name) >= 0.8:
variations.add(lowercase_author)
del authors[i]
break
with open('papers.txt', 'w', encoding='utf-8') as f:
json.dump(papers, f, ensure_ascii=False, indent=4)
print('\n\n\nSTEP 2 COMPLETE: REMOVED REDUNDANT AUTHOR NAMES\n\n\n')
# STEP 3: crunch coauthors
coauthors = {}
counter = 0
for name, publications in papers.items():
counter += 1
print(f'{counter} / {len(papers.items())} -~ ', end='')
coauthors[name] = {}
for title, others in publications.items():
# Skip empty papers OR the "we-thank-the-editors" type papers.
t = title.lower()
if others is None or 'editor' in t or (('thank' in t or 'acknowledg' in t) and ('review' in t or 'referee' in t)) or (is_int(others[0]) and int(others[0]) < 1980):
continue
for other in others[1:]: # coauthors start at index 1, after the year
if other not in coauthors[name]:
coauthors[name][other] = 1
else:
coauthors[name][other] += 1
with open('coauthors.txt', 'w', encoding='utf-8') as f:
json.dump(coauthors, f, ensure_ascii=False, indent=4)
print('\n\n\nSTEP 3 COMPLETE: CRUNCHED COAUTHORS\n\n\n')
# STEP 4: delete non-department-editor coauthors, plus expand names
dept_editor_last_names = set()
last_name_to_full_name = {}
for name in names:
last_name = name['name'].split(' ')[-1].lower()
dept_editor_last_names.add(last_name)
last_name_to_full_name[last_name] = name['name']
formatted_coauthors = {}
# whitelist stores valid ways to refer to department editors
# (i.e. include "B Bushee" because "Brian Bushee" is an editor)
# blacklist stores invalid ways to refer to department editors
# (i.e. include "R Ranarana" because no one is named that)
whitelist = set()
blacklist = set()
counter = 0
for name, coauths in coauthors.items():
counter += 1
print(f'{counter} / {len(coauthors.items())}')
print('-~' * 10)
formatted_coauthors[name] = {}
for coauth, weight in coauths.items():
last_name = coauth.split(' ')[-1].lower()
if last_name not in dept_editor_last_names:
continue
# full_name is what the name should be, i.e. 'Brian Bushee'
# coauth might be 'B Bushee' or 'R Bushee'
full_name = last_name_to_full_name[last_name]
if coauth not in whitelist:
if nt.match(coauth, full_name) >= 0.8:
whitelist.add(coauth)
else:
blacklist.add(coauth)
continue
if full_name not in formatted_coauthors[name]:
formatted_coauthors[name][full_name] = weight
else:
formatted_coauthors[name][full_name] += weight
coauthors = formatted_coauthors
with open('coauthors.txt', 'w', encoding='utf-8') as f:
json.dump(coauthors, f, ensure_ascii=False, indent=4)
print('\n\n\nSTEP 4 COMPLETE: FORMATTED COAUTHORS\n\n\n')
def undirect(coauthors):
# We want an undirected graph, but because Google Scholar is imperfect, we sometimes
# get data that says John Smith has coauthored 12 papers with Sandy Roland, while
# Sandy Roland has only coauthored 11 papers with John Smith. This function takes a
# maximum to fix these anomalies and create an approximate undirected graph.
for name, coauths in coauthors.items():
for coauth, weight in coauths.items():
us = weight
them = coauthors[coauth][name] if name in coauthors[coauth] else 0
coauths[coauth] = max(us, them)
coauthors[coauth][name] = max(us, them)
return coauthors
coauthors = undirect(coauthors)
with open('coauthors.txt', 'w', encoding='utf-8') as f:
json.dump(coauthors, f, ensure_ascii=False, indent=4)
print('\n\n\nSTEP 5 COMPLETE: MADE GRAPH UNDIRECTED\n\n\n')
|
arr1 = ['a', 'b', 'c', 'd', 'x']
arr2 = ['z', 'x', 'y']
def contains_common_item(arr1, arr2):
big_array = arr1 + arr2
big_set = set(big_array)
if len(big_array) == len(big_set):
return False
return True
print(contains_common_item(arr1, arr2))
|
"""Utility functions"""
import os
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
def symbol_to_path(symbol, base_dir="data"):
"""Return CSV file path given ticker symbol."""
return os.path.join(base_dir, "{}.csv".format(str(symbol)))
def get_data(symbols, dates):
"""Read stock data (adjusted close) for given symbols from CSV files."""
df = pd.DataFrame(index=dates)
if 'SPY' not in symbols: # add SPY for reference, if absent
symbols.insert(0, 'SPY')
for symbol in symbols:
df_temp = pd.read_csv(symbol_to_path(symbol),index_col='Date',
parse_dates=True, usecols=['Date','Adj Close'], na_values=['nan'])
df_temp = df_temp.rename(columns={'Adj Close':symbol})
df = df.join(df_temp)
if symbol =='SPY':
df = df.dropna(subset=['SPY'])
return df
def normalize_data(df):
'''Normalize stock prices using the first rows of the dataframe'''
return df/df.ix[0,:]
def plot_data(df, title="Stock prices", xlabel="Date", ylabel="Price"):
"""Plot stock prices with a custom title and meaningful axis labels."""
ax = df.plot(title=title, fontsize=12)
ax.set_xlabel(xlabel)
ax.set_ylabel(ylabel)
plt.show()
#ax.set_xlabel("Date")
#ax.set_ylabel("Price")
#ax.legend(loc='upper left')
def plot_selected(df, columns, start_index, end_index):
"""Plot the desired columns over index values in the given range."""
df = df.ix[start_index:end_index,columns]
# Note: DO NOT modify anything else!
plot_data(df)
def get_rolling_mean(values, window):
"""Return rolling mean of given values, using specified window size."""
return pd.rolling_mean(values, window=window)
def get_rolling_std(values, window):
"""Return rolling standard deviation of given values, using specified window size."""
return pd.rolling_std(values, window=window)
def get_bollinger_bands(rm, rstd):
"""Return upper and lower Bollinger Bands."""
upper_band = rm + rstd*2
lower_band = rm - rstd*2
return upper_band, lower_band
def compute_daily_returns(df):
"""Compute and return the daily return values."""
daily_returns = df.copy()
#Compute daily returns for rows 1 onwars
daily_returns[1:] = (df[1:]/df[:-1].values) -1 #.values to use numpy
#daily_returns = (df /df.shift(1)) -1 #much easier with Pandas
daily_returns.ix[0,:] = 0 #set daily_returnsfor row 0 to 0
return daily_returns
def compute_cumulative_returns(df):
"""Compute and return the daily return values."""
cumulative_returns = df.copy()
#Compute cumulative_returns for rows 1 onwars
#cumulative_returns = (df/df.ix[0,:].values) -1 #.values to use numpy
cumulative_returns = (df/df.ix[0,:]) -1 #much easier with Pandas
return cumulative_returns
def test_run():
# Define a date range
dates = pd.date_range('2010-01-01', '2010-12-31')
# Choose stock symbols to read
symbols = ['GOOG', 'IBM', 'GLD']
# Get stock data
df = get_data(symbols, dates)
# Slice by row range (dates)
#print (df.ix['2010-01-01':'2010-01-31'])
#Slice by column (symbols)
#print (df['GOOG'])
#print (df[['IBM','GLD']])
# Slice by row range (dates) & column
#print (df.ix['2010-01-01':'2010-01-31',['IBM','GLD']])
#Data plot
#plot_data(df)
#ax = df['SPY'].plot(title="SPY rolling mean",label='SPY')
# Slice and plot
#plot_selected(df, ['SPY', 'IBM'], '2010-03-01', '2010-04-01')
#Compute mean
#print (df.mean())
#Compute rolling mean using a 20-days window
rm_SPY = pd.rolling_mean(df['SPY'],window=20)
#Compute rolling standard deviation
rstd_SPY = get_rolling_std(df['SPY'], window=20)
#Compute upper and lower bands
upper_band, lower_band = get_bollinger_bands(rm_SPY, rstd_SPY)
# Plot raw SPY values, rolling mean and Bollinger Bands
ax = df['SPY'].plot(title="Bollinger Bands", label='SPY')
rm_SPY.plot(label='Rolling mean', ax=ax)
upper_band.plot(label='upper band', ax=ax)
lower_band.plot(label='lower band', ax=ax)
# Add axis labels and legend
ax.set_xlabel("Date")
ax.set_ylabel("Price")
ax.legend(loc='upper left')
plt.show()
# Compute daily returns
daily_returns = compute_daily_returns(df)
plot_data(daily_returns, title="Daily returns", ylabel="Daily returns")
# Compute daily returns
cumulative_returns = compute_cumulative_returns(df)
plot_data(cumulative_returns, title="Cumulative Returns", ylabel="Cumulative Returns")
if __name__ == "__main__":
test_run()
|
def si(y) :
if y > 7 :
print("yes!")
else :
print("no")
def age(age) :
if age<18 :
print("Quelle es ton école?")
elif 17 < age < 65 :
print("Ou travailles-tu?")
else :
print("Wow... T'es vieux.vieille")
|
"""Generate Markov text from text files."""
from random import choice
# import random
import sys
def open_and_read_file(file_path):
"""Take file path as string; return text as string.
Takes a string that is a file path, opens the file, and turns
the file's contents as one string of text.
"""
# Use open function to open the file, file_path
# Get text from file as a string and use read method
# Return that
text_file = open(file_path)
return text_file.read()
# print(open_and_read_file('green-eggs.txt'))
def make_chains(text_string):
"""Take input text as string; return dictionary of Markov chains.
A chain will be a key that consists of a tuple of (word1, word2)
and the value would be a list of the word(s) that follow those two
words in the input text.
For example:
>>> chains = make_chains('hi there mary hi there juanita')
Each bigram (except the last) will be a key in chains:
>>> sorted(chains.keys())
[('hi', 'there'), ('mary', 'hi'), ('there', 'mary')]
Each item in chains is a list of all possible following words:
>>> chains[('hi', 'there')]
['mary', 'juanita']
>>> chains[('there','juanita')]
[None]
"""
chains = {}
# your code goes here
# Split input text string and store as variable, words
# Loop over the range of length of list
# Create a tuple of words[i] and words [i+1] and assign as a key
# Create a value variable as assign as words[i+2]
# Put the key and value we made into chains - chains[key] = [value]
words = text_string.split()
for i in range(len(words) - 2):
key = (words[i], words[i+1])
value = words[i+2]
chains[key] = chains.get(key, [])
# print(f'chains is {chains}')
# print(f'chains[key] is {chains[key]}')
chains[key].append(value)
# print(chains)
return chains
# def make_chains(text_string, n):
# chains = {}
# # Split input text string and store as variable, words
# # Loop over the range of length of list
# # Create a tuple of words[i] and words [i+1] and assign as a key
# # Create a value variable as assign as words[i+2]
# # Put the key and value we made into chains - chains[key] = [value]
# words = text_string.split()
# for i in range(len(words) - n):
# key = ()
# ctr = 0
# while n > 0:
# key += (words[i+ctr],)
# ctr += 1
# n -= 1
# value = words[i+n]
# chains[key] = chains.get(key, [])
# # print(f'chains is {chains}')
# # print(f'chains[key] is {chains[key]}')
# chains[key].append(value)
# # print(chains)
# return chains
def make_text(chains):
"""Return text from chains."""
words = []
# Use the random module to get the first random key (tuple)
# Get the first and second word in the tuple we got, key[0] and [1]
# Add them to words
# Loop to keep getting random word until we run out of words using while True
# if key is in dictionary
# Look into the values list, get a random word
# Add that random word to words
# New key = second word and random word in value, this will be a tuple
# Get random word associated with new key
# Append new word to words
# if key key not in dictionary, break
random_key = choice(list(chains))
words.extend([random_key[0], random_key[1]])
current_key = random_key
while True:
if current_key in chains:
new_word = choice(chains[current_key])
words.append(new_word)
current_key = (current_key[1], new_word)
else:
break
# print(' '.join(words))
return ' '.join(words)
input_path = sys.argv[1]
# Open the file and turn it into one long string
input_text = open_and_read_file(input_path)
# Get a Markov chain
chains = make_chains(input_text)
# Produce random text
random_text = make_text(chains)
print(random_text)
|
class Node(object):
"""
class used to represent a Node.
"""
def __init__(self, data=None, next_node=None):
self.data = data
self.next_node = next_node
def __iter__(self):
nodes = [self]
while nodes[-1].has_next():
nodes.append(nodes[-1].next_node)
return iter(nodes)
def has_next(self):
return self.next_node is not None
def get_linked_list_length(n):
"""
Get length of list given a starting node.
:param n: Node that may or may not have following Nodes
:type n: Node
:return: The length of the list starting at the given Node
:rtype: int
"""
return len([_ for _ in iter(n)])
def main():
nodes = Node(data=1, next_node=Node(data=2, next_node=Node(data=3)))
length = get_linked_list_length(nodes)
print(length)
if __name__ == '__main__':
main()
|
import re
def all_matching_strings(regex, out_length):
if out_length == 0: return
output = [0] * out_length
for x in range(2**out_length):
r = ''.join(['a','b'][i] for i in output)
if regex.match(r):
yield(r)
i = 0
output[i] += 1
while (i<out_length) and (output[i]==2):
output[i] = 0
i += 1
if i<out_length: output[i] += 1
return
count = int(input())
regexs = []
while count > 0:
str = input().split(' ')
regexs.append((str[0],int(str[1])))
a = all_matching_strings(re.compile('^'+str[0]+'$'), int(str[1]))
print(len([x for x in a]))
count -= 1 |
t = int(input().strip())
def solve(passwords, loginAttempt):
dead_end = set()
stack = []
stack.append(([], loginAttempt))
while stack:
acc, cur = stack.pop()
if cur == "":
return acc
is_dead_end = True
for password in passwords:
if cur.startswith(password):
cur2 = cur[len(password):]
if cur2 in dead_end:
continue
is_dead_end = False
acc2 = acc[:]
acc2.append(password)
stack.append((acc2, cur2))
if is_dead_end:
dead_end.add(cur)
for ti in range(t):
n = int(input().strip())
passwords = [tmp for tmp in input().strip().split(' ')]
loginAttempt = input().strip()
answer = solve(passwords, loginAttempt)
print("WRONG PASSWORD" if answer is None else " ".join(answer)) |
def rgb_to_cmyk(r,g,b):
cmyk_scale = 100
if (r == 0) and (g == 0) and (b == 0):
return 0, 0, 0, cmyk_scale
c = 1 - r / 255.
m = 1 - g / 255.
y = 1 - b / 255.
min_cmy = min(c, m, y)
c = (c - min_cmy) / (1 - min_cmy)
m = (m - min_cmy) / (1 - min_cmy)
y = (y - min_cmy) / (1 - min_cmy)
k = min_cmy
return c*cmyk_scale, m*cmyk_scale, y*cmyk_scale, k*cmyk_scale
def rgb_to_hsv(r, g, b):
r, g, b = r/255.0, g/255.0, b/255.0
mx = max(r, g, b)
mn = min(r, g, b)
df = mx-mn
if mx == mn:
h = 0
elif mx == r:
h = (60 * ((g-b)/df) + 360) % 360
elif mx == g:
h = (60 * ((b-r)/df) + 120) % 360
elif mx == b:
h = (60 * ((r-g)/df) + 240) % 360
if mx == 0:
s = 0
else:
s = df/mx
v = mx
return h, s, v
if __name__ == "__main__":
print('Entre com os valores de RGB:')
r = eval(input('R:'))
g = eval(input('G:'))
b = eval(input('B:'))
c, m, y, k = rgb_to_cmyk(r, g, b)
h, s, v = rgb_to_hsv(r, g , b)
print("RGB({0},{1},{2}) = CMYK({3:.2f},{4:.2f},{5:.2f},{6:.2f})".format(r,g,b,c,m,y,k))
print("RGB({0},{1},{2}) = HSV({3:.2f}º,{4:.2f}%,{5:.2f}%)".format(r,g,b,h,s*100,v*100)) |
'''
Calculate GPA for classes.
'''
gradePoints ={'A':4, 'B':3, 'C':2, 'D':1, 'F':0}
'''
Function addClass: Add classname to dictionary of classes
'''
def addClass(classes, className, grade, credits):
if takenClass(classes, className):
return False
else:
#classes[className] = [grade, credits]
classes[className] = {}
classes[className]['grade'] = grade
classes[className]['credits'] = credits
return True
'''
Function importReportCard: # Import datafile to dictionary of classes
'''
def importReportCard(classes, filename='reportcard.txt'):
dataFile = open(filename, 'r')
for line in dataFile:
line = line.strip()
(className, grade, credits) = line.split(':')
credits= int(credits)
addClass(classes, className, grade, credits)
dataFile.close()
'''
Function dropClass: Rmove a class from dictionary of classes
'''
def dropClass(classes, className):
if takenClass(classes, className):
#classes.pop(className)
del classes[className]
return True
else:
return False
'''
Function attemptedCredits: Return the number of attempted credits.
'''
def attemptedCredits(classes):
aCredits = 0
for value in classes:
aCredits += classes[value]['credits']
return aCredits
'''
Function passedCredits: Return the number of passed credits(A-D).
'''
def passedCredits(classes):
pCredits = 0
for value in classes:
if classes[value]['grade'] != 'F':
pCredits += classes[value]['credits']
return pCredits
'''
Function takenClass: If a class is in dictionary of classes, return True.
'''
def takenClass(classes, className):
if className in classes:
return True
else:
return False
'''
Function getGPA: Return the number of GPA.
'''
def getGPA(classes):
totalPoints = 0
for value in classes:
points = classes[value]['grade']
totalPoints += classes[value]['credits'] * gradePoints[points]
gpa = totalPoints/attemptedCredits(classes) # if not include 'F', use next command.
#gpa = totalPoints/passedCredits(classes)
return gpa
'''
Function updateClass: Update a class with new grade
'''
def updateClass(classes, className, grade):
if takenClass(classes, className):
classes[className]['grade'] = grade
return True
else:
return False
'''
Function printClass: print classes in a neat talble.
'''
def printClass(classes):
print(format(' Class', '15s')+format('Grade', '10s')+format('Credits', '10s'))
n=0
sortedClass = list(classes.keys())
sortedClass.sort()
for value in sortedClass:
n += 1
print (str(n)+'. '+format((value+':'), '14s')+format(classes[value]['grade'], '5s')+ format(classes[value]['credits'], '10d'))
gpa= float(getGPA(classes))
print()
print ('Overall GPA:', format(gpa, '5.3f'))
'''
Test above Functions.
'''
def main():
classes = {}
addClass(classes, 'CS160', 'A', 4)#test addClass and takenClass
addClass(classes, 'CS161', 'A', 3)
addClass(classes, 'Math201', 'F', 3)
importReportCard(classes, filename='reportcard.txt' ) #test importRportCard
print(classes)
print()
print('After drop classes CS161:')
dropClass(classes, 'CS161')#test dropClass and takenClass
print(classes)
print()
aC = attemptedCredits(classes)#test attemptedCredits
print('Attempted Credits:', aC)
print()
pC = passedCredits(classes)#test passedCredits
print('Passed Credits:', pC)
print()
print('After update classes Math201:')
updateClass(classes, 'Math201', 'A')#Test Updateclass and takenClass
print(classes)
print()
printClass(classes)# Test printClass and getGPA
main()
|
class Employee:
def __init__(self, name, date):
self.name = name
self.date = date
def details(self):
print("Employee Name:", self.name)
print("Employee joining date:", self.date)
emp = Employee("john", "18-02-2020")
emp.details()
|
# Write a program that asks for two numbers
# Thw first number represents the number of girls that comes to a party, the
# second the boys
# It should print: The party is exellent!
# If the the number of girls and boys are equal and there are more people coming than 20
#
# It should print: Quite cool party!
# It there are more than 20 people coming but the girl - boy ratio is not 1-1
#
# It should print: Average party...
# If there are less people coming than 20
#
# It should print: Sausage party
# If no girls are coming, regardless the count of the people
ngirls = input("Type a number representing the number of female visitors: ")
nboys = input("Type a number representing the number of male visitors: ")
ngirls = int(ngirls)
nboys = int(nboys)
if ngirls == nboys and ngirls + nboys >= 20:
print("The party is exellent!")
elif ngirls != nboys and ngirls + nboys >= 20:
print("Quite cool party!")
elif ngirls + nboys < 20:
print("Average party...")
elif ngirls <= 0:
print("Sausage party")
|
# - Create a function called `factorio`
# that returns it's input's factorial
def factorio(numb):
summ = 1
for n in range(1, numb + 1):
summ = summ * n
return summ
print(factorio(5)) |
from d1_e3_Domino import Domino
def initialize_dominoes():
dominoes = []
dominoes.append(Domino(5, 2))
dominoes.append(Domino(4, 6))
dominoes.append(Domino(1, 5))
dominoes.append(Domino(6, 7))
dominoes.append(Domino(2 ,4))
dominoes.append(Domino(7, 1))
return dominoes
dominoes = initialize_dominoes()
# You have the list of Dominoes
# Order them into one snake where the adjacent dominoes have the same numbers on their adjacent sides
# eg: [2, 4], [4, 3], [3, 5] ...
# print(dominoes)
# FIRST TRY
# for domi in range(len(dominoes)):
# # if dominoes[domi].values[1] == dominoes[domi - 1].values[0]:
# for domiNum in dominoes[domi].values[]:
# if domiNum == dominoes[domi+1].values[0]:
# print('Success', dominoes[domi].values[1], dominoes[domi - 1].values[0])
# else:
# print('Hope')
# # if domi[1] == domi + 1[0]
# SOLUTION 1
# for i in range(len(dominoes) - 1):
# for j in range(len(dominoes)):
# if dominoes[i].values[1] == dominoes[j].values[0]:
# temp = dominoes[i + 1]
# dominoes[i + 1] = dominoes[j]
# dominoes[j] = temp
# print(dominoes)
# SOLUTION 2
def sorter(list):
new_dominoes = []
new_dominoes.append(dominoes[0])
while len(new_dominoes) != len(list):
for i in range(1, len(dominoes)):
if dominoes[i].values[0] == new_dominoes[-1].values[1]:
new_dominoes.append(dominoes[i])
return new_dominoes
print(sorter(dominoes)) |
# - Create a variable named `aj`
# with the following content: `[3, 4, 5, 6, 7]`
# - Reverse the order of the elements in `aj`
# - Print the elements of the reversed `aj`
aj = [3, 4, 5, 6, 7]
# rj = 0
# for i in range(len(aj) - 1, -1, -1):
# rj.append(i)
# print(aj = rj)
aj[4], aj[3], aj[2], aj[1], aj[0] = aj[0], aj[1], aj[2], aj[3], aj[4]
print(aj)
# OR:
# ja = []
# for i in aj[::-1]:
# ja.append(i)
# aj = ja
# print(aj) |
# Create a method that decrypts encoded-lines.txt
# def decrypt(file_name):
# textfile = open(file_name)
# textdec = open('file10dec.txt', 'w')
# textorig = textfile.read()
# text = ''
# for i in textorig:
# charval = ord(i)
# text += chr(charval - 1)
# textdec.write(text)
# textfile.close
# textdec.close
# return text
# print(decrypt('file10.txt'))
def decrypt(file_name):
textfile = open(file_name)
textdec = open('file10dec.txt', 'w')
textlist = textfile.readlines()
# miért nem definiálhatom ezt itt?: textlines = ''
for line in textlist:
textlines = ''
for char in line:
if char == ' ':
textlines += ' '
else:
charval = ord(char)
textlines += chr(charval - 1)
textdec.write(textlines + '\n')
textfile.close
textdec.close
return 'Yes'
print(decrypt('file10.txt')) |
from tkinter import *
root = Tk()
canvas = Canvas(root, width='300', height='300')
canvas.pack()
# reproduce this:
# [https://github.com/greenfox-academy/teaching-materials/blob/master/workshop/drawing/purple-steps-3d/r4.png]
x = 5
for i in range(1, 6):
x *= 2
canvas.create_rectangle(x, x, x+x, x+x, fill='purple')
root.mainloop() |
# Given base and n that are both 1 or more, compute recursively (no loops)
# the value of base to the n power, so powerN(3, 2) is 9 (3 squared).
def topower(base, power):
if base == 0 or power == 0:
return 1
else:
return base * topower(base, power - 1)
print(topower(3, 4)) |
# Write a program that reads a number from the standard input, then draws a
# square like this:
# %%%%%
# %% %
# % % %
# % %%
# % %
# %%%%%
# The square should have as many lines as the number was
numi = int(input("Dobj ide nekem egy numit haver:" ))
for n in range(1, numi +1):
print("%")
|
#User function Template for python3
def countOfElements( arr, total_num, x):
count=0
for i in range(total_num):
if(arr[i]<=x):
#print(arr[i])
count = count + 1
#print(count)
else:
exit
return count
def main():
T = int(input())
while(T > 0):
n = int(input())
a = [int(x) for x in input().strip().split()]
k = int(input())
print(countOfElements(a, n, k))
T -= 1
if __name__ == "__main__":
main()
|
my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
# STRETCH: implement Linear Search
def linear_search(arr, target):
for i in arr:
if i == target:
return True
return False
linear_search(my_list, 8)
# STRETCH: write an iterative implementation of Binary Search
def binary_search(arr, target):
if len(arr) == 0:
return -1 # array empty
lo = 0
hi = len(arr)-1
while lo < hi:
mid = (lo + hi)//2
if target == arr[mid]:
return True
elif target > arr[mid]:
lo = arr[mid]
else:
hi = arr[mid]
return False # not found
binary_search(my_list, 8)
# STRETCH: write a recursive implementation of Binary Search
def binary_search_recursive(arr, target, low, high):
middle = (low+high)//2
if len(arr) == 0:
return False # array empty
'''
FROM CLASS - BINARY SEARCH CODE:
Binary Search is O(log(n))
Assume the array is sorted, return True if target is in the list
'''
def class_binary_search(arr, target):
# set boundaries for low and high marks to search
lo = 0
hi = len(arr)
# while low and high do not overlap...
while lo < hi:
# check the middle
mid = (lo + hi) // 2
# if equal, return True
if arr[mid] == target:
return True
# else, if target is smaller
elif target < arr[mid]:
# set the high to the midpoint value
hi = mid - 1
# else, if target is bigger
else:
# set the low to midpoint value
lo = mid + 1
# if we get to the end, return False
return False
print(class_binary_search(my_list, 30))
print(class_binary_search(my_list, 10))
print(class_binary_search(my_list, 8))
'''
Challenge from Training Kit:
Write a recursive search function that receives as input an array of
integers and a target integer value. This function should return True
if the target element exists in the array, and False otherwise.
'''
def recursive_search(arr, target):
i = len(arr) - 1
if i < 0:
return False
elif arr[i] == target:
return True
else:
arr.pop()
recursive_search(arr, target)
recursive_search([1, 2, 3, 4, 5, 6, 7, 8, 9], 6)
|
def readInteger():
try:
sNumber = raw_input()
return int(sNumber)
except ValueError:
print "Skipping value '",sNumber,"'. Not a number"
exit()
print "This will find indexes/positions of numbers from the list."
print "Enter size of the 1st list (the original data):"
iSizeDataset = readInteger()
print "Enter size of the 2nd list (the numbers to look for in original data):"
iSizeLookFor = readInteger()
print "Enter", iSizeDataset, "numbers for the 1st list (the original data):"
iNumbersDataset = []
for iN in range(iSizeDataset):
iNumbersDataset.append(readInteger())
print "Enter", iSizeLookFor, " numbers for the 2nd list (the numbers to look for in original data):"
iNumbersLookFor = []
for iN in range(iSizeLookFor):
iNumbersLookFor.append(readInteger())
print "Original dataset: ", iNumbersDataset
iIndexedDataset = dict({})
print "Indexing original dataset ..."
for i, number in enumerate(iNumbersDataset):
if not number in iIndexedDataset.keys():
iIndexedDataset[number] = i + 1
print "Original dataset was indexed:", iIndexedDataset
print "Numbers to look for: ", iNumbersLookFor
iResultIndexes = []
for i, number in enumerate(iNumbersLookFor):
iResultIndexes.append(iIndexedDataset[number] if (number in iIndexedDataset.keys()) else 0)
print "Indexes found: ", iResultIndexes
print "Bye"
|
import random
class Ability:
def __init__(self, name, attack_strength):
'''Create Instance Variables:
name:String
max_damage: Integer
'''
self.name = name
self.attack_strength = attack_strength
# TODO: Instantiate the variables listed in the docstring with then
# values passed in
pass
def attack(self):
''' Return a value between 0 and the value set by self.max_damage.'''
# TODO: Use random.randint(a, b) to select a random attack value.
self.attack_value = random.randint(0,1500)
self.max_damage = 1500
# Return an attack value between 0 and the full attack.
return self.attack_value
# Hint: The constructor initializes the maximum attack value.
class Armor:
def __init__(self, name, max_block):
#TODO: Create instance variables for the values passed in.
self.name = name
self.max_block = max_block
def block(self):
''' Return a random value between 0 and the initialized max_block strength. '''
self.defense_value = random.randint(0,500)
self.max_block = 500
return self.defense_value
class Weapon(Ability):
def __init__(self, name, attack_value):
super().__init__(name, attack_value)
def attack(self):
""" This method returns a random value
between one half to the full attack power of the weapon.
"""
self.attack_value = random.randint(0, 1500)
# TODO: Use what you learned to complete this method.
damage = random.randint(0, self.attack_value)
return damage // 2
class Hero:
def __init__(self, name, deaths = 0, kills = 0, starting_health = 5000, defense_value = 50, attack_value = 50):
'''Instance properties:
abilities: List
armors: List
name: String
starting_health: Integer
current_health: Integer
'''
# TODO: Initialize instance variables values as instance variables
self.abilities = []
self.armor = []
self.deaths = 0
self.kills = 0
self.name = name
self.defense_value = defense_value
self.attack_value = attack_value
self.starting_health = self.current_health = starting_health
self.stats = self.deaths, self.kills
# (Some of these values are passed in above,
# others will need to be set at a starting value)
# abilities and armors are lists that will contain objects that we can use
def begin_fight(self):
print("Welcome to the arena!")
user_input = input("Would you like to create your very own hero?\n")
user_input = user_input.lower()
while True:
if user_input == "yes":
self.hero_creation()
elif user_input == "no":
print("Then choose a pre-made hero to play as.")
print("Your choices are: Double, Kiva, Kabuto, Groh, Dimitri, and Orochi.")
user_input = input("Make your decision.\n")
user_input = user_input.lower()
while True:
if user_input == "Double":
add_hero(my_hero)
remove_hero(default)
print("You have chosen {0}!".format(self.name))
if user_input == "Kiva":
add_hero(my_hero2)
remove_hero(default)
if user_input.lower() == "Kabuto":
add_hero(my_hero3)
remove_hero(default)
if user_input.lower() == "Groh":
add_hero(my_hero4)
remove_hero(default)
if user_input.lower() == "Dimitri":
add_hero(my_hero5)
remove_hero(default)
if user_input.lower() == "Orochi":
add_hero(my_hero6)
remove_hero(default)
user_input = input("Ready to battle?\n")
user_input = user_input.lower()
while True:
if user_input == "yes":
print("Beginning fight...")
break
elif user_input == "no":
print("There's no use running!")
user_input = input("Ready to battle?\n")
user_input = user_input.lower()
else:
user_input = input("Ready to battle?\n")
user_input = user_input.lower()
def add_ability(self, ability):
''' Add ability to abilities list '''
# TODO: Add ability object to abilities:List
self.abilities.append(ability)
def add_armor(self, armor):
'''Add armor to self.armors
Armor: Armor Object
'''
# TODO: Add armor object that is passed in to `self.armors`
self.armor.append(armor)
def add_weapon(self, weapon):
self.abilities.append(weapon)
def add_kills(self, num_kills):
''' Update kills with num_kills'''
# TODO: This method should add the number of kills to self.kills
self.kills += num_kills
def add_deaths(self, num_deaths):
self.deaths = num_deaths
def attack(self):
'''Calculate the total damage from all ability attacks.
return: total:Int'''
total = 0
for ability in self.abilities:
total += ability.attack()
return total
# TODO: This method should run Ability.attack() on every ability
# in self.abilities and returns the total as an integer.
def defend(self, damage_amt):
'''Runs `block` method on each armor.
Returns sum of all blocks
'''
total_armor = 0
for armor in self.armors:
block = armor.block()
total_armor = total_armor + block
return sum
def take_damage(self, damage):
'''Updates self.current_health to reflect the damage minus the defense.
'''
self.current_health = self.current_health - damage - self.defense_value
return self.current_health
print("Took damage! Remaining health: {0}".format(self.current_health))
def is_alive(self):
if self.current_health < 0:
return False
else:
return True
pass
def team_battle(self, opponent):
''' Battle each team against each other.'''
# TODO: Randomly select a living hero from each team and have
# them fight until one or both teams have no surviving heroes.
# Hint: Use the fight method in the Hero class.
team_one_name = "My Team"
team_two_name = "Opposing Team"
team_one = Team("My Team")
team_two = Team("Opposing Team")
test_hero1 = Hero("Masamune Date")
test_hero2 = Hero("Yukimura Sanada")
team_one.add_hero(test_hero2)
team_two.add_hero(test_hero1)
print("{0} vs. {1}! Only one shall emerge victorious!".format(team_one_name, team_two_name))
while self.is_alive() and enemy_team.is_alive():
my_team_hero = self.randomhero()
enemy_team_hero = enemy_team.randomhero()
my_team_hero.fight(enemy_team_hero)
# Fightin'
damage = self.attack()
opponentdamage = opponent.attack()
opponent.take_damage(damage)
self.take_damage(opponentdamage)
if enemy_team_hero == False:
print("{0} has fallen! {1} is the victor!".format(self.name, my_hero4.name))
if my_team_hero.is_alive() == False:
print("{0} has fallen! {1} is the victor!".format(self.name, my_hero4.name))
def fight(self, opponent):
''' Current Hero will take turns fighting the opponent hero passed in.
'''
# TODO: Fight each hero until a victor emerges.
# If both heroes lack abilities, call a draw
while self.is_alive() == True and opponent.is_alive() == True:
if len(self.abilities) == 0 and len(opponent.abilities) == 0:
print("{0} and {1} both lack abilities! It's a draw!".format(self.name, opponent.name))
break
# Fightin'
damage = self.attack()
opponentdamage = opponent.attack()
opponent.take_damage(damage)
self.take_damage(opponentdamage)
# Print the victor's name to the screen.
#TODO: Refactor this method to update the
# number of kills the hero has when the opponent dies.
# Also update the number of deaths for whoever dies in the fight
# Player Dies
if self.is_alive() == False:
print("{0} has fallen!".format(self.name))
print("{0} wins!".format(opponent.name))
# add stats
self.add_deaths(1)
opponent.add_kills(1)
# victory quotes
if opponent.name == "Double" and opponent.is_alive() == True:
print("Phillip: We are victorious.")
print("Shotaro: Excellent work, Phillip.")
if opponent.name == "Kiva" and opponent.is_alive() == True:
print("Kivat: Wataru, nice work!")
print("Wataru: It's finally over...")
if opponent.name == "Kabuto" and opponent.is_alive() == True:
print("Tendou: I am the one who walks the path to heaven.")
if opponent.name == "Groh" and opponent.is_alive() == True:
print("Groh: Target eliminated. Moving on to next assignment.")
if opponent.name == "Dimitri" and opponent.is_alive() == True:
print("Dimitri: I pray for a day in which needless bloodshed will cease.")
if opponent.name == "Orochi" and opponent.is_alive() == True:
print("Orochi: Pathetic...I long for a real challenge...")
# Opponent Dies
if opponent.is_alive() == False:
print("{0} has fallen!".format(opponent.name))
print("{0} wins!".format(self.name))
# add stats
opponent.add_deaths(1)
self.add_kills(1)
# victory quotes
if self.name == "Double" and self.is_alive() == True:
print("Phillip: We are victorious.")
print("Shotaro: Excellent work, Phillip.")
if self.name == "Kiva" and self.is_alive() == True:
print("Kivat: Wataru, nice work!")
print("Wataru: It's finally over...")
if self.name == "Kabuto" and self.is_alive() == True:
print("Tendou: I am the one who walks the path to heaven.")
if self.name == "Groh" and self.is_alive() == True:
print("Groh: Target eliminated. Moving on to next assignment.")
if self.name == "Dimitri" and self.is_alive() == True:
print("Dimitri: These hands are stained red once again.")
if self.name == "Orochi" and self.is_alive() == True:
print("Orochi: Pathetic...I long for a real challenge...")
def create_hero(self):
# Name your hero
print("Welcome! Let's create a hero.")
print("First, we need a name.")
print("Enter your hero's name:")
hero_name = input()
print("Okay, your hero's name is {0}.".format(hero_name))
print("Now, choose a class for {0}.".format(hero_name))
# Choose your class (There are default classes, but user can put any string they want.)
print("Your class choices are:")
print("1) Warrior, 2) Mage, 3) Thief")
print("Choose your class.")
hero_class = input()
# Default classes will have extra text, but any other strings are accepted but will not have a description.
if hero_class == "Warrior":
print("You have chosen the Warrior Class!")
print("You are an armed bruiser that deals nasty damage!")
hero_class = "Warrior"
if hero_class == "Mage":
print("You have chosen the Mage Class!")
print("You are an expert in the arcane arts!")
hero_class = "Mage"
if hero_class == "Thief":
print("You have chosen the Thief Class!")
print("You are a shadow in the night who excells in speed and stealth!")
hero_class = "Thief"
# Creates Custom Hero Object with the custom name given.
custom_hero = Hero("{0}".format(hero_name))
self.name = custom_hero
print("My hero's name is {0}, and is a {1}.\n".format(custom_hero.name, hero_class))
def create_ability(self):
'''Prompt for Ability information.
return Ability with values from user Input
'''
# TODO: This method will allow a user to create an ability.
# Prompt the user for the necessary information to create a new ability object.
# return the new ability object.
print("Now, let's create a starting ability for your hero.")
print("Choose a name for your ability:")
ability_name = input()
# Checks to see if input was an integer
try:
print("How strong is this ability?")
ability_strength = int(input())
except ValueError:
print("Sorry, integers only!")
print("Entering default value...100")
ability_strength = 100
# Adds Ability
self.add_ability(Ability(ability_name, ability_strength))
print("Ability is called {0} and has {1} strength!".format(ability_name, ability_strength))
print("{0} has gained the ability, {1}!\n".format(self.name, ability_name))
def create_weapon(self):
#Creates Custom weapon.
print("Okay, let's make your hero's trusted weapon!")
print("What type of weapon you'd like to forge:")
weapon_type = input()
print("So your weapon is a mighty {0}?".format(weapon_type))
print("Does this weapon have a name?")
weapon_name = input()
print("Your {0}'s name is {1}.".format(weapon_type, weapon_name))
#Checks to make sure input was an integer.
try:
print("Now, how strong is the {0}?".format(weapon_name))
weapon_strength = int(input())
except ValueError:
print("Sorry, integers only!")
print("Entering default value...200")
weapon_strength = 200
self.add_weapon(Weapon(weapon_name, weapon_strength))
print("Your {0} is called {1} and has {2} strength!".format(weapon_type, weapon_name, weapon_strength))
print("Now, your hero needs some protection. Time to forge some armor!\n")
def create_armor(self):
#Creates Custom Armor.
print("Lastly, let's forge some armor for your hero.")
print("What is the name of your armor?")
armor_name: input()
print("So, your armor is known far and wide as {0}.".format(armor_name))
#Checks to make sure input was an integer.
try:
print("How much protection value does {0} give?".format(armor_name))
armor_defense = int(input())
except ValueError:
print("Sorry, integers only!")
print("Entering default value...200")
armor_defense = 200
self.add_armor(Armor(armor_name, armor_defense))
print("Armor named {0} with a defense value of {1} has been forged!".format(armor_name, armor_defense))
print("Bolta would be proud!")
class Team:
def __init__(self, teamname):
''' Initialize your team with its team name
'''
# TODO: Implement this constructor by assigning the name and heroes, which should be an empty list
self.heroes = []
self.teamname = teamname
def remove_hero(self, name):
'''Remove hero from heroes list.
If Hero isn't found return 0.
'''
# TODO: Implement this method to remove the hero from the list given their name.
for hero in self.heroes:
if name == hero.name:
self.heroes.remove(hero)
return 1
return 0
def add_hero(self, hero):
'''Add Hero object to self.heroes.'''
# TODO: Add the Hero object that is passed in to the list of heroes in
# self.heroes
self.heroes.append(hero)
def view_all_heroes(self):
for hero in self.heroes:
print("{0}".format(hero.name))
def revive_heroes(self, health = 5000):
''' Reset all heroes health to starting_health'''
# TODO: This method should reset all heroes health to their
# original starting value.
for hero in self.heroes:
hero.current_health = hero.starting_health
def stats(self):
'''Print team statistics'''
# TODO: This method should print the ratio of kills/deaths for each
# member of the team to the screen.
# This data must be output to the console.
# Hint: Use the information stored in each hero.
for hero in self.heroes:
print("Hero: {0} has died {1} time(s) and has killed {2} foe(s).".format(self.name, self.deaths, self.kills))
def is_alive(self):
if self.current_health < 0:
return False
else:
return True
def randomhero(self):
while True:
hero = random.choice(self.heroes)
if hero.is_alive():
return hero
def team_attack(self, enemy_team):
''' Battle each team against each other.'''
# TODO: Randomly select a living hero from each team and have
# them fight until one or both teams have no surviving heroes.
# Hint: Use the fight method in the Hero class.
print("{0} vs. {1}! Only one shall emerge victorious!".format(my_team.name, enemy_team.name))
while self.is_alive() and enemy_team.is_alive():
my_team_hero = self.randomhero()
enemy_team_hero = enemy_team.randomhero()
my_team_hero.fight(enemy_team_hero)
# Fightin'
damage = self.attack()
opponentdamage = opponent.attack()
opponent.take_damage(damage)
self.take_damage(opponentdamage)
if enemy_team_hero == False:
print("{0} has fallen! {1} is the victor!".format(my_team.name, enemy_team.name))
if my_team_hero.is_alive() == False:
print("{0} has fallen! {1} is the victor!".format(enemy_team.name, my_team.name))
class Arena(Hero, Team):
def __init__(self):
super().__init__(self)
'''Instantiate properties
team_one: None
team_two: None
'''
# TODO: create instance variables named team_one and team_two that
# will hold our teams.
team_one: None
team_two: None
def create_team(self):
team_one_name = input("Please choose a name for your team.\n")
self.team_one = Team(team_one_name)
print("Your team is called {0}".format(team_one_name))
try:
print("How many heroes are on this team?")
number_of_heroes = int(input())
except ValueError:
print("Sorry, integers only!")
print("Now, time to create a hero for your team.")
print("To create a hero, you must also make a starting ability, a weapon, and armor.\n")
self.create_hero()
return self.team_one
def create_enemy_team(self):
print("Now it's time to make your opponent's team.")
team_two_name = input("Please choose a name for the opposing team.\n")
self.team_two = Team(team_two_name)
print("The opposing team is called {0}".format(team_two_name))
try:
print("How many heroes are in {0}?".format(team_two_name))
number_of_heroes2 = int(input())
except ValueError:
print("Sorry, integers only!")
print("Now, time to create heroes for the opposing team.")
print("To create a hero, you must also make a starting ability, a weapon, and armor.\n")
self.create_hero()
return self.team_two
def create_hero(self):
# Name your hero
print("Welcome! Let's create a hero.")
print("First, we need a name.")
print("Enter your hero's name:")
hero_name = input()
print("Okay, your hero's name is {0}.".format(hero_name))
print("Now, choose a class for {0}.".format(hero_name))
# Choose your class (There are default classes, but user can put any string they want.)
print("Your class choices are:")
print("1) Warrior, 2) Mage, 3) Thief")
print("Choose your class.")
hero_class = input()
# Default classes will have extra text, but any other strings are accepted but will not have a description.
if hero_class == "Warrior":
print("You have chosen the Warrior Class!")
print("You are an armed bruiser that deals nasty damage!")
hero_class = "Warrior"
if hero_class == "Mage":
print("You have chosen the Mage Class!")
print("You are an expert in the arcane arts!")
hero_class = "Mage"
if hero_class == "Thief":
print("You have chosen the Thief Class!")
print("You are a shadow in the night who excells in speed and stealth!")
hero_class = "Thief"
# Creates Custom Hero Object with the custom name given.
custom_hero = Hero("{0}".format(hero_name))
self.name = custom_hero.name
print("My hero's name is {0}, and is a {1}.\n".format(custom_hero.name, hero_class))
self.create_ability()
def create_ability(self):
'''Prompt for Ability information.
return Ability with values from user Input
'''
# TODO: This method will allow a user to create an ability.
# Prompt the user for the necessary information to create a new ability object.
# return the new ability object.
print("Now, let's create a starting ability for your hero.")
print("Choose a name for your ability:")
ability_name = input()
# Checks to see if input was an integer
try:
print("How strong is this ability?")
ability_strength = int(input())
except ValueError:
print("Sorry, integers only!")
print("Entering default value...100")
ability_strength = 100
# Adds Ability
self.add_ability(Ability(ability_name, ability_strength))
print("Ability is called {0} and has {1} strength!".format(ability_name, ability_strength))
print("{0} has gained the ability, {1}!\n".format(self.name, ability_name))
self.create_weapon()
def create_weapon(self):
#Creates Custom weapon.
print("Okay, let's make your hero's trusted weapon!")
print("What type of weapon you'd like to forge:")
weapon_type = input()
print("So your weapon is a mighty {0}?".format(weapon_type))
print("Does this weapon have a name?")
weapon_name = input()
print("Your {0}'s name is {1}.".format(weapon_type, weapon_name))
#Checks to make sure input was an integer.
try:
print("Now, how strong is the {0}?".format(weapon_name))
weapon_strength = int(input())
except ValueError:
print("Sorry, integers only!")
print("Entering default value...200")
weapon_strength = 200
self.add_weapon(Weapon(weapon_name, weapon_strength))
print("Your {0} is called {1} and has {2} strength!".format(weapon_type, weapon_name, weapon_strength))
print("Now, your hero needs some protection. Time to forge some armor!\n")
self.create_armor()
def create_armor(self):
#Creates Custom Armor.
# Default Settings
customarmor_name = "Default"
customarmor_defense = 200
print("Lastly, let's forge some armor for your hero.")
print("What is the name of your armor?")
customarmor_name = input()
print("So, your armor is known far and wide as {0}.".format(customarmor_name))
#Checks to make sure input was an integer.
try:
print("How much protection value does {0} give?".format(customarmor_name))
customarmor_defense = int(input())
except ValueError:
print("Sorry, integers only!")
print("Entering default value...200")
customarmor_defense = 200
self.add_armor(Armor(customarmor_name, customarmor_defense))
print("Armor named {0} with a defense value of {1} has been forged!".format(customarmor_name, customarmor_defense))
print("Bolta would be proud!\n")
user_input = input("Alright, did you want to make another hero? Or are you ready to battle? Choose Battle, Create hero or Create Enemy Team.\n")
user_input = user_input.lower()
if user_input == "create hero":
self.create_hero()
if user_input == "Create Enemy Team":
self.create_enemy_team()
if user_input == "Battle":
self.arena_battle(team_two)
def team_battle(self, opponent):
''' Battle each team against each other.'''
# TODO: Randomly select a living hero from each team and have
# them fight until one or both teams have no surviving heroes.
# Hint: Use the fight method in the Hero class.
team_one_name = "My Team"
team_two_name = "Opposing Team"
team_one = Team("My Team")
team_two = Team("Opposing Team")
test_hero1 = Hero("Masamune Date")
test_hero2 = Hero("Yukimura Sanada")
team_one.add_hero(test_hero2)
team_two.add_hero(test_hero1)
print("{0} vs. {1}! Only one shall emerge victorious!".format(team_one_name, team_two_name))
while team_one_name.is_alive() and team_two_name.is_alive():
my_team_hero = self.randomhero()
enemy_team_hero = enemy_team.randomhero()
my_team_hero.fight(enemy_team_hero)
# Fightin'
damage = self.attack()
opponentdamage = opponent.attack()
opponent.take_damage(damage)
self.take_damage(opponentdamage)
if enemy_team_hero == False:
print("{0} has fallen! {1} is the victor!".format(self.name, my_hero4.name))
if my_team_hero.is_alive() == False:
print("{0} has fallen! {1} is the victor!".format(self.name, my_hero4.name))
def show_stats(self):
'''Print team statistics'''
# TODO: This method should print the ratio of kills/deaths for each
# member of the team to the screen.
# This data must be output to the console.
# Hint: Use the information stored in each hero.
for hero in self.heroes:
print("Hero: {0} has died {1} time(s) and has killed {2} foe(s).".format(self.name, self.deaths, self.kills))
if __name__ == "__main__":
game_is_running = True
# If you run this file from the terminal
# this block is executed.
# My Data
# Weapons
weapondouble = Weapon("CycloneJoker Double Blades",100)
weaponkiva = Weapon("Zanbat Blade", 100)
weaponkabuto = Weapon("Kabuto Kunai", 100)
weapongroh = Weapon("Aerondight Replica", 100)
weapondimitri = Weapon("Areadbhar", 100)
weaponorochi = Weapon("Serpent King's Scythe", 100)
# Abilities
ability = Ability("Double Boiled Extreme", 350)
ability2 = Ability("Flame Maximum Drive", 200)
ability3 = Ability("Wake up Fever!", 350)
ability4 = Ability("Break the Chain", 200)
ability5 = Ability("Clock up", 200)
ability6 = Ability("Hyper Kick", 350)
ability7 = Ability("Chevalier Mal Fet", 200)
ability8 = Ability("Super Chevalier Mal Fet", 350)
ability9 = Ability("Atrocity", 350)
ability10 = Ability("Vengeance of the King", 200)
# Armor
armor = Armor("Cyclone", 200)
armor2 = Armor("Joker", 200)
armor3 = Armor("Emperor's Garb", 200)
shield = Armor("Emperor's Shield", 200)
armor4 = Armor("ZECT Kabuto Armor", 200)
armor5 = Armor("ZECT Kabuto Cast", 200)
armor6 = Armor("Midnight Purge Uniform", 200)
gauntlet = Armor("Limiter Gauntlet", 200)
charm = Armor("Minerva's Ward", 15)
armor7 = Armor("Fallen King's Armor", 200)
armor8 = Armor("Lion's Cape", 200)
armor9 = Armor("Serpent King's Garb", 200)
shield2 = Armor("Aegis", 200)
charm2 = Armor("Ouroboros Bracelet", 15)
# Teams
my_team = Team("Rider War")
enemy_team = Team("Strike Force")
# Team Rider War
# Double
my_hero = Hero("Double")
my_hero.add_weapon(weapondouble)
my_hero.add_armor(armor)
my_hero.add_armor(armor2)
my_hero.add_ability(ability)
my_hero.add_ability(ability2)
# Kiva
my_hero2 = Hero("Kiva")
my_hero2.add_weapon(weaponkiva)
my_hero2.add_armor(armor3)
my_hero2.add_armor(shield)
my_hero2.add_ability(ability3)
my_hero2.add_ability(ability4)
# Kabuto
my_hero3 = Hero("Kabuto")
my_hero3.add_weapon(weaponkabuto)
my_hero3.add_armor(armor4)
my_hero3.add_armor(armor5)
my_hero3.add_ability(ability5)
my_hero3.add_ability(ability6)
# Team Strike Force
# Groh
my_hero4 = Hero("Groh")
my_hero4.add_weapon(weapongroh)
my_hero4.add_armor(armor6)
my_hero4.add_armor(gauntlet)
my_hero4.add_armor(charm)
my_hero4.add_ability(ability7)
my_hero4.add_ability(ability8)
# Dimitri
my_hero5 = Hero("Dimitri")
my_hero5.add_weapon(weapondimitri)
my_hero5.add_armor(armor7)
my_hero5.add_armor(armor8)
my_hero5.add_ability(ability9)
my_hero5.add_ability(ability10)
# Orochi
my_hero6 = Hero("Orochi")
my_hero6.add_weapon(weaponorochi)
my_hero6.add_armor(armor9)
my_hero6.add_armor(shield2)
my_hero6.add_armor(charm2)
# Default Hero
default = Hero("Default")
# Begin Game
arena = Arena()
arena.create_team()
arena.create_enemy_team()
# Test Battle (Since Creation process is lengthy!)
my_hero.fight(my_hero2)
while game_is_running:
my_hero.fight(my_hero4)
play_again = input("Would you like to play again?\n")
#Check for player Input
if play_again.lower() == "No":
game_is_running = False
else:
arena.team_one.revive_heroes()
arena.team_two.revive_heroes()
|
valor_1 = 100
valor_2 = 14
#Soma
valor_soma = valor_1 + valor_2
print('O valor da soma eh ', valor_soma)
#Subtração
valor_sub = valor_1 - valor_2
print('O valor da subtração eh ', valor_sub)
#Divisão
valor_div = valor_1 - valor_2
print('O valor da divisão eh ', valor_div)
#Multiplicação
valor_mult = valor_1 * valor_2
print('O valor da multiplicação eh ', valor_mult)
#Exponenciação
valor_expo = valor_1 ** valor_2
print('O valor da exponenciação eh ', valor_expo)
#Resto da divisão por 2
valor_resto = valor_1 % 2
if(valor_resto == 0):
print(valor_1, 'eh par!')
else:
print(valor_1, 'eh impar!') |
import exceptions
import os
class FileNotFound(Exception):
def __init__(self,val):
self.val = val
def __str__(self):
return repr(self.val)
class ReadMonthlyMass:
##
# Initialize the monthly mass constructor
# @param filename Filename for the monthly mass file to read
def __init__(self, filename):
self.filename = filename ##< Filename of the monthly mass file
self.topCorner = [9999,-9999] ##< X,Y postion of the top corner point
##
# Reads the data in the monthly mass file
def Read(self):
data = [] ## < Stores file data as a list of lines in the text file
#if the file exists, read it and store information in data.
if os.path.exists(self.filename):
f = open(self.filename,"r")
data = f.readlines()
f.close()
#if it does not exists, throw a FileNotFound Exception
else:
raise FileNotFound("Could not find file " + self.filename)
#Parse the file data and return the result
return self.ParseFile(data)
##
# Parses the data in the file and generates an object with all of the file
# data to return to the caller
# @param data Data contained
def ParseFile(self,data):
dataDict = {}
#for each line in the data file
for line in data:
#Check to see if it is a valid line based on our schema
if self.CheckLine(line) == False:
#line not valid, continue to next line in file
continue
dataDict[str(self.x) + "," + str(self.y)] = self.z
if self.x < self.topCorner[0] and self.y > self.topCorner[1]:
self.topCorner = [self.x,self.y]
return dataDict
##
# Checks the validity of a line from the file
# @param line A line to check
# @return True if the line is valid, false if not valid
def CheckLine(self,line):
tmpData = line.split(" ")
data = []
for x in tmpData:
if x != "":
data.append(x.strip())
try:
if len(data) == 3:
self.x = float(data[0])
self.y = float(data[1])
self.z = float(data[2])
return True
else:
return False
except:
pass
return False
#Testing
if __name__ == "__main__":
testFile = "mass.month.017"
m = ReadMonthlyMass(testFile)
d = m.Read()
assert(d[str(81.500) + "," + str(43.000)] == float("0.39887E+01"))
|
'''Dynamic programming example used for calculating in which order whould we arrange a certain thing example bag'''
def knapsack(val,wt,W,n):
if n==0 or W==0:
return 0
if wt[n-1]>W:
return knapsack(val,wt,W,n-1)
else:
return max(val[n-1]+knapsack(val,wt,W-wt[n-1],n-1),knapsack(val,wt,W,n-1))#return largest value
#dynamic programing with memoization
def knapsack_dp(capacity,values,weights):
l=len(values)
dp=[[0 for col in range(capacity+1)] for row in range(l+1)]
for i in range(1,l+1):
w=weights[i-1]
v=values[i-1]
for j in range(1,capacity+1):
dp[i][j]=dp[i-1][j]
if j>=w and dp[i-1][j-w]+v>dp[i][j]:
dp[i][j]=dp[i-1][j-w]+v
sz=capacity
for i in range(l,0,-1):
if dp[i][sz]!=dp[i-1][sz]:
print("item of value "+str(values[i-1])+" and weigth "+str(weights[i-1])+" taken")
sz=sz-weights[i-1]
return dp[l][capacity]
#start
val=[20,50,100,90,40]#importance of item
wt=[10,20,30,35,40]#weight of items
W=60#total weight
n=len(val)
print(knapsack(val,wt,W,n))
print(knapsack_dp(W,val,wt))
|
arr=[]
top=-1
while(1):
print("choose:")
print("1.push 2.pop 3.top")
ch = int(input())
if(ch==1):
top=top+1
arr.insert(top,int(input("Enter num to push:")))
print("Entered element is:",arr[top])
elif ch==2:
if top == -1:
print("STACK UNDERFLOW")
else:
print("popped element is ",arr[top])
top=top-1
else:
if top ==-1:
print("STACK UNDERFLOW")
else:
print("top element is ",arr[top])
|
import sys
import os
########## WRITING FILE OUT ##########
#open file to write and read
f = open('read_write.txt', 'w+')
for number in range(1, 10):
#write number to file (with a new line)
f.write("{0}\n".format(number))
#create a list of letters to output to our file
letters = ['a', 'b', 'c', 'd', 'e']
for letter in letters:
#write letter to file (with a new line)
f.write("{0}\n".format(letter))
f.seek(0)
for line in f:
print("Line:{0}".format(line))
f.close()
with open("read_write.txt") as f, open("output.txt", "w") as g:
for line in f:
g.write(line)
print("Ciao Monica") |
# https://leetcode.com/problems/longest-palindromic-substring/
# Time out
class Solution:
def longestPalindrome(self, s: str) -> str:
for length in range(len(s), 0, -1):
for start_index in range(len(s) - length + 1):
word = s[start_index : start_index + length]
for index in range(length // 2):
if word[index] != word[-(index + 1)]:
break
else:
return word
ex1 = "wsgdzojcrxtfqcfkhhcuxxnbwtxzkkeunmpdsqfvgfjhusholnwrhmzexhfqppatkexuzdllrbaxygmovqwfvmmbvuuctcwxhrmepxmnxlxdkyzfsqypuroxdczuilbjypnirljxfgpuhhgusflhalorkcvqfknnkqyprxlwmakqszsdqnfovptsgbppvejvukbxaybccxzeqcjhmnexlaafmycwopxntuisxcitxdbarsicvwrvjmxsapmhbbnuivzhkgcrshokkioagwidhmfzjwwywastecjsolxmhfnmgommkoimiwlgwxxdsxhuwwjhpxxgmeuzhdzmuqhmhnfwwokgvwsznfcoxbferdonrexzanpymxtfojodcfydedlxmxeffhwjeegqnagoqlwwdctbqnuxngrgovrjesrkjrfjawknbrsfywljscfvnjhczhyeoyzrtbkvvfvofykkwoiclgxyaddhpdoztdhcbauaagjmfzkkdqexkczfsztckdlujgqzjyuittnudpldjvsbwbzcsazjpxrwfafievenvuetzcxynnmskoytgznvqdlkhaowjtetveahpjguiowkiuvikwewmgxhgfjuzkgrkqhmxxavbriftadtogmhlatczusxkktcsyrnwjbeshifzbykqibghmmvecwwtwdcscikyzyiqlgwzycptlxiwfaigyhrlgtjocvajcnqyenxrnjgogeqtvkxllxpuoxargzgcsfwavwbnktchwjebvwwhfghqkcjhuhuqwcdsixrkfjxuzvhjxlyoxswdlwfytgbtqbeimzzogzrlovcdpseoafuxfmrhdswwictsctawjanvoafvzqanvhaohgndbsxlzuymvfflyswnkvpsvqezekeidadatsymbvgwobdrixisknqpehddjrsntkqpsfxictqbnedjmsveurvrtvpvzbengdijkfcogpcrvwyf"
print(Solution().longestPalindrome(ex1))
|
x=input("Enter the radius of the cirlcle")
area=3.14*r*
print("Area of cirlcle is",area) |
from copy import deepcopy
import board as b
class HumanPlayer:
def __init__(self, black) -> None:
self.black = black
def _get_action_input(self, phase):
pos_1 = None
pos_2 = None
pos_3 = None
if phase == 1:
x_y = input("Enter target x and y:")
x = int(x_y[0])
y = int(x_y[2])
pos_1 = (x,y)
return pos_1
# x_y = input("")
if phase == 2 or phase == 3:
x_y = input("Enter origin x and y:")
x = int(x_y[0])
y = int(x_y[2])
pos_1 = (x,y)
x_y = input("Enter destination x and y:")
x = int(x_y[0])
y = int(x_y[2])
pos_2 = (x,y)
return (pos_1, pos_2)
def _get_mill_input(self):
x_y = input("Enter x and y to capture:")
x = int(x_y[0])
y = int(x_y[2])
pos_1 = (x,y)
return pos_1
def _prompt_and_move_phase1(self, board: "b.Board"):
pos = self._get_action_input(1)
while pos not in b.positions or board.pos_marker_dict[pos] is not None:
print("invalid position")
pos = self._get_action_input(1)
board_copy = deepcopy(board)
board_copy.pos_marker_dict[pos] = b.Marker(self.black, pos)
board_copy.last_move_type = b.ACTION_PLACE
board_copy.last_move_is_black = self.black
if self.black:
board_copy.black_markers_out -= 1
board_copy.black_markers_in += 1
else:
board_copy.white_marker_out -= 1
board_copy.white_markers_in += 1
if board_copy.white_marker_out == 0 and board_copy.black_markers_out == 0:
board_copy.phase = 2
if board_copy.is_mill(pos, self.black):
capt = self._get_mill_input()
while capt not in b.positions or board_copy.pos_marker_dict[capt] is None or board_copy.pos_marker_dict[capt].black == self.black:
print("invalid capture")
capt = self._get_mill_input()
board_copy.pos_marker_dict[capt] = None
if self.black:
board_copy.black_mills += 1
board_copy.white_markers_in -= 1
board_copy.last_move_type = b.ACTION_PLACE_MILL
if board.is_mill(capt, not self.black):
board_copy.white_mills -= 1
else:
board_copy.white_mills += 1
board_copy.black_markers_in -= 1
board_copy.last_move_type = b.ACTION_PLACE_MILL
if board.is_mill(capt, not self.black):
board_copy.black_mills -= 1
return board_copy
def _prompt_and_move_phase2(self, board: "b.Board"):
pos_old, pos_new = self._get_action_input(2)
while pos_old not in b.positions\
or pos_new not in b.positions\
or board.pos_marker_dict[pos_old] is None\
or board.pos_marker_dict[pos_new] is not None\
or board.pos_marker_dict[pos_old].black != self.black\
or pos_new not in b.adjacent_dict[pos_old]:
print("invalid positions")
pos_old, pos_new = self._get_action_input(2)
bcp = deepcopy(board)
bcp.last_move_type = b.ACTION_MOVE
bcp.last_move_is_black = self.black
if bcp.is_mill(pos_old, self.black):
if self.black:
bcp.black_mills -= 1
else:
bcp.white_mills += 1
bcp.pos_marker_dict[pos_old] = None
bcp.pos_marker_dict[pos_new] = b.Marker(self.black, pos_new)
if bcp.is_mill(pos_new, self.black):
capt = self._get_mill_input()
while capt not in b.positions or bcp.pos_marker_dict[capt] is None or bcp.pos_marker_dict[capt].black == self.black:
print("invalid capture")
capt = self._get_mill_input()
bcp.pos_marker_dict[capt] = None
if self.black:
bcp.black_mills += 1
bcp.white_markers_in -= 1
bcp.last_move_type = b.ACTION_MOVE_MILL
if board.is_mill(capt, not self.black):
bcp.white_mills -= 1
else:
bcp.white_mills += 1
bcp.black_markers_in -= 1
bcp.last_move_type = b.ACTION_MOVE_MILL
if board.is_mill(capt, not self.black):
bcp.black_mills -= 1
if bcp.white_markers_in == 3 or bcp.black_markers_in == 3:
bcp.phase = 3
return bcp
def _prompt_and_move_phase3(self, board: "b.Board"):
if self.black and board.black_markers_in > 3:
return self._prompt_and_move_phase2(board)
elif not self.black and board.white_markers_in >3:
return self._prompt_and_move_phase2(board)
pos_old, pos_new = self._get_action_input(3)
while pos_old not in b.positions\
or pos_new not in b.positions\
or board.pos_marker_dict[pos_old] is None\
or board.pos_marker_dict[pos_new] is not None\
or board.pos_marker_dict[pos_old].black != self.black:
print("invalid positions")
pos_old, pos_new = self._get_action_input(3)
bcp = deepcopy(board)
bcp.last_move_type = b.ACTIION_FLY
bcp.last_move_is_black = self.black
if bcp.is_mill(pos_old, self.black):
if self.black:
bcp.black_mills -= 1
else:
bcp.white_mills -= 1
bcp.pos_marker_dict[pos_old] = None
bcp.pos_marker_dict[pos_new] = b.Marker(self.black, pos_new)
if bcp.is_mill(pos_new, self.black):
capt = self._get_mill_input()
while capt not in b.positions or bcp.pos_marker_dict[capt] is None or bcp.pos_marker_dict[capt].black == self.black:
print("invalid capture")
capt = self._get_mill_input()
bcp.pos_marker_dict[capt] = None
if self.black:
bcp.black_mills += 1
bcp.white_markers_in -= 1
bcp.last_move_type = b.ACTION_FLY_MILL
if board.is_mill(capt, not self.black):
bcp.white_mills -= 1
else:
bcp.white_mills += 1
bcp.black_markers_in -= 1
bcp.last_move_type = b.ACTION_FLY_MILL
if board.is_mill(capt, not self.black):
bcp.black_mills -= 1
return bcp
def prompt_and_move(self, board: "b.Board") -> "b.Board":
if board.phase == 1:
return self._prompt_and_move_phase1(board)
elif board.phase == 2:
return self._prompt_and_move_phase2(board)
else:
return self._prompt_and_move_phase3(board) |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Jun 8 21:17:15 2020
@author: dogukan
"""
# %%
# list
liste = [1,2,3,4,5,6]
print (type (liste))
liste_str = ["pazartesi", "sali", "carsamba"]
type(liste_str)
value = liste [1]
print (value)
last_value = liste [-1]
print(last_value)
liste_divide = liste [0:3]
print (liste_divide)
liste.append(7)
liste.remove(7)
liste.reverse ()
liste2= [1,3,5,2,4]
liste2.sort()
string_int_liste = [1,2,3,"a","b"]
# %% tuple
t = (1,2,3,4,4,5,6)
t.count(4)
t.index(3)
# %% dictionary
dictionary = {"ali":32,"veli":45,"mehmet":65}
#ali, veli , metmet = keys
# 32,45,65 = values
def deneme():
dictionary = {"ali":32,"veli":45,"mehmet":65}
return dictionary
dic = deneme ()
# %% conditionals
# if else statement
var1 = 20
var2 = 20
if(var1 > var2):
print ("var1 buyuktur var2"),
elif (var1==var2):
print ("var1 eşittir var2")
else:
print("var1 kucuktur var2")
liste = [1,2,3,4,5,]
value=3
if value in liste:
print ("evet {} degeri listenin icinde".format(value))
else:
print ("hayir yok")
dic = {"ali":32,"veli":45,"mehmet":65}
keys = dic.keys()
print (keys)
if "ali " in keys:
print ("evet")
else:
print("hayır")
# %%
# 1640. yil == 17. yuzyil
# 109. yil == 2.yuzyil
# 2000.yil == 20.yuzyil
# metodyazin
#input integer yillar
#output integer yuzyil
# input = year >> 1 <= year <= 2005
# syntax hatası veriyor!!
def year2century(year):
"""
year to century
"""
str_year = str(year)
if (len(str_year)<3):
return 1
elif (len(str_year) == 3):
if((str_year[1:3]) == "00") # 100,200,300.....
return int (str_year[0])
else: # 190,250,450......
return int (str_year[0])+1
else: # 1750,1700,1805
if((str_year[2:4])=="00"): #1700,1800..
return int(str_year[:2])
else: # 1705,1805,1645
return int( str_year[:2])+1
# %% Loops
# for loop
for each in range (1,11):
print(each)
for each in "ankara ist":
print(each)
for i in "ankara ist".split():
print(i)
liste = [1,3,5,9,5,74,5,34,48534]
sum(liste)
count=0
for i in liste:
print(i)
count = count+i
print(count)
# while loop
i = 0
while(i<4):
print(i)
i=i+1
sinir = len (liste)
i = 0
count=0
while ( i< sinir):
count = count+liste[i]
i=i+1
print(i)
# %%
liste = [1,2,35,458,34,564,-65,-63,-463,46,21]
mini = 1000000
for i in liste:
if (i<mini):
mini=i
else:
continue
print(mini)
|
def update(x):
print(id(x))
x=8
print(id(x))
print("x",x)
a=10
print(id(a))
update(10)
print("a",a)
def update(lst):
print(id(lst))
lst[1]=25
print(id(lst))
print("x",lst)
lst=[10,20,30]
print(id(lst))
update(lst)
print("lst",lst)
|
def fact(n):
f=1
for i in range(1,n+1):
f=f*i
return f
x=4
result =fact(x)
print(result) |
from tkinter import*
from tkinter import ttk
class Ventana(Frame):
def __init__(self, master=None):
super(). __init__(master, width=680,height=260)
self.master = master
self.pack()
self.create_widgets()
def fNuevo(self):
pass
def fModificar(self):
pass
def fEliminar(self):
pass
def fGuardar(self):
pass
def fCancelar(self):
pass
def create_widgets(self):
frame1 = Frame(self, bg="#bfdaff")
frame1.place(x=0, y=0, width=93, height=259)
self.btnNuevo = Button(frame1, text="Nuevo", command=self.fNuevo, bg="blue", fg="white")
self.btnNuevo.place(x=5, y=50, width=80, height=30) #ubicación del boton y tamaño
self.btnModificar = Button(frame1, text="Modificar", command=self.fModificar, bg="blue", fg="white")
self.btnModificar.place(x=5, y=90, width=80, height=30) #ubicación del boton y tamaño
self.btnEliminar = Button(frame1, text="Eliminar", command=self.fEliminar, bg="blue", fg="white")
self.btnEliminar.place(x=5, y=130, width=80, height=30) #ubicación del boton y tamaño
frame2 = Frame(self, bg="#d3dde3")
frame2.place(x=95, y=0, width=150, height=259)
lbl1 = Label(frame2, text="ISO3: ")
lbl1.place(x=3, y=5)
self.txtISO3= Entry(frame2)
self.txtISO3.place(x=3, y=25, width=100, height=20)
lbl2 = Label(frame2, text="Country Name: ")
lbl2.place(x=3, y=55)
self.txtISO3= Entry(frame2)
self.txtISO3.place(x=3, y=75, width=100, height=20)
lbl3 = Label(frame2, text="Capital: ")
lbl3.place(x=3, y=105)
self.txtISO3= Entry(frame2)
self.txtISO3.place(x=3, y=125, width=100, height=20)
lbl4 = Label(frame2, text="Currency Code: ")
lbl4.place(x=3, y=155)
self.txtISO3= Entry(frame2)
self.txtISO3.place(x=3, y=175, width=100, height=20)
self.btnGuardar = Button(frame2, text="Guardar", command=self.fGuardar, bg="green", fg="white")
self.btnGuardar.place(x=10, y=210, width=60, height=30)
self.btnCancelar= Button(frame2, text="Cancelar", command=self.fCancelar, bg="red", fg="white")
self.btnCancelar.place(x=80, y=210, width=60, height=30)
self.grid = ttk.Treeview(self, columns=("col1", "col2", "col3", "col4"))
self.grid.column("#0", width=50)
self.grid.column("col1",width=60, anchor=CENTER)
self.grid.column("col2",width=90, anchor=CENTER)
self.grid.column("col3",width=90, anchor=CENTER)
self.grid.column("col4",width=90, anchor=CENTER)
self.grid.heading("#0", text="Id", anchor=CENTER)
self.grid.heading("col1",text="ISO3", anchor=CENTER)
self.grid.heading("col2",text="Country Name", anchor=CENTER)
self.grid.heading("col3",text="Capital", anchor=CENTER)
self.grid.heading("col4",text="Currency Code", anchor=CENTER)
self.grid.place(x=247, y=0, width=420, height=259)
self.grid.insert("", END, text="1", values=("ARG","Argentina","Buenos Aires","ARS")) |
#Class: CS 4308 Section 01
#Term: Summer 2021
#Name: Ruthana, Jorge, Seth
#Instructor: Deepa Muralidhar
#Project: Deliverable 3 Interpreter - Python
import scanner
import descent_parser
# TODO: 1. Open and Read file
def main():
#scanner now handles file input directly through get_char function
basic_code = "BASIC_Input_File_1.txt"
scan_obj = scanner.Scanner(basic_code)
prse = descent_parser.Parser(scan_obj)
prse.parse()
prse.root.eval()
parse_tree_preorder = prse.display_preorder()
# Big part after this print statement where we will validate tokens and count.
# TODO: 2. Write to existing output file
# After counting we then overwrite the empty output file with a 'count' or whatever we decide to use.
fileOut = open("output.txt", "w")
# Will need a format for the information we will write to the file.
fileOut.write(parse_tree_preorder)
#print("wrote " + str(token) + " to file")
fileOut.close()
if __name__ == "__main__":
main()
|
import json
'''
>wikiのマークアップ早見表
wikiのデータ形式に関することは以下のリンク先に書かれている
https://ja.wikipedia.org/wiki/Help:%E6%97%A9%E8%A6%8B%E8%A1%A8
'''
class Section_3():
#ss1-ss9で利用 jsonを読んでデータを返す
def read_json(self):
f = open('jawiki-country.json','r')
for count,line in enumerate(f):
data_json = json.loads(line)
if data_json['title'] == 'イギリス':
text_data = data_json['text']
break
f.close() #ファイルクローズをお忘れなく
return text_data
#JSONデータの読み込み
#read_jsonとやってることは同じ
def ss0(self):
#jsonファイルは一行ずつ読まないと怒られる...
f = open('jawiki-country.json','r')
for count,line in enumerate(f):
'''
enumerate()はカウントと値を返すので、
for文の引数も"num,line"となる
'''
data_json = json.loads(line)
if data_json['title'] == 'イギリス':
print(data_json['text'])
f.close()
#カテゴリ名を含む行を抽出
def ss1(self):
'''
>[[Category:英連邦王国|*]]
これを抜き出す
'''
import re
#全文データを取得
data = self.read_json()
lines = data.split('\n') #リスト化
pattern = r'\[\[Category:' #正規表現で探す時のパターン
for i in range(len(lines)):
matchOB = re.match(pattern,lines[i])
if matchOB :
print(lines[i])
#カテゴリ名の抽出
def ss2(self):
'''
>[[Category:英連邦王国|*]]
これから、以下のように抜き出す
>英連邦王国|*
'''
import re
#全文データを取得
data = self.read_json()
lines = data.split('\n') #リスト化
pattern1 = r'\[\[Category:' #正規表現で探す時のパターン
pattern2 = r'\S*'
for i in range(len(lines)):
matchOB_1 = re.match(pattern1,lines[i])
if matchOB_1 :
matchOB_2 = re.match(pattern2,lines[i])
if matchOB_2 :
#pattern1のマッチ部分を抜き出す
re_pattern1 = matchOB_1.group()
#いらない部分をreplaceで削除
category_name = matchOB_2.group().replace(re_pattern1,'').replace(']]','')
print(category_name)
#セクション構造
def ss3(self):
import re
data = self.read_json()
lines = data.split('\n')
pattern1 = r'='
print('レベル : セクション名')
for i in range(len(lines)):
matchOB_1 = re.match(pattern1,lines[i])
if matchOB_1 :
#パターンにマッチした全てをリストとして返す,"="がリストに含まれる
matchedlist = re.findall(pattern1,lines[i])
if matchedlist:
#リストをカウントして ÷2
section_num = int(len(matchedlist)/2)
#セクション名のみ抜き出す,リプレイスで空白にして要らない部分を除去
section_name = lines[i].replace(matchOB_1.group(),'')
print(section_num,' : ',section_name)
#ファイル参照の抽出
def ss4(self):
import re
data = self.read_json()
lines = data.split('\n')
#以下の2つのパターンで書かれている,カンマ以下を抜き出したい
pattern_1 = r'\[\[File:' #正規表現パターン
pattern_2 = r'\[\[ファイル:' #正規表現パターン
for i in range(len(lines)):
matchOB_1 = re.match(pattern_1,lines[i])
matchOB_2 = re.match(pattern_2,lines[i])
if matchOB_1 :
#pattern_1分を消去
file_name = lines[i].replace(matchOB_1.group(),'')
#"|"でスプリットしリスト化して、その0要素目を呼び出す
file_name_list = file_name.split('|')
print(file_name_list[0])
elif matchOB_2 :
file_name = lines[i].replace(matchOB_2.group(),'')
file_name_list = file_name.split('|')
print(file_name_list[0])
#テンプレートの抽出
def ss5(self):
import re
data = self.read_json()
lines = data.split('\n')
#テンプレートを使っている行の抜き出し
#()で正規表現のグループ化,コードの可読性を上げるために利用
pattern_1 = r'^\|(\w*)(\s*)=' #正規表現パターン
temp_dic = {}
for i in range(len(lines)):
matchOB_1 = re.findall(pattern_1,lines[i])
if matchOB_1 :
temp = lines[i].replace('|','')
temp_list = temp.split('=',1)
temp_dic[temp_list[0]] = temp_list[1] #辞書に格納完了
print('辞書に格納完了')
for item in temp_dic :
print(item,':',temp_dic[item])
#ss5と同じ動き,最後に辞書を返す
def return_dic_ss5(self):
import re
data = self.read_json()
lines = data.split('\n')
#テンプレートを使っている行の抜き出し
#()で正規表現のグループ化,コードの可読性を上げるために利用
pattern_1 = r'^\|(\w*)(\s*)='
temp_dic = {}
for i in range(len(lines)):
matchOB_1 = re.findall(pattern_1,lines[i])
if matchOB_1 :
temp = lines[i].replace('|','')
temp_list = temp.split('=',1)
temp_dic[temp_list[0]] = temp_list[1] #辞書に格納完了
return temp_dic
#強調マークアップの除去
def ss6(self):
import re
#ss5の処理を行った辞書を受け取る
temp_dic = self.return_dic_ss5()
for item in temp_dic :
temp_dic[item] = temp_dic[item].replace('\'','') #置換
print(item,':',temp_dic[item])
#ss6と同じ動き,最後に辞書を返す
def return_dic_ss6(self):
import re
data = self.read_json()
lines = data.split('\n')
temp_dic = self.return_dic_ss5()
for item in temp_dic :
temp_dic[item] = temp_dic[item].replace('\'','')
return temp_dic
#内部リンクの除去
def ss7(self):
#内部リンクは"[[]]"で覆われている
import re
#ss6の処理を行った辞書を受け取る
temp_dic = self.return_dic_ss6()
pattern_1 =r'\[\[' #正規表現パターン
for item in temp_dic :
matchOB_1 = re.findall(pattern_1,temp_dic[item])
if matchOB_1:
#大括弧を置換
temp_dic[item] = temp_dic[item].replace('[[','').replace(']]','')
print(item,':',temp_dic[item])
#ss7と同じ動き,最後に辞書を返す
def return_dic_ss7(self):
import re
#ss6の処理を行った辞書を受け取る
temp_dic = self.return_dic_ss6()
pattern_1 =r'\[\[' #正規表現パターン
for item in temp_dic :
matchOB_1 = re.findall(pattern_1,temp_dic[item])
if matchOB_1:
#大括弧を置換
temp_dic[item] = temp_dic[item].replace('[[','').replace(']]','')
return temp_dic
#Media Wiki マークアップの除去
def ss8(self):
'''
除去すべきマークアップの例
ex1)公式国名 : {{langenUnited Kingdom of Great Britain and Northern Ireland}}<ref>
ex2)人口値 : 63,181,775<ref>['外部リンク']</ref>
ex3)GDP値MER : 2兆4337億<ref name="imf-statistics-gdp" />
(※)ex3)で除去対象になるURLには'数字'を含むものも存在する
'''
import re
#ss7の処理を行った辞書を受け取る
temp_dic = self.return_dic_ss7()
#正規表現のリスト化
#pattern_list[3]と[4]の順序が逆だと成功しない 消す順序が大事な正規表現
pattern_list = ["{{","}}","<\w*>","<ref[\D*[0-9]*]","<ref\D*","</ref>","\[\D*\]","<br\D*/>"]
for item in temp_dic :
for count in range(len(pattern_list)) :
#re.findallは一致したものをリストで返す
matchOB = re.findall(pattern_list[count],temp_dic[item])
if matchOB :
#print('------ マッチ!! ------',matchOB) #確認用
#一致した内容はmatchOBにリストとして格納されているので、0番目の要素指定で取り出す
temp_dic[item] = temp_dic[item].replace(matchOB[0],'')
print(item,':',temp_dic[item])
'''
!!!! 最初に書いた、'ダメ'なコードだけどわかりやすい !!!!
pattern_1 = r'{{' #ex1)の一部の正規表現
pattern_2 = r'<\w*>' #<ref>を見つける正規表現
pattern_3 = r'<ref[\D*|[0-9]*]|<ref\D*|</ref>' #ex2)とex3)の正規表現 #3つの正規表現
pattern_4 = r'\[\D*\]'
pattern_5 = r'<br\D*/>' #"<br />"の正規表現
for item in temp_dic :
#パターン1の置換作業
matchOB_1 = re.findall(pattern_1,temp_dic[item])
if matchOB_1:
temp_dic[item] = temp_dic[item].replace('{{','').replace('}}','')
#print('----- matchOB_1を実行 -----',matchOB_1)
#パターン2の置換作業
matchOB_2 = re.findall(pattern_2,temp_dic[item])
if matchOB_2:
temp_dic[item] = temp_dic[item].replace(matchOB_2[0],'')
#print('----- matchOB_2を実行 -----',matchOB_2)
#パターン3の置換作業
matchOB_3 = re.findall(pattern_3,temp_dic[item])
if matchOB_3:
#パターン3のみ複数の正規表現をまとめたので、for文でmatchOB_3リスト分を置換する
for i in range(len(matchOB_3)):
temp_dic[item] = temp_dic[item].replace(matchOB_3[i],'')
#print('----- matchOB_3を実行 -----',matchOB_3)
#パターン4の置換作業
matchOB_4 = re.findall(pattern_4,temp_dic[item])
if matchOB_4:
temp_dic[item] = temp_dic[item].replace(matchOB_4[0],'')
#print('----- matchOB_4を実行 -----',matchOB_4)
matchOB_5 = re.findall(pattern_5,temp_dic[item])
if matchOB_5:
temp_dic[item] = temp_dic[item].replace(matchOB_5[0],'')
#print('----- matchOB_5を実行 -----',matchOB_5)
print(item,':',temp_dic[item])
'''
#ss8と同じ動き,最後に辞書を返す
def return_dic_ss8(self):
import re
#ss7の処理を行った辞書を受け取る
temp_dic = self.return_dic_ss7()
#正規表現のリスト化
#pattern_list[3]と[4]の順序が逆だと成功しない 消す順序が大事な正規表現
pattern_list = ["{{","}}","<\w*>","<ref[\D*[0-9]*]","<ref\D*","</ref>","\[\D*\]","<br\D*/>"]
for item in temp_dic :
for count in range(len(pattern_list)) :
#re.findallは一致したものをリストで返す
matchOB = re.findall(pattern_list[count],temp_dic[item])
if matchOB :
#print('------ マッチ!! ------',matchOB) #確認用
#一致した内容はmatchOBにリストとして格納されているので、0番目の要素指定で取り出す
temp_dic[item] = temp_dic[item].replace(matchOB[0],'')
return temp_dic
#国旗画像のURLを取得する
def ss9(self):
import re
import requests
import json
temp_dic = self.return_dic_ss8()
#APIエンドポイント
url = 'https://www.mediawiki.org/w/api.php'
payload = {'action':'query',
'titles':'File:{}'.format(temp_dic['国旗画像 ']),
'prop' :'imageinfo',
'format':'json',
'iiprop':'url'}
ans_r_json = requests.get(url, params=payload).json()
print(ans_r_json['query']['pages']['-1']['imageinfo'][0]['url'])
num = input('サブセクション番号入力:')
do = Section_3()
ss_num = 'ss' + str(num)
eval('do.' + ss_num + '()') #入力した数字の関数を実行
|
import numpy as np
import plotly.graph_objects as go
import pandas as pd
from sklearn.linear_model import LinearRegression
pd.options.plotting.backend = "plotly"
def get_best_fit(data, verbose=False):
'''
Gets a curve of best fit with the given data. It is assumed that
companies generally increase their dividend every period over time.
From this assumption the data is fitted to an exponential curve.
'''
X = (data.index - data.index[0]).days # NOTE: Compounding period is in days
Y = np.log(data.Dividends)
X = np.array(X).reshape(-1,1) # Regressor requires data to be '2-D'
Y = np.array(Y).reshape(-1,1) # That is, it likes to see one column and
# many rows.
linear_regressor = LinearRegression()
linear_regressor.fit(X, Y)
Y_pred = linear_regressor.predict(X)
Y_pred = np.exp(Y_pred)
Y_pred = Y_pred.flatten() # plotly doesn't like dealing with a list of lists
if verbose:
print(f'Best Fit Equation: Y_pred = {np.exp(linear_regressor.intercept_)}exp({linear_regressor.coef_}X)')
return Y_pred
def get_cagr(begin_value, end_value, num_years):
'''
Calculate the cumulative annual growth rate
'''
return pow((end_value/begin_value), (1/num_years)) - 1
def analyze(data):
'''
Analyzes the dividend history of the given company.
Some metrics
- Forward dividend
- Trailing dividend
- Period of growth (monotonically increasing)
'''
# Check that the data looks right
data.info()
print(data.head())
# Calculate best fit curves.
domains = [['Jan 2015', 'Jan 2021'],
['Mar 1995', 'Mar 2001'],
['Sep 2003', 'Oct 2008']]
X = []
Y_pred = []
for domain in domains:
X.append(data[domain[0]:domain[1]].index)
Y_pred.append(get_best_fit(data[domain[0]:domain[1]]))
# Calculate the annual growth rate
# growth=get_cagr(data.loc['Jan 2020'].values[0], data.loc['Jan 2021'].values[0], 1)
# print(f'Cumulative Annual Growth Rate: {growth*100} percent')
# Plot the data.
fig = go.Figure()
# fig.update_yaxes(type='log')
fig.add_trace(go.Scatter(x=data.index, y=data.Dividends, mode='markers', name='Dividends (dB)'))
for i in range(len(Y_pred)):
fig.add_trace(go.Scatter(x=X[i], y=Y_pred[i], mode='lines', name=f'fit{i}'))
fig.show() |
filename = "input.txt"
file = open(filename)
#read in the lines
passwords = []
line = file.readline()
while line:
passwords.append(line)
line = file.readline()
#do the thing: scrape
counter = 0
for full_line in passwords:
rule, password = full_line.replace(" ","").split(":")
okay_index = int(rule.split("-")[0]) - 1
buf = rule.split("-")[1]
bad_index = int(''.join([i for i in buf if i.isdigit()]))-1
char = ''.join([i for i in buf if not i.isdigit()])
#print("{} is char_min\n{} is charmax\n{}ischar".format(char_min,char_max, char))
if ((password[okay_index]==char and password[bad_index] != char) or (password[okay_index]!=char and password[bad_index] == char)):
counter= counter+1
print("{} is counter".format(counter))
|
# 2. Реализовать класс Road (дорога).
# определить атрибуты: length (длина), width (ширина);
# значения атрибутов должны передаваться при создании экземпляра класса;
# атрибуты сделать защищёнными;
# определить метод расчёта массы асфальта, необходимого для покрытия всей дороги;
# использовать формулу: длина * ширина * масса асфальта для покрытия одного кв. метра дороги асфальтом,
# толщиной в 1 см *
# число см толщины полотна;
# проверить работу метода.
# Например: 20 м*5000 м*25 кг*5 см = 12500 т.
class Road:
length = None
width = None
weigth = None
tickness = None
def __init__(self, length, width):
self.length = length
self.width = width
print('Creat road_to_village object')
def intake(self):
self.weigth = 25
self.tickness = 0.05
intake = self.length * self.width * self.weigth * self.tickness / 1000
print(f'Need {intake} ton for the building')
road_to_village = Road(20000, 6)
road_to_village.intake()
|
from math import pi, e, factorial, sqrt, pow
import math as mt
def constante(exp):
#esta funcao substitui as funcoes em numeros para utilizar no calculo
exp = exp
if "π" in exp:
exp = exp.replace("π", str(pi))
if "e" in exp:
exp = exp.replace("e", str(e))
return exp
def fatorial(exp):
exp = str(exp)
while "!" in exp:
#vai verificar a existencia de fatorial e repetir os processos para cada
local = exp.find("!")
#vai verificar o local da primeira fatorial
lista_exp = list(exp)
#transforma a exp em uma lista para ser modificada.
lista_exp.pop(local)
#vai apagar a fatorial
c = 1 #define o contador
value = "" #define a variável temporária que vai sofrer modificações
while True:
#aqui vai pegar os números e armazená-los em value para serem calculados
try:
#vai ser tratado erros como os de range
if lista_exp[local-c].isnumeric() and local-c > -1:
#verifica se o elemento da lista é um número e se corresponde ao range da esquerda pra a direita
value += str(lista_exp[local-c]) #caso verdade ele é atribuido ao value para ser calculado a fatorial
lista_exp.pop(local-c) #o número é apagado para ser substituído depois pelo valor da fatorial
pos = local-c #é salvo a posição do último número para ser innserido nesse espaço
c += 1 #aqui soma o contador
else:
break
#caso não seja um número ou esteja voltando a lista, ele encerra
except Exception:
#caso exista um erro, ele para a executação
break
value = value[::-1] #inversão do value
lista_exp.insert(pos,str(factorial(float(value)))) #calcula e insere a fatorial do value
exp = "".join(lista_exp) #atribui os resultados à expressão
return exp #retorna a expressão já com os resultados calculados
def raiz(exp):
#esta funcao resolve raizes
exp = str(exp)
while "√" in exp:
#verifica a existencia de raizes e faz um looping para repetir o processo para cada raiz.
local = exp.find("√")
#vai verificar o local da primeira raiz
lista_exp = list(exp)
#transforma a exp em uma lista para ser modificada.
lista_exp.pop(local)
#vai apagar a raiz
value = "" #define a variável temporária que vai sofrer modificações
#aqui detecta o fator de multiplicação
c = 1 #cria o contador
tmp = "" #cria a var tmp que vai conter o fator
while True: #cria um looping para pegaar todos os números
try:
if lista_exp[local-c].isnumeric() and local-c > -1:#verifica se o item da lista é um número e sua posição
tmp += lista_exp[local-c] #atribui a tmp
lista_exp[local-c] = ""#aqui vai substituir o valor, mas não vai mudar as casas
else:
break #para quando não é um número ou está voltando
except Exception: #interrope caso haja um erro
break
#aqui verifica se tmp tem valor senão é atribuído 1 para multiplicar
if tmp != "":
tmp = float(tmp[::-1]) #inverte a var
else:
tmp = 1
while True:
#aqui vai pegar os números e armazená-los em value para serem calculados
try:
#vai ser tratado erros como os de range
if lista_exp[local].isnumeric():
#verifica se o elemento da lista é um número e se corresponde ao range da esquerda pra a direita
value += str(lista_exp[local]) #caso verdade ele é atribuido ao value para ser calculado a fatorial
lista_exp.pop(local) #o número é apagado para ser substituído depois pelo valor da fatorial
pos = local #é salvo a posição do último número para ser innserido nesse espaço
else:
break
#caso não seja um número ou esteja voltando a lista, ele encerra
except Exception:
#caso exista um erro, ele para a executação
break
value = sqrt(float(value))
lista_exp.insert(pos,str(tmp*value)) #calcula e insere a fatorial do value
exp = "".join(lista_exp) #atribui os resultados à expressão
return exp #retorna a expressão já com os resultados calculados
#EXPRESSÕES TRIGONOMÉTRICAS
def sin(val):
mode = globals()["mode"] #busca mode que foi definida em resolve()
#verifica se está em graus, caso contrário, apenas calcula o seno
if mode[5:8] == "Deg":
tmp = mt.sin(mt.radians(float(val))) #calcula o sin
tmp = "{:.10f}".format(tmp) #arredonda o valor para melhor compreensão
else:
tmp = mt.sin(val)
tmp = f"{tmp:.10f}"
return float(tmp) #retorna tmp em float para retirar o zeros das casas decimais.
def cos(val):
mode = globals()["mode"] #busca mode que foi definida em resolve()
#verifica se está em graus, caso contrário, apenas calcula o cosseno
if mode[5:8] == "Deg":
tmp = mt.cos(mt.radians(float(val))) #calcula o cos
tmp = "{:.10f}".format(tmp) #arredonda o valor para melhor compreensão
else:
tmp = mt.cos(val)
tmp = f"{tmp:.10f}"
return float(tmp) #retorna tmp em float para retirar o zeros das casas decimais.
def tan(val):
mode = globals()["mode"] #busca mode que foi definida em resolve()
#verifica se está em graus, caso contrário, apenas calcula o cosseno
if mode[5:8] == "Deg":
tmp = mt.tan(mt.radians(float(val))) #calcula o cos
tmp = "{:.10f}".format(tmp) #arredonda o valor para melhor compreensão
else:
tmp = mt.tan(val)
tmp = f"{tmp:.10f}"
return float(tmp) #retorna tmp em float para retirar o zeros das casas decimais.
#FIM EXPRESSÕES TRIGONOMÉTRICAS
def potencia(exp):
exp = str(exp)
while "^" in exp: #verifica a existencia de potencias
local = exp.find("^") #localiza a primeira ocorrência de potencia
lista_exp = list(exp)
lista_exp.pop(local) #apaga a ^
lista_exp.pop(local) #apaga o parênteses
expoente = ""
base = ""
while True: #pega o expoente
if lista_exp[local] != ")":
expoente += lista_exp[local]
lista_exp.pop(local)
else:
lista_exp.pop(local)
break
c = 1 #define o contador
while True: #pega a base
try:
if lista_exp[local-c].isnumeric() and local-c > -1:
base += lista_exp[local-c]
lista_exp.pop(local-c)
pos = local-c #marca a posicao do ultimo
c += 1
else:
break
except Exception:
break
base = base[::-1] #inversao da base
x = str(pow(float(base), float(expoente)))
lista_exp.insert(pos, x)
exp = "".join(lista_exp)
return exp
def resolve(expressao, mode):
#define mode como uma variável global para ser usada nas expressões trignométricas
globals()["mode"] = mode
mode = mode
try:
expressao = expressao
expressao = constante(expressao)
expressao = fatorial(expressao)
expressao = raiz(expressao)
expressao = potencia(expressao)
valor = str(eval(expressao))
return valor
except ArithmeticError:
return "Erro matemático"
except Exception:
return "Erro de síntaxe"
|
import random
WORDS = ("terorysta","marchewka", "smaczne", "koronawirus", "mercedes")
word = random.choice(WORDS)
correct = word
jumble = ""
while word:
position = random.randrange(len(word))
jumble += word[position]
word = word[:position] + word[(position + 1):]
print("Witaj w grze")
print("zgadnij jakie to slowo", jumble)
guess = input("\n Twoja odpowiedz")
while guess != correct and guess != "":
print("Niestety to nie to slowo")
guess = input("\n Twoja odpowiedz :")
if guess == correct:
print("Gratulacje")
print("Game over")
|
def enter_radius():
radius = input("Enter value for radius: ")
return eval(radius)
def calc_area(radius):
pi = 3.14159
area = 2 * pi * (radius * radius)
return print("Area: " + area)
calc_area(enter_radius())
|
sum = 0
for i in range(1, 21):
if i % 2 == 0 or i % 3 == 0:
sum += i
print(sum)
|
for i in range(1, 31):
print("{:3d}".format(i), end=" ")
if i % 7 == 0:
print()
|
import math
print("{0:<10} {1:<10} {2:<10}".format("degree", "sin", "cos"))
for i in range(0, 370, 10):
print("{0:<10} {1:<10.4f} {2:<10.4f}".format(i, math.sin(math.radians(i)), math.cos(math.radians(i))))
|
number = 1000
count = 0
for i in range(1, number):
if i % 2 == 0 or i % 3 == 0 and i != 2:
print(i, "is not prime")
elif i == 2:
print(i, "is prime")
count += 1
else:
print(i, "is prime")
count += 1
print("Number of primes", count)
|
import turtle1
angle = 90
d = 5
turtle1.speed(1000)
for i in range(300):
turtle1.forward(d)
turtle1.right(angle)
turtle1.circle(30)
d += 2
turtle1.done() |
import time
# for i in range(9, 0, -1):
# time.sleep(1)
# print(i)
# print("Boom")
factor = 1
for step in range(3):
for i in range(9, 0, -1):
print(factor * i)
time.sleep(0.5)
factor *= 0.1
print("Boom")
|
"""
Creates new set of books based on user's query.
Function is called in route: add_books with POST method.
"""
import requests
from datetime import datetime
from flask_sqlalchemy import SQLAlchemy
def get_new_books(book, link: str, db: SQLAlchemy) -> None:
"""
Passes the query to the Google Book API, retrieves the necessary parameters spiecified in book detial section.
So many try-except are used, due to the incompleteness of the data received from the API.
:param book: A Book model, which is used in DB.
:param link: Link used with GET method to pass query to Google Book API.
:param db: SQLAlchemy DataBase.
:return: None.
"""
lib_data = requests.get(link).json()['items']
for item in lib_data:
new_authors = ""
new_category = ""
new_title = item['volumeInfo']['title']
try:
for author in item['volumeInfo']['authors']:
new_authors = new_authors + ',' + author
new_authors = new_authors[1:]
except KeyError:
new_authors = ""
try:
new_date = datetime.strptime(item['volumeInfo']['publishedDate'], '%Y-%m-%d').date()
new_date_disp = 'd'
except ValueError:
try:
new_date = datetime.strptime(item['volumeInfo']['publishedDate'], '%Y-%m').date()
new_date_disp = 'm'
except ValueError:
new_date = datetime.strptime(item['volumeInfo']['publishedDate'], '%Y').date()
new_date_disp = 'y'
try:
for category in item['volumeInfo']['categories']:
new_category = new_category + category
except KeyError:
new_category = ""
try:
new_avg_rating = item['volumeInfo']['averageRating']
except KeyError:
new_avg_rating = 0
try:
new_rating_count = item['volumeInfo']['ratingsCount']
except KeyError:
new_rating_count = 0
try:
new_thumbnail = item['volumeInfo']['imageLinks']['thumbnail']
except KeyError:
new_thumbnail = ""
new_book = book(
title=new_title,
authors=new_authors,
published_date=new_date,
date_to_disp=new_date_disp,
categories=new_category,
average_rating=new_avg_rating,
ratings_count=new_rating_count,
thumbnail=new_thumbnail
)
book_exists = book.query.filter_by(title=new_title, authors=new_authors).first()
if book_exists:
setattr(book_exists, 'title', new_book.title)
setattr(book_exists, 'authors', new_book.authors)
setattr(book_exists, 'published_date', new_book.published_date)
setattr(book_exists, 'categories', new_book.categories)
setattr(book_exists, 'average_rating', new_book.average_rating)
setattr(book_exists, 'ratings_count', new_book.ratings_count)
setattr(book_exists, 'thumbnail', new_book.thumbnail)
db.session.commit()
else:
db.session.add(new_book)
db.session.commit()
|
import MyResources
import random
import MyEvents
class Ship:
def __init__(self):
self.Gold = 0
self.ShipHpBeg = 0
self.ShipHp = 0
self.CrewHpBeg = 0
self.CrewHp = 0
self.Fame = 0
self.Infamy = 0
self.Happiness = 0
self.Wealth = 0
self.Crew = []
self.Resources = MyResources.Resources()
self.EventTyp = "N"
self.mess = "N"
def dodailyevent(self, a_mench):
evech = 0
evech = random.randint(1, 4)
if self.EventTyp == "N" and evech == 1:
typofsh = random.randint(1,3)
if typofsh == 1:
self.EventTyp = "shcomcar"
if typofsh == 2:
self.EventTyp = "shcompir"
if self.EventTyp == "shcomcar":
self.shcomcargo()
if self.EventTyp == "attcargo":
self.attshcargo(a_mench)
def shcomcargo(self, a_ch):
self.mess = "Look! It seems like a ship is approaching"
self.mess += "It's a cargo ship! What should we do Captain?"
if a_ch == "ATTCARGO":
self.EventTyp ="attcargo"
self.attshcargo()
if a_ch == "IGNCARGO":
self.EventTyp ="igncargo"
self.attshcargo()
def shcompir(self):
self.mess = "Oh it's a pirate ship!"
self.mess += "Other pirates on the sea are pretty tricky, how would you like to handle the encounter"
if a_ch == "ATTPIR":
self.EventTyp ="attpir"
self.attshpir()
def attshcargo(self, a_ch):
redunum = random.randint(0, 2)
self.CrewHp -= redunum
self.mess = "The life of the Pirate is crowned by the menace generated on the innocents of the sea."
self.mess += "You attacked the cargo ship!"
self.mess += "Now that the ship is disabled what would you like to do?"
if a_ch == "OB":
self.shipeventob()
if a_ch == "LT":
self.shipeventltnonnavy()
def attshpir(self):
redunum = random.randint(0, 5)
def shipeventob(self):
messap1 = "No Mercy! You destroyed all in site, sparing no one and nothing."
messap2 = "The breeze of the sea blows with the deafening silence after the cries of your victims!"
messap3 = "Your name will ring around the globe for your destructive force"
self.Fame += 50
self.Infamy += 60
def shipeventltnonnavy(self):
mess = "You ravaged the goods of your enemy taking them for spoil"
num = random.randint(1, 100)
self.Wealth += num
self.Fame += .80 * num
self.Resources.Ammunition += .25 * num
self.Resources.Medicine += .25 * num
def shipeventltnavy(self):
mess = "A pirate defeating the navy! Quite an unusual feat, and a juicy loot at that"
num = random.randint(1, 100)
self.Wealth += 2.5 * num
self.Fame += 1.75 * num
self.Resources.Ammunition += 1.25 * num
self.Resources.Ammunition += .50 * num
self.Resources.Medicine += .25 * num
def shipeventafterlt(self, a_ch):
mess += "The enemy is at your mercy, what would you have done to them?"
if a_ch == "MRCY":
mess = "You took their goods but spared their lives, some call it marcy others maybe not"
if a_ch == "OB":
self.shipeventob()
def ignshcargo(self):
self.mess = "You have ignored a ship perhaps tomorrow might be a better time for a good loot"
def addcrewmem(self, a_mem):
self.Crew.append(a_mem)
|
"""
Anagram functions
Algorithms with different orders of magnitude
"""
import unittest
from collections import OrderedDict
def anagram_first(first, second):
"""
Strategy: Tick off
"""
if first == second:
return True
if not len(first) == len(second):
return False
for char in first:
if char in second:
second = second.replace(char, '-', 1)
first = first.replace(char, '-', 1)
def is_hyphens(a_str):
return all(map(lambda x: x == '-', a_str))
if is_hyphens(first) and is_hyphens(second):
return True
else:
return False
def anagram_tick_off(first, second):
first = [char for char in first]
idx = 0
ok = True
while idx < len(first) and ok:
jdx = 0
found = False
while jdx < len(second) and not found:
if first[idx] == second[jdx]:
found = True
else:
jdx += 1
if not found:
ok = False
idx += 1
return ok
def anagram_sort_and_compare(first, second):
if first == second:
return True
if not len(first) == len(second):
return False
first = list(first)
second = list(second)
first.sort()
second.sort()
for char_a, char_b in zip(first, second):
if not char_a == char_b:
return False
return True
def anagram_count_and_compare_first(first, second):
# sacrifice space for time
if first == second:
return True
if not len(first) == len(second):
return False
def count_chars(string):
res = OrderedDict()
for char in first:
if char in res:
res[char] += 1
else:
res[char] = 1
return res
first_res = count_chars(first)
second_res = count_chars(second)
for count_one, count_two in zip(first_res.values(), second_res.values()):
if not count_one == count_two:
return False
return True
def anagram_count_and_compare(first, second):
# init letter counts
letter_count_a = [0]*26
letter_count_b = [0]*26
for char in first:
idx = ord(char) - ord('a')
current = letter_count_a[idx]
letter_count_a[idx] = current + 1
for char in second:
idx = ord(char) - ord('a')
current = letter_count_b[idx]
letter_count_b[idx] = current + 1
for i in range(26):
if not letter_count_a[i] == letter_count_b[i]:
return False
return True
class TestAnagram(unittest.TestCase):
tests = [
('', '', True), # empty stings
('abc', 'abc', True), # identical strings
('abcd', 'abc', False), # strings of unequal length
('heart', 'earth', True),
('python', 'typhon', True),
('apple', 'pleap', True),
]
@classmethod
def _wrap(cls, anagram_function):
def inner():
for arg1, arg2, res in cls.tests:
got = anagram_function(arg1, arg2)
err_msg = '"{}" "{}" failed, expected "{}"'.format(
arg1, arg2, res
)
assert got == res, err_msg
return inner
def test_anagram_first(self):
self._wrap(anagram_first)()
def test_anagram_tick_off(self):
self._wrap(anagram_tick_off)()
def test_anagram_sort_and_compare(self):
self._wrap(anagram_sort_and_compare)()
def test_anagram_count_and_compare_first(self):
self._wrap(anagram_count_and_compare_first)()
def test_anagram_count_and_compare(self):
self._wrap(anagram_count_and_compare)()
if __name__ == '__main__':
unittest.main()
|
"""
Linked List implementation
run tests:
python3 list.py
"""
import unittest
class Node:
def __init__(self, value):
self.next = None
self.value = value
class LinkedList:
def __init__(self):
self.head = None
def append(self, value):
if self.is_empty():
self.head = Node(value)
else:
cursor = self.head
while cursor.next:
# iterate to end of list
cursor = cursor.next
cursor.next = Node(value)
def insert(self, value):
if self.is_empty():
self.head = Node(value)
return
temp = Node(value)
temp.next = self.head
self.head = temp
def count(self):
if self.is_empty():
return 0
cursor = self.head
count = 1
while cursor.next:
cursor = cursor.next
count += 1
return count
def search(self, value):
if self.is_empty():
return False
cursor = self.head
def found():
return cursor.value == value
if found():
return cursor
while cursor.next:
if found():
return cursor
cursor = cursor.next
return False
def remove(self, value):
if self.is_empty():
return False
# special treatment for first value
# TODO find algorithm that avoids this
if self.head.value == value:
self.head = None
return True
assert self.count() > 1, 'list has at least one element'
found = False
current = self.head
previous = None
while not found:
if current.value == value:
found = True
break
elif not current.next:
break
previous = current
current = current.next
if not found:
return False
previous.next = current.next
# current is garbage collected
return True
def is_empty(self):
return not bool(self.head)
class OrderedLinkedList(LinkedList):
def append(self, value):
# meaningless in this context
raise(NotImplemented)
def insert():
# TODO insert value at correct location
# to maintain ordering
pass
def search(self, value):
# TODO implent binary or quick search
pass
class TestLinkedList(unittest.TestCase):
def test_creation_returns_empty_list(self):
list_ = LinkedList()
self.assertTrue(list_.is_empty)
def test_one_value(self):
list_ = LinkedList()
list_.append(1)
self.assertTrue(isinstance(list_.head, Node))
self.assertEqual(list_.head.value, 1)
self.assertFalse(list_.is_empty())
def test_two_nodes(self):
list_ = LinkedList()
list_.append(1)
list_.append(2)
self.assertEqual(list_.head.next.value, 2)
def test_three_nodes(self):
list_ = LinkedList()
list_.append(1)
list_.append(2)
list_.append(3)
self.assertEqual(list_.head.next.next.value, 3)
def test_insert_empty(self):
list_ = LinkedList()
list_.insert(1)
self.assertEqual(list_.head.value, 1)
def test_insert_one_member(self):
list_ = LinkedList()
list_.append(1)
list_.insert(2)
self.assertEqual(list_.head.value, 2)
self.assertEqual(list_.head.next.value, 1)
def test_insert_two_members(self):
list_ = LinkedList()
list_.append(1)
list_.insert(2)
list_.insert(3)
self.assertEqual(list_.head.next.next.value, 1)
self.assertEqual(list_.head.next.value, 2)
self.assertEqual(list_.head.value, 3)
def test_count_empty(self):
list_ = LinkedList()
self.assertEqual(list_.count(), 0)
def test_count_one_member(self):
list_ = LinkedList()
list_.insert(2)
self.assertEqual(list_.count(), 1)
def test_count_hundred_members(self):
list_ = LinkedList()
for i in range(100):
list_.insert(i)
self.assertEqual(list_.count(), 100)
def test_search_empty(self):
list_ = LinkedList()
got = list_.search(3)
self.assertFalse(got)
def test_search_one_member_true(self):
list_ = LinkedList()
list_.insert(3)
got = list_.search(3)
self.assertTrue(got)
self.assertEqual(got.value, 3)
def test_search_one_member_false(self):
list_ = LinkedList()
list_.insert(2)
got = list_.search(3)
self.assertFalse(got)
def test_search_fifty_members_true(self):
list_ = LinkedList()
for i in range(50):
list_.insert(i)
got = list_.search(49)
self.assertTrue(got)
self.assertEqual(got.value, 49)
def test_search_fifty_members_false(self):
list_ = LinkedList()
for i in range(50):
list_.insert(i)
got = list_.search(50)
self.assertFalse(got)
def test_remove_empty_list(self):
list_ = LinkedList()
self.assertFalse(list_.remove(5))
def test_remove_from_one_member_list(self):
list_ = LinkedList()
list_.insert(5)
list_.remove(5)
self.assertTrue(list_.is_empty())
def test_remove_from_two_member_list(self):
list_ = LinkedList()
list_.insert(5)
list_.insert(65)
list_.remove(5)
self.assertEqual(list_.count(), 1)
self.assertEqual(list_.head.value, 65)
def test_remove_from_end_of_three_member_list(self):
list_ = LinkedList()
list_.insert(5)
list_.insert(65)
list_.insert(43)
list_.remove(5) # first inserted will be last in list
self.assertEqual(list_.count(), 2)
self.assertEqual(list_.head.value, 43)
self.assertEqual(list_.head.next.value, 65)
self.assertIsNone(list_.head.next.next)
class TestOrderedLinkedList(unittest.TestCase):
pass
if __name__ == '__main__':
unittest.main()
|
# Definition for a binary tree node.
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
def getResult(self, root, result, level):
if not root: return None
if len(result) <= level: result.insert(0, [])
result[-(level+1)].append(root.val)
if root.left: self.getResult(root.left, result, level+1)
if root.right: self.getResult(root.right, result, level+1)
def levelOrderBottom(self, root):
"""
:type root: TreeNode
:rtype: List[List[int]]
"""
result = []
self.getResult(root, result, 0)
return result
|
class Solution(object):
def longestPalindromeSubseq(self, s):
"""
:type s: str
:rtype: int
"""
d = {}
def findIn(s):
if s not in d:
max_length = 0
for i in set(s):
i, j = s.find(i), s.rfind(i)
current_length = 1 if i == j else 2 + findIn(s[i+1:j])
max_length = max(max_length, current_length)
d[s] = max_length
return max_length
else:
return d[s]
return findIn(s)
ss = ["bbbab", "cbbd", 'euazbipzncptldueeuechubrcourfpftcebikrxhybkymimgvldiwqvkszfycvqyvtiwfckexmowcxztkfyzqovbtmzpxojfofbvwnncajvrvdbvjhcrameamcfmcoxryjukhpljwszknhiypvyskmsujkuggpztltpgoczafmfelahqwjbhxtjmebnymdyxoeodqmvkxittxjnlltmoobsgzdfhismogqfpfhvqnxeuosjqqalvwhsidgiavcatjjgeztrjuoixxxoznklcxolgpuktirmduxdywwlbikaqkqajzbsjvdgjcnbtfksqhquiwnwflkldgdrqrnwmshdpykicozfowmumzeuznolmgjlltypyufpzjpuvucmesnnrwppheizkapovoloneaxpfinaontwtdqsdvzmqlgkdxlbeguackbdkftzbnynmcejtwudocemcfnuzbttcoew']
for s in ss:
print(Solution().longestPalindromeSubseq(s))
|
from tree_generator import TreeGenerator
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def check(self, root, min, max):
if not root: return True
if (min and root.val <= min.val) or (max and root.val >= max.val):
return False
else:
return self.check(root.left, min, root) and self.check(root.right, root, max)
def isValidBST(self, root):
"""
:type root: TreeNode
:rtype: bool
"""
return self.check(root, None, None)
# root = TreeGenerator().generate([], [2,1,3,1,3,2,4])
# root = TreeGenerator().generate([], [1,2,3])
# root = TreeGenerator().generate([], [1,1])
root = TreeGenerator().generate([], [10,5,15,None,None,6,20])
print(Solution().isValidBST(root)) |
# Uses python3
import sys
def get_change(m):
# List will hold min number of change coins for values 0 - m
min_num_coins = [0] * (m + 1)
# Change coins
coins = [1, 3, 4]
# Looping through all the money values from 0 to m to find the change for each
for money in range(1, m + 1):
min_num_coins[money] = float('inf')
# For each coin, we calculate the change we would get
for coin in coins:
# If current coin is larger than current money value, we cannot get change
if money >= coin:
# We add + 1 because we need to account for when (money - coin) = 0 and get_change rets 0
num_of_coins = min_num_coins[money - coin] + 1
if num_of_coins < min_num_coins[money]:
min_num_coins[money] = num_of_coins
return min_num_coins[m]
if __name__ == '__main__':
m = int(sys.stdin.read())
print(get_change(m))
|
"""
there is no 9 digit number exist for condition
"""
# how many digit numbers
ref = set("02468")
f = lambda x:set(str(x+int(str(x)[::-1]))).isdisjoint(ref)
count = 0
for digit_len in range(2,9):
for first_digit in range(1,10):
def get_numbers(first_digit, digit_len, num):
global count
if digit_len == 1:
for i in range(first_digit-1,0,-2):
if f(num*10+i):
count+=1
else:
for i in range(0,10):
get_numbers(first_digit,digit_len-1,num*10+i)
get_numbers(first_digit, digit_len-1,first_digit)
print(2*count) |
from prime import is_prime
l1 = 2
l2 = 8
l3 = 20
l2_size = 2 # 6*l2_size
corner_gape_l2 = 1
count = 2 # first 1 second 2
current_ans = 2
while(True):
start_point = l2
end_point = l2+6*l2_size-1
start_ele_pd = 0
end_ele_pd = 0
if is_prime(abs(6*l2_size-1)):
start_ele_pd+=1
end_ele_pd+=1
# for start
start_ele_pd+= is_prime(abs(l2-l3))
start_ele_pd+=is_prime(abs(l2-(l3+1)))
start_ele_pd+=is_prime(abs(l2-(l3+6*(l2_size+1)-1)))
start_ele_pd+=is_prime(abs(l2-l1))
# end
end_ele_pd+= is_prime(abs(end_point-l1))
end_ele_pd+= is_prime(abs(end_point-(l1+6*(l2_size-1)-1)))
end_ele_pd+= is_prime(abs(end_point-(l3+6*(l2_size+1)-1)))
end_ele_pd+= is_prime(abs(end_point-(l3+6*(l2_size+1)-2)))
# print("pd",start_ele_pd)
#print(start_point,start_ele_pd,abs(l2-l3),abs(l2-(l3+1)),abs(l2-(l3+6*(l2_size+1)-1)),abs(l2-l1))
if start_ele_pd==3:
count+=1
current_ans = start_point
if end_ele_pd ==3:
count+=1
current_ans = end_point
if count == 2000:
print(current_ans)
break
l1 = l2
l2 = l3
l3 = l3+6*(l2_size+1)
l2_size += 1 # 6*l2_size
"""
14516824220
real 0m3.088s
user 0m3.046s
sys 0m0.016s
""" |
import re
def min_and_max(iterable):
iterator = iter(iterable)
# Assumes at least two items in iterator
minim, maxim = sorted((next(iterator), next(iterator)))
for item in iterator:
if item < minim:
minim = item
elif item > maxim:
maxim = item
return (minim, maxim)
with open('gen_20', 'r') as f:
g = (re.search(r'Fitness: [-+]?[0-9]*\.?[0-9]*',line,re.I) for line in f)
values = (float(v.group(1)) for v in g)
minim, maxim = min_and_max(values)
print(maxim)
print(minim) |
total = 0
for h in range(24): #시간
for m in range(60): #분
if '3' in str(h) or '3' in str(m):
total += 60
print (total) |
n1 = float(input("Digite primer número: "))
n2 = float(input("Digite segundo número: "))
while(True):
print("****MENU****")
print("1.- Sumar dos números")
print("2.- Restar dos números")
print("3.- Multiplicar dos números")
print("4.- Salir del programa")
opcion = input("Opción: ")
if opcion == '1':
resultado = n1 + n2
elif opcion == '2':
resultado = n1-n2
elif opcion == '3':
resultado =n1*n2
elif opcion =='4':
break
else:
print("Digite una opción válida")
continue
print("El resultado es:",resultado)
|
from tkinter import *
window = Tk()
window.title("Welcome to LikeGeeks app")
# set window size - sets window width to 350 pixels and the height to 200 pixels
window.geometry('350x200')
"""
Common Steps
1. Create widget
2. Position widget in grid
3. Add attributes (font, forground color, background color)
"""
# create a label
lbl = Label(window, text="Hello", font=("Arial Bold", 50))
# Using the grid function set the labels position on the form
lbl.grid(column=0, row=0)
# create a textbox using Tkinter Entry class
txt = Entry(window, width=10, state="disabled")
# Using the grid function set the textboxs position on the form
txt.grid(column=1, row=0)
# execute a function when the button is clicked
def clicked():
# get entry text using get function
res = "Welcome to " + txt.get()
# if you clikc the buttin and there is a text on the entry widget, it will
# show "Welcome to" concatenated with the entered text.
lbl.configure(text=res)
txt.focus()
#create a button
# change the foreground of any widget using fg property
# change the background of any widget using bg property
btn = Button(window, text="Click Me", command = clicked)
# Using the grid function set the buttons position on the form
btn.grid(column=2, row=0)
window.mainloop()
|
#counts number of sequences in File
import sys
file = sys.argv[1]
f = open(file, "r")
cnt = 0
for line in f:
if line[0] == "#": # 3 lines with "#" per sequence
cnt+=1
print(cnt, cnt/3)
|
#!/usr/bin/python
# --------------------------------------------------------
# PYTHON PROGRAM
# Here is where we are going to define our set of...
# - Imports
# - Global Variables
# - Functions
# ...to achieve the functionality required.
# When executing > python 'this_file'.py in a terminal,
# the Python interpreter will load our program,
# but it will execute nothing yet.
# --------------------------------------------------------
import sys
import codecs
# ------------------------------------------
# FUNCTION strip_comma
# ------------------------------------------
def strip_comma(s):
s = s.replace(',', '')
return s
#---------------------------------------
# FUNCTION strip_line
#---------------------------------------
def strip_line(line):
# Get rid of newline character
line = line.replace('\n', '')
# Split the string by the tabulator delimiter
words = line.split(' ')
# Get the key and the value and return them
language = words[0]
title = words[1]
views = words[2]
return language, title, views
# ------------------------------------------
# FUNCTION my_map
# ------------------------------------------
def my_map(input_stream, per_language_or_project, output_stream):
#create list to hold all the input from the input stream
input_list = []
# Process lines in the input stream
for line in input_stream:
input_list.append(line)
# create result list to hold modified input_list with changed language or project
results = []
for line in input_list:
if per_language_or_project:
#Separate the language, title and views into variables
(language, title, views) = strip_line(line)
language = language.split(".")[0]
results.append(language + " " + title + " " + views + "\n")
else:
#Separate the project, title and views into variables
(language, title, views) = strip_line(line)
if '.' in language:
project = language.split('.',1)[-1]
if '.' in project:
#print(project)
project = project.split('.')[0]
#print(project)
results.append(project + " " + title + " " + views + "\n")
#print(project + " " + title + " " + views + "\n")
else:
project = 'wikipedia'
results.append(project + " " + title + " " + views + "\n")
#print(project + " " + title + " " + views + "\n")
#Sort the results list on language/project
results.sort()
#current_lang variable to keep track of the language as I work through the results list
wordlist = results[0].split(' ')
current_lang = wordlist[0]
#current_lang_proj is a list to hold all entries of the current language or project
current_lang_proj = []
for line in results:
#split the line into it's constituent words
words = line.split(' ')
#Extract language title and views
language = words[0]
title = words[1]
views = words[2]
#strip the newline character from views
views = views.replace('\n', '')
if language == current_lang:
current_lang_proj.append(int(views))
else:
#This means there is no more of the previous language so now we
#add up all the views and write to file
#petitions is number of petitions for that language
petitions = 0
for i in current_lang_proj:
petitions = petitions + i
result_string = current_lang + "\t" + str(petitions) + "\n"
output_stream.write(result_string)
#Empty the list and start to fill it again with the new language
current_lang_proj = []
current_lang_proj.append(int(views))
#Set current_lang = to language
current_lang = language
#I had to put this block of code in as my loops weren't accounting for the last
#project/language
petitions = 0
for i in current_lang_proj:
petitions = petitions + i
result_string = current_lang + "\t" + str(petitions) + "\n"
output_stream.write(result_string)
# ------------------------------------------
# FUNCTION my_main
# ------------------------------------------
def my_main(debug, i_file_name, o_file_name, per_language_or_project):
# We pick the working mode:
# Mode 1: Debug --> We pick a file to read test the program on it
if debug == True:
my_input_stream = codecs.open(i_file_name, "r", encoding='utf-8')
my_output_stream = codecs.open(o_file_name, "w", encoding='utf-8')
# Mode 2: Actual MapReduce --> We pick std.stdin and std.stdout
else:
my_input_stream = sys.stdin
my_output_stream = sys.stdout
# We launch the Map program
my_map(my_input_stream, per_language_or_project, my_output_stream)
# ---------------------------------------------------------------
# PYTHON EXECUTION
# This is the main entry point to the execution of our program.
# It provides a call to the 'main function' defined in our
# Python program, making the Python interpreter to trigger
# its execution.
# ---------------------------------------------------------------
if __name__ == '__main__':
# 1. Input parameters
debug = True
i_file_name = "pageviews-20180219-100000_0.txt"
o_file_name = "mapResult.txt"
per_language_or_project = False # True for language and False for project
# 2. Call to the function
my_main(debug, i_file_name, o_file_name, per_language_or_project)
|
#!/usr/bin/python2
for i in range(1,5):
print i
else :
print 'the for loop is done '
|
class Tank(object):
def __init__(self,name):
self.name = name
self.alive = True
self.shells = 5
self.armor = 60
def __str__(self):
if self.alive:
return "%s (%i shells, %i armor)" % (self.name, self.shells, self.armor)
else:
return "%s is dead!" % self.name
def fire_at(self, enemy):
if self.shells >= 1:
self.shells-= 1
print self.name, 'fire at ' ,enemy.name
enemy.hit()
else:
print self.name, 'has no shells'
def hit(self):
self.armor-= 20
print self.name , 'is hit!'
if self.armor<= 0:
self.explode()
def explode(self):
self.alive = False
print self.name,'is exploded!'
|
#!/usr/bin/python2
#Filename is docstring.py
def printMax(x,y):
'''Print the maximum of the two numbers.
The two numbers must be integers'''
x = int(x)
y = int(y)
if x > y :
print x ,'is the maximum one '
else:
print y ,'is the maximum one '
printMax(3,5)
print printMax.__doc__
|
#!/usr/bin/python2
#Filename is using_file.py
poem = '''\
program amming is fun
when the work is done
if you want to make your work also fun:
use Python!
'''
f = file('poem.txt','w')#open for 'w'riting
f.write(poem)
f.close()
f = file('poem.txt')
#if no mode is specified ,'r'ead mode is assumed by default
while True:
line = f.readline()
if len(line) == 0:#Zero length indicates EOF
break
print line,
#Notice comma to avoid automaic newline add to by python
f.close()
#close the file
|
a=int(input("enter a"))
b=int(input("enter b"))
n=a+b
if n%2==0:
print("even")
else:
print("odd")
|
# Наследование
"""class Person:
name = "Ivan"
age = 10
def set(self, name, age):
self.name = name
self.age = age
class Student(Person):
course = 1
igor = Student()
igor.set("Igor", 19)
print(igor.course)
vlad = Person()
vlad.set("Влад", 25)
print(vlad.name + " " + str(vlad.age))
ivan = Person()
ivan.set("Иван", 56)
print(ivan.age) """
# инкапсуляция
"""
ставим _ перед name (_set) и функция не будет использоваться в других классах
(это как рекомендация для других разрабов)
ставим __ перед name (__set) то это уже строгое ограничение, выдаст ошибку,
если использовать в др классах \ методах и тд.
"""
class Person:
name = "Ivan"
age = 10
def set(self, name, age):
self.name = name
self.age = age
class Student(Person):
course = 1
igor = Student()
igor.set("Igor", 19)
print(igor.course)
vlad = Person()
vlad.set("Влад", 25)
print(vlad.name + " " + str(vlad.age))
ivan = Person()
ivan.set("Иван", 56)
print(ivan.age)
|
import sqlite3
from sqlite3 import Error
class File_database(object):
def __init__(self):
self.conn = sqlite3.connect("file database management.db")
self.cur = self.conn.cursor()
self.username = ""
self.conn.execute("""CREATE TABLE IF NOT EXISTS users(
username text PRINARY KEY,
password text NOT NULL);""")
self.conn.execute("""CREATE TABLE IF NOT EXISTS public (
title text ,
author text NOT NULL,
filename text NOT NULL,
type_form text );""")
def register_account(self,username,password):
self.cur.execute("""INSERT INTO users (username,password) VALUES (?,?)""",(username,password))
self.conn.commit()
self.send_history_table(username)
self.inbox_table(username)
print("Register Complete...")
def send_history_table(self,username):
self.conn.execute("""CREATE TABLE IF NOT EXISTS {}_send(
title text ,
author text NOT NULL,
filename text NOT NULL,
type_form text );""".format(username))
def add_send_history(self,title,author,filename,type_form):
try :
sql_command = """INSERT INTO {}_send(title,author,filename,type_form) VALUES (?,?,?,?)""".format(self.username)
self.cur.execute(sql_command,(title,author,filename,type_form,))
except Error as e:
print(e)
else :
self.conn.commit()
def get_send_history(self, username, file_name_search = None):
try:
sql_command = """SELECT * FROM {}_send """.format(username)
self.cur.execute(sql_command)
except Error as e :
print(e)
else :
data = []
for item in self.cur.fetchall() :
if file_name_search != None :
if item[2].find(file_name_search) != -1 :
data.append(item)
else :
data.append(item)
return data
def inbox_table(self,username):
self.conn.execute("""CREATE TABLE IF NOT EXISTS {}_inbox(
title text ,
author text NOT NULL,
filename text NOT NULL,
type_form text );""".format(username))
def add_inbox(self,title,author,filename,type_form,target):
try :
sql_command = """INSERT INTO {}_inbox(title,author,filename,type_form) VALUES (?,?,?,?)""".format(target)
self.cur.execute(sql_command,(title,author,filename,type_form,))
except Error as e:
print(e)
else:
self.conn.commit()
def get_inbox(self, username, file_name_search = None):
try:
sql_command = """SELECT * FROM {}_inbox """.format(username)
self.cur.execute(sql_command)
except Error as e :
print(e)
else :
data = []
for item in self.cur.fetchall() :
if file_name_search != None :
if item[2].find(file_name_search) != -1 :
data.append(item)
else :
data.append(item)
return data
def add_public(self,title,author,filename,type_form):
try :
sql_command = """INSERT INTO public(title,author,filename,type_form) VALUES (?,?,?,?)"""
self.cur.execute(sql_command,(title,author,filename,type_form,))
except Error as e:
print(e)
else:
self.conn.commit()
def get_public(self,file_name_search = None):
try:
sql_command = """SELECT * FROM public """
self.cur.execute(sql_command)
except Error as e :
print(e)
else :
data = []
for item in self.cur.fetchall() :
if file_name_search != None :
if item[2].find(file_name_search) != -1 :
data.append(item)
else :
data.append(item)
return data
def search_name(self,user):
try :
sql_command = """SELECT * FROM users WHERE username = ?"""
self.cur.execute(sql_command,(user,))
except :
return None
else:
try :
user = self.cur.fetchall()[0][0]
print(user)
except :
return None
else:
return user
def login(self,user,password):
try :
self.cur.execute("""SELECT * FROM users WHERE username = ? AND password = ?""",(user,password,))
except :
return False
else :
try :
username = self.cur.fetchall()[0][0]
except IndexError :
return False
else:
print('Login complete...')
return True
def logout(self):
self.username = ""
def check_all_id(self):
self.cur.execute("""SELECT * FROM users""")
row = self.cur.fetchall()
for item in row :
print(item)
def check_all_item(self, username):
sql_command = """SELECT * FROM {}_send """.format(username)
self.cur.execute(sql_command)
row = self.cur.fetchall()
for item in row :
print(item)
def del_all_table(self):
self.cur.execute("""SELECT * FROM users""")
row = self.cur.fetchall()
for item in row :
sql_command = '''DROP TABLE {}_send'''.format(item[0])
sql_command2 = '''DROP TABLE {}_inbox'''.format(item[0])
self.conn.execute(sql_command)
self.conn.execute(sql_command2)
self.conn.execute('''DROP TABLE public''')
self.conn.execute('''DROP TABLE users''')
def send_item(self,item):
owner = item["Author : "]
receiver = item["User to receive : "]
title = item["Title : "]
type_send = item["Send to : "]
print(type_send)
fileName = item["File name"]
type_file = item["Type file"]
data = item["File : "] # ต้องอ่านไฟล์ก่อนค่อยใส่ไปในตัวแปร data นี่เป็นเพียงการทดลอง
if type_file != fileName : # error string of find method when it is not found
if type_send == "send_public" :
self.add_send_history(title,owner,fileName,data,type_file)
print(self.get_send_history())
try :
self.cur.execute("""SELECT * FROM users""")
row = self.cur.fetchall()
except :
pass
else:
self.add_public(title,owner,fileName,type_file)
else:
receiver_username = self.search_name(receiver)
print(receiver_username)
if receiver_username != None :
self.add_send_history(title,owner,fileName,type_file)
self.add_inbox(receiver_username,title,owner,fileName,type_file)
print(self.get_inbox())
self.username = owner
def test():
a = File_database()
a.del_all_table()
def test2():
b = File_database()
print(b.username)
def test3():
c = File_database()
c.check_all_id() |
import scrabble
def is_palindrome(word):
return word == word[::-1]
count_palindromes = 0
longest = ""
for word in scrabble.wordlist:
if is_palindrome(word):
count_palindromes += 1
if len(word) > len(longest):
longest = word
print("\nTotal number of palindromes: {:d}".format(count_palindromes))
print("The longest palindrome is: {:s}\n".format(longest))
|
# 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 BSTIterator:
# Use a stack to store nodes; if it is not empty, then it has Next
# Initialize: get all left nodes until the last left one(smallest)
# next: get the node then simply pop it.
# if the node has right, right.left is not None, then the next should be the smallest left
# TC -> O(N); Space -> O(h)
def __init__(self, root: "TreeNode"):
self.stack = []
while root:
self.stack.append(root)
root = root.left
def next(self) -> int:
node = self.stack[-1]
self.stack.pop()
if node.right:
n = node.right
while n:
self.stack.append(n)
n = n.left
return node.val
def hasNext(self) -> bool:
return len(self.stack) > 0
# Your BSTIterator object will be instantiated and called as such:
# obj = BSTIterator(root)
# param_1 = obj.next()
# param_2 = obj.hasNext()
|
# 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 flatten(self, root: "TreeNode") -> None:
"""
Do not return anything, modify root in-place instead.
"""
# Divide and Conquer
# Each time, return the last node
# 1. root is None: return None
# 2. left is None and right is None: return root
# 3. One of them is not None: return the other one's last node
# make sure they are all in the right side of the root.
# 4. Both not None:
# left_lastnode.right = root.right
# root.right = root.left
# root.left = None
# TC: O(N); Space: O(1)
self.flatten_divide(root)
def flatten_divide(self, root):
if not root:
return None
left_last = self.flatten_divide(root.left)
right_last = self.flatten_divide(root.right)
if not left_last and not right_last:
return root
if not left_last:
return right_last
if not right_last:
root.right = root.left
root.left = None
return left_last
left_last.right = root.right
root.right = root.left
root.left = None
return right_last
|
def recur_fibo(n,m):
"""Recursive function to
print Fibonacci sequence"""
if n < 1:
return 0
elif n==1:
return 1
else:
for i in range(1,m+1):
return recur_fibo(n-m,m)
c=recur_fibo(5,2)
print(c) |
import numpy as np
import pylab
def sigmoid(z):
return 1.0 / (1.0 + np.exp(-z))
x = np.array(range(1, 100)) / 100
b = -40
w = 500
# 一个神经元的输出
# y = sigmoid(w * x + b)
#
# pylab.plot(x, y, 'r-', label=u'b -40 w 100')
# pylab.legend()
# 两个神经元
s1 = 0
s2 = .2
h1 = -.3
h2 = .3
s3 = .2
s4 = .4
h3 = -1.3
h4 = 1.3
s5 = .4
s6 = .6
h5 = -.5
h6 = .5
s7 = .6
s8 = .8
h7 = 1.3
h8 = -1.3
s9 = .8
s10 = 1.0
h9 = -.2
h10 = .2
b1 = -s1 * w;
b2 = -s2 * w;
b3 = -s3 * w;
b4 = -s4 * w;
b5 = -s5 * w;
b6 = -s6 * w;
b7 = -s7 * w;
b8 = -s8 * w;
b9 = -s9 * w;
b10 = -s10 * w;
y2 = sigmoid(w * x + b1) * h1 + sigmoid(w * x + b2) * h2 \
+ sigmoid(w * x + b3) * h3 + sigmoid(w * x + b4) * h4 \
+ sigmoid(w * x + b5) * h5 + sigmoid(w * x + b6) * h6 \
+ sigmoid(w * x + b7) * h7 + sigmoid(w * x + b8) * h8 \
+ sigmoid(w * x + b9) * h9 + sigmoid(w * x + b10) * h10
pylab.plot(x, y2, 'b-', label=u'4 ')
pylab.legend()
pylab.show()
|
def x_win(game):
for i in range(3):
if game[3 * i] == game[3 * i + 1] == game[3 * i + 2] == "X":
return True
elif game[i] == game[i + 3] == game[i + 6] == "X":
return True
if game[2] == game[4] == game[6] == "X":
return True
elif game[0] == game[4] == game[8] == "X":
return True
return False
def o_win(game):
for i in range(3):
if game[3 * i] == game[3 * i + 1] == game[3 * i + 2] == "O":
return True
elif game[i] == game[i + 3] == game[i + 6] == "O":
return True
if game[2] == game[4] == game[6] == "O":
return True
elif game[0] == game[4] == game[8] == "O":
return True
return False
def move(player):
while True:
global board
coordinates = input("Enter the coordinates:")
coordinates = coordinates.split()
if coordinates[0].isdigit() and coordinates[1].isdigit():
if 1 <= int(coordinates[0]) <= 3 and 1 <= int(coordinates[1]) <= 3:
if board[(int(coordinates[0]) - 1) * 3 + (int(coordinates[1]) - 1)] == "_":
board[3 * (int(coordinates[0]) - 1) + (int(coordinates[1]) - 1)] = player
break
else:
print("This cell is occupied! Choose another one!")
else:
print("Coordinates should be from 1 to 3!")
else:
print("You should enter numbers!")
print("---------")
print(f"| {board[0]} {board[1]} {board[2]} |")
print(f"| {board[3]} {board[4]} {board[5]} |")
print(f"| {board[6]} {board[7]} {board[8]} |")
print("---------")
if x_win(board):
print("X wins")
exit(0)
elif o_win(board):
print("O wins")
exit(0)
elif len([x for x in board if x == "_"]) == 0:
print("Draw")
exit(0)
board = list("_________")
print("---------")
print(f"| {board[0]} {board[1]} {board[2]} |")
print(f"| {board[3]} {board[4]} {board[5]} |")
print(f"| {board[6]} {board[7]} {board[8]} |")
print("---------")
while True:
move("X")
move("O")
|
import math
import numpy as np
import matplotlib.pyplot as plt
import sys
## USER DEFINED INPUTS -- call cmd: python RKT2.py A B C
# A. Defines where on Earth the Rocket starts at
def getLaunchPadAngle():
try:
return float(sys.argv[1])
except ValueError:
print("Invalid Velocity Angle. Setting to default value of 0")
return 0.0
# B. Defines the angle, relative to the ground, with which the rocket is initially pointing
def getVelocityAngle():
try:
return float(sys.argv[2])
except ValueError:
print("Invalid Velocity Angle. Setting to default value of 0")
return 0.0
# C. Defines the initial speed with which the rocket begins
def launchspeed():
try:
return float(sys.argv[3])
except ValueError:
print("Invalid launch speed. Setting to default value of 0")
return 0
LaunchPadLocationAngle = getLaunchPadAngle()
VelocityAngle = getVelocityAngle()
VelocityAngle += (LaunchPadLocationAngle - 90) #updates angle to make it relative to earth at all points
RocketSpeed = launchspeed()
print(" ")
print(" **NEW COMMAND**")
print(" Starting at an angle of: ", LaunchPadLocationAngle)
print(" launch angle Rel to surface: ", VelocityAngle)
print(" Initial Speed: ", RocketSpeed)
print(" ")
print("computing...")
## TRIGONOMETRY SETUP
def cos(x):
return math.cos(x * math.pi / 180) #Defines cos(x)
def sin(x):
return math.sin(x * math.pi / 180) #Defines sin(x)
def mag(x):
return np.linalg.norm(x) #Defines mag([x,y,z]) for magnitude
## CONSTANTS
# Universal Constants
G = 6.67E-11 # m/s^2
# Masses
earthMass = 5.972E24 # kg
rocketMass = 50000 # kg
# Radii
earthRadius = 6.371E6 # meters, radius of earth
## NON USER DEFINED INPUTS
# Angles
# Separation Distances
rocketdis = earthRadius + 1 # meters, launch pad relative to center of earth
boundary = earthRadius
# Time Tracking
startTime = 0 # seconds, beginning of launch
timeDelta = 1 # seconds, change in time per simulation loop
endTimeDays = 1
endTime = 100 # seconds, time before simulation close
## INITIAL CONDITIONS
# Position Vectors
positionEarth = np.array([0, 0, 0]) # [x,y,z]
positionRocket = np.array([rocketdis * cos(LaunchPadLocationAngle),rocketdis * sin(LaunchPadLocationAngle),0])
# Velocity Scalars
Vr = RocketSpeed # m/s, initial velocity of rocket
# Velocity Vectors
startingRocketVelocity = np.array([Vr * cos(VelocityAngle),Vr * sin(VelocityAngle),0])
# Create Edge Boundaries for Graph
graphx = np.array([-1.5*boundary,-1.5*boundary,1.5*boundary,1.5*boundary])
graphy = np.array([-1.5*boundary,1.5*boundary,-1.5*boundary,1.5*boundary])
## PLOTTING
plt.ion() # flag plt as interactive
plt.figure(figsize=(10,10))
# plots earth's curve
surfaceangle = 85 # initializes angle for circle graphing of earth
while surfaceangle < 95:
plt.plot([earthRadius*cos(surfaceangle)], [earthRadius*sin(surfaceangle)], color='blue', linestyle='dashed', marker='o', markerfacecolor='blue', markersize=3) # plots earth
surfaceangle += .5
# Starting Locations
plt.plot(positionRocket[0], positionRocket[1], 'go') # Rocket Starting Location
# Plot boundary points
plt.plot(graphx,graphy,'k^')
## LOOP SECTION of Plotting
currentTime = startTime # seconds, initializes time tracking variable
timeframe = 1 # divides time and declares number of points to plot
resolution = timeframe # Amount of time between plotted points
# Counters
outerLoopIterations = 0
totalInnerIterations = 0
crashrocket = 0 # Checks for crash condition of Rocket
z = 0 # Resolution tracker
##THE LOOP
while currentTime < endTime and crashrocket < 1:
outerLoopIterations += 1
print("Start Loop: ", outerLoopIterations)
while z < resolution:
totalInnerIterations += 1
#positions and updating
positionRocket += startingRocketVelocity * timeDelta # updates rocket position
#rocket vectors
rre = (positionEarth - positionRocket) / mag((positionEarth - positionRocket)) # unit vector from rocket to earth
rrmagearth = mag((positionEarth - positionRocket)) # distance between rocket and earth
#gravitational accelerations
grearth = (G * earthMass / (mag(positionRocket - positionEarth)) ** 2) * rre # acceleration due to gravity on the moon due to
# Updates Velocity after checking for crash conditions
if rrmagearth < (earthRadius):
crashrocket = 1
startingRocketVelocity = 0
else:
startingRocketVelocity += (grearth) * timeDelta
# Updates time
currentTime += timeDelta
z += timeDelta
plt.plot(positionRocket[0], positionRocket[1], color='green', linestyle='dashed', marker='o', markerfacecolor='green', markersize=3)#plots current point of rocket location
plt.show()
plt.pause(.0001)
print("Finish Loop: ", outerLoopIterations)
#END
## PRINT SECTION
print (" ")
if crashrocket == 1:
print(" rocket has crashed.")
else:
print(" rocket has NOT crashed.")
print (" ")
graphcommand = input("Would you like to close graph window (Y/N)? ")
if "graphcommand" == "Y" or "y" or "Yes" or "yes":
plt.pause(1)
else:
plt.pause(500) # Did this because the program will immediately exit since plt is no longer blocking the thread from continuing execution. sloppy but works
print(" ")
|
import math
def test_palindrome1(strings,answer):
print (palindrome1(strings)==answer)
def test_palindrome2(strings,answer):
print (palindrome2(strings)==answer)
def test_palindrome3(strings,answer):
print (palindrome3(strings)==answer)
def test():
test1 = "abba"
test_palindrome3(test1,True)
test2 = "Abbbba"
test_palindrome3(test2,False)
test3 = "gdfvtre"
test_palindrome3(test3,False)
test4 = "ab1221ba"
test_palindrome3(test4,True)
test5 = "abcba"
test_palindrome3(test5,True)
test6 = "abca"
test_palindrome3(test6, False)
def palindrome1(a):
if a == a[::-1]:
return True
else :
return False
def palindrome2(a):
b = list(a)
c = []
for i in range(len(a)-1,-1,-1):
c.append(a[i])
return (b==c)
def palindrome3(a):
for i in range(0,math.ceil((len(a)/2))):
if a[i] != a[(len(a)-1)-i]:
return False
return True
def main():
a = input()
b = palindrome3(a)
test() |
import math
def test(expected,answer):
print(expected==answer)
def test_multiply_left_right_array():
test1 = [1,2,3,4]
test(multiply_left_right_array(test1),21)
test2 = [4,5,6]
test(multiply_left_right_array(test2), 44)
test3 = []
test(multiply_left_right_array(test3),0)
test4 = [10,9,8,7,6,5,4,3,2,1]
test(multiply_left_right_array(test4),600)
def multiply_left_right_array(arrs):
size = len(arrs)
n = math.floor(size/2)
arr1 = arrs[0:n]
arr2 = arrs[n:size]
pro1 = pro2 = 0
for i in range (0,len(arr1)):
pro1 = pro1 + arr1[i]
for i in range(0, len(arr2)):
pro2 = pro2 + arr2[i]
return(pro1*pro2)
test_multiply_left_right_array() |
def test(output,expected):
print(output==expected)
def test_list_to_string():
test1 = "g e e k s f o r g e e k s"
test(list_to_string(test1),"geeksforgeeks")
test2 = "p r o g r a m m i n g"
test(list_to_string(test2),"programming")
def list_to_string(strs):
strs = list(strs)
for i in range(0,len(strs)):
if strs[i] == " ":
strs[i] = ''
strs = "".join(strs)
return strs
test_list_to_string() |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
class Solution(object):
def longestPalindrome(self, s):
"""
:type s: str
:rtype: str
"""
if len(s) <= 1:
return s
out = s[0]
for i in range(len(s)-1):
l = len(out)/2
tmp = self.palin(s, i, i)
if len(tmp) > len(out):
out = tmp
if s[i] == s[i+1]:
tmpdb = self.palin(s, i, i+1)
if len(tmpdb) > len(out):
out = tmpdb
return out
def palin(self, s, left, right):
while left > 0 and right < len(s)-1:
if s[left-1] == s[right+1]:
left -= 1
right += 1
else:
return s[left:right+1]
return s[left:right+1]
|
import l98
# import l102 # level order traversal
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
root = TreeNode(3)
root.left = TreeNode(1)
root.right = TreeNode(5)
root.left.left = TreeNode(0)
root.left.right = TreeNode(2)
root.right.left = TreeNode(4)
root.right.right = TreeNode(6)
#root.left.left.left = TreeNode(8)
test = l98.Solution()
out = test.isValidBST(root)
print out
|
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
# recursive
"""
def postorderTraversal(self, root):
if root is None:
return []
return self.postorderTraversal(root.left)\
+ self.postorderTraversal(root.right)+ [root.val]
# iterative - 2 stacks
def postorderTraversal(self, root):
if root is None:
return []
stack1, stack2 = [root], []
while stack1:
current = stack1.pop()
stack2.append(current)
if current.left:
stack1.append(current.left)
if current.right:
stack1.append(current.right)
return [i.val for i in stack2[::-1]]
"""
# iterative - 1 stack
def postorderTraversal(self, root):
if root is None:
return []
stack, current, res = [], root, []
while True:
while current:
if current.right:
stack.append(current.right)
stack.append(current)
current = current.left
current = stack.pop()
topStack = None if len(stack) < 1 else stack[-1]
if current.right and current.right == topStack:
stack.pop()
stack.append(current)
current = current.right
else:
res.append(current.val)
current = None
if len(stack) < 1:
break
return res
|
class Solution(object):
def rotate(self, matrix):
"""
:type matrix: List[List[int]]
:rtype: void Do not return anything, modify matrix in-place instead.
"""
n = len(matrix)-1
if n <= 0:
return None
for i in range((n+1)/2):
for j in range(i, n-i):
matrix[i][j], matrix[j][n-i], matrix[n-i][n-j], matrix[n-j][i] \
= matrix[n-j][i], matrix[i][j], matrix[j][n-i], matrix[n-i][n-j]
|
import matplotlib.pyplot as plt
# x_values = [1, 2, 3, 4, 5]
x_value = list(range(1, 1001))
# y_values = [1, 4, 9, 16, 25]
y_values = [x ** 2 for x in x_value]
plt.scatter(x_value, y_values, s=20, edgecolors='none', c=y_values, cmap=plt.cm.Blues)
# 设置图表标题,并给坐标轴加上标签
plt.title("Square Numbers", fontsize=24)
plt.xlabel("Value", fontsize=14)
plt.ylabel("Square of Value", fontsize=14)
# 设置刻度标记大小
plt.tick_params(axis='both', which='major', labelsize=14)
# 设置每个坐标轴的取值范围
plt.axis([0, 1100, 0, 1100000])
plt.show()
# 保存图片
# plt.savefig("squares_plot.png",bbox_inches='tight') |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.