text
stringlengths 37
1.41M
|
---|
nums = [1,2,3,4,5]
#regular
for num in nums:
print(num)
print('-----')
#break
for num in nums:
if num==3:
print(num,"is found, Chimp has it!!")
break
print(num)
print('-----')
#continue
for num in nums:
if num==3:
print(num,"is found, Chimp has it!!")
continue
print(num)
print('-----')
#loop in loop
for num in nums:
for letter in 'abc':
print(num, letter)
print('-----')
#range
for i in range(10):
print(i)
print('-----')
#range with starting position
for i in range(2, 10):
print(i) |
#Sets are unordered and no deplicates list
courses = {'Maths', 'Physics','Chemistry', 'Computer Sci', 'Maths'}
print(courses)
print('Maths' in courses)
cs_courses = {'Java','Angular', 'Maths', 'Computer Sci'}
print(cs_courses .intersection(courses))
print(cs_courses.difference(courses))
print(cs_courses.union(courses))
#empty Set - watch out
#empty_set = {} // BOOM..not a inbuilt method just like lists and tuples, this will create a empty dictionary
empty_set = set() |
class Node:
def __init__(self, key, value, left=None, right=None, size=1):
assert ((left is None or isinstance(left, Node)) and
(right is None or isinstance(right,Node)))
self.key = key
self.value = value
self.left = left
self.right = right
self.size = size
class BST:
def __init__(self, root=None):
self.root = root
def size(self):
if not self.root:
return 0
result = self.root.size
if self.root.left:
result += self.root.left.size()
if self.root.right:
result += self.root.right.size()
return result
def find(self, key):
if not self.root:
return None
if key == self.root.key:
return self.root.value
if key < self.root.key:
if not self.root.left:
return None
return self.root.left.find(key)
if key > self.root.key:
if not self.root.right:
return None
return self.root.right.find(key)
def insert(self, key, value):
if not self.root:
self.root = Node(key, value)
elif key == self.root.key:
self.root.value = key
elif key < self.root.key:
if not self.root.left:
self.root.left = BST()
self.root.left.insert(key, value)
else: # key > self.root.key:
if not self.root.right:
self.root.right = BST()
self.root.right.insert(key, value)
def delete(self, key):
node = self.root
if node.key == key:
if node.left:
while node.key != key:
if node.key < key:
node = node.left
else:
node = node.right
@property
def key(self):
return self.root.key
@property
def value(self):
return self.root.value
@property
def left(self):
return self.root.left
@property
def right(self):
return self.root.right
|
s1 = 'abcdefg'
s2 = 'cdefghi'
def fn(s1,s2):
if len(s1) < len(s2):
s1,s2 = s2,s1
maxstr = s1
substr_maxlen = max(len(s1),len(s2))
for sublen in range(substr_maxlen,-1,-1):
for i in range(substr_maxlen-sublen+1):
if maxstr[i:i+sublen] in s2:
return maxstr[i:i+sublen]
print(fn(s1,s2))
|
#! /usr/bin/python
# D:{SADASANT;}
import euler
def euler0019(d,m,y): # d must be 31, m must be 12, y must be 2000 in order to solve the problem
""" How many Sundays fell on the first of the month during the twentieth century? """
D,M,Y = 1,1,1901
m30d = [4,6,9,11]
m31d = [1,3,5,7,8,10,12]
week = {1:'monday',2:'tuesday',3:'wednesday',4:'thursday',5:'friday',6:'saturday',7:'sunday'}
wekc = 2
if m > 12: return 'month out of range'
if m == 2 and d > 28: return 'day out of range'
elif m in m30d and d > 30: return 'day out of range'
elif m in m31d and d > 31: return 'day out of range'
print D,M,Y,week[wekc]
answercounter = 0
while (D,M,Y) != (d,m,y):
if D is 1 and wekc is 7: answercounter += 1
if M is 2 and D is 28 and Y%4 and (not Y%100 or Y%400): M,D = M+1,0
elif M is 2 and D is 29: M,D = M+1,0
elif M in m30d and D is 30: M,D = M+1,0
elif M in m31d and D is 31: M,D = M+1,0
D,wekc = D+1,wekc+1
if wekc > 7: wekc = 1
if M is 13: Y,M,D = Y+1,1,1
print D,M,Y,week[wekc]
return answercounter
print euler0019(31,12,2000)
|
#! /usr/bin/python
# D:{SADASANT;}
import euler
def euler0009(n): # n must be 1000 in order to solve the problem
""" Find the only Pythagorean triplet, {a, b, c}, for which a + b + c = 1000. """
l = []
for x in range(1,n/2):
l.append(x)
for xxx in l:
for xx in l:
for x in l:
if x<xx<xxx and x+xx+xxx == n and x**2+xx**2 == xxx**2:
return x,xx,xxx,x*xx*xxx
return ''
print euler0009(1000)
|
#! /usr/bin/python
# D:{SADASANT;}
import euler
def euler0016(n,e): # n must be 2 and e must be 1000 in order to solve the problem
""" What is the sum of the digits of the number 2**1000? """
N = n**e
print N
R = 0
for x in str(N):
R+=int(x)
return R
print euler0016(2,1000)
|
def mdc(a, b):
return a if b == 0 else mdc(b, a % b)
def mmc(a, b):
return abs(a * b) / mdc(a, b)
while True:
try:
lastAlign = int(input())
line = input().split(' ')
l1 = int(line[0])
l2 = int(line[1])
l3 = int(line[2])
days = int(mmc(mmc(l1, l2), l3) - lastAlign)
print(days)
except EOFError:
break
|
import numpy as np
import maze as m
# the neighbors checked when scanning neighbors
neighbors = [
(-1, 0), # one space above
(1, 0),
(0, -1),
(0, 1),
]
# the search starts at [start[0]][start[1]] and searches for [end[0][end[1]]
# only works for rectangular mazes
# assumes the params are valid
def dfs(path, maze, start, end):
path.clear()
stack = [ start ]
predecessors = {
start : start,
}
while len(stack) > 0:
current = stack.pop(0) # pop from fringe
dfs_insert_neighbors(maze, current, stack, predecessors) # add current's neighbors to stack and update predecessors
if end in predecessors: # compile the path if end is found
compile_path(path, end, predecessors)
return True
else:
return False
# updates the predecessors if possible for the current cell's neighbors and inserts back into the stack
def dfs_insert_neighbors(maze, current, stack, predecessors):
for neighbor_offset in neighbors:
neighbor = (
current[0] + neighbor_offset[0],
current[1] + neighbor_offset[1],
)
# if neighbor doesn't exist (out of bounds), skip
if (neighbor[0] < 0) or (neighbor[1] < 0):
continue
if (neighbor[0] >= maze.height) or (neighbor[1] >= maze.width):
continue
# if neighbor is not an open space
if maze.maze[neighbor[0]][neighbor[1]] != 0:
continue
# if neighbor has not been looked at before, insert to stack
if neighbor not in predecessors:
predecessors[neighbor] = current
stack.insert(0, neighbor)
# assembles the path given the end, predecessors, and distances
# [start, ... , end]
def compile_path(path, end, predecessors):
current = end
path.insert(0, current)
while predecessors[current] != current: # while current isn't the start
current = predecessors[current]
path.insert(0, current)
return
# example usage of maze_search.py
"""
maze = m.Maze(10, 10, .25)
maze.output()
path = []
dfs(
path,
maze,
(1, 1),
(8, 8)
)
print(path)
""" |
# Dictionary Stuff
print("Hello World");
test = {'color':'green','points':5};
print(test['color']);
print(test['points']);
test['xPos'] = 0;
test['yPos'] = 25;
test['dummydata']='deleteme';
print(test);
del test['dummydata'];
print(test);
#===========================================
favLang = {'Chris':'C#','Hazel':'Plural Site','Bill':'VB','Larry':'dBase'};
print(favLang);
language = favLang['Chris'].title();
print(f"1 Favorite language is {language}.");
#===another way
language = favLang.get('Chris','Not assigned');
print(f"2 Favorite language is {language}.");
language = favLang.get('Christ','Not assigned');
print(f"3 Favorite language is {language}.");
#================= looping
for key, value in favLang.items():
print(f"\nLanguage:{key} :: {value}");
for name in sorted(favLang.keys()):
print(f"{name.title()}");
for langs in sorted(favLang.values()):
print (f"{langs.title()}");
#===========
while name != '':
name = input("Enter name for yourself:")
if (len(name)>0):
print(f"Name entered is: {name}")
age = input("Enter Age:")
if (int(age) > 60):
print("Dude your old!!")
|
def sort_stupid(sort_list):
iteration = 0
for i in range(len(sort_list) - 1):
for j in range(len(sort_list) - i - 1):
iteration += 1
if sort_list[j] > sort_list[j + 1]:
sort_list[j], sort_list[j + 1] = sort_list[j + 1], sort_list[j]
return [sort_list, iteration] |
# Informatika érettségi 2012 május programozás----------
# 1.feladat --------------------------------------------
utak = []
with open('tavok.txt','r') as fbe:
for sor in fbe:
s = sor.split()
utak.append([int(s[0]),int(s[1]),int(s[2])])
utak = sorted(utak)
# 2. feladat -------------------------------------------
print('--- 2. feladat ---')
print('A hét legelső útja',utak[0][2],'km hosszú volt.')
# 3.feladat --------------------------------------------
print('--- 3. feladat ---')
print('A hét utolsó útja',utak[-1][2],'km hosszú volt.')
# Előkészítés a következő feladatokhoz -----------------
fuvarok = [0]*8 # fuvarok száma az egyes napokon
tavok = [0]*8 # távolságok az egyes napokon
for ut in utak:
fuvarok[ut[0]] += 1
tavok[ut[0]] += ut[2]
|
# Parkettázás
import math
# --- negyzet() függvény ----
def negyzet():
a = float(input('A négyzet oldala: '))
t = a * a
print('Terület:',math.ceil(t))
print('Költség:',ar * math.ceil(t))
# --- teglalap() függvény ----
def teglalap():
pass
# --- Főprogram ---
ar = 1000
print('Parkettázás')
while True:
print('1 - Négyzet\n2 - Téglalap\n0 - Kilépés')
v = input('Válasz: ')
if v == '1':
negyzet()
elif v == '2':
teglalap()
else:
break
|
# Hőmérséklet statisztika
feb = [2,1,5,-3,3,2,8,-5,1,2,2,-5,0,5,
-3,5,-3,3,-21,1,-9,-2,1,1,-9,-12,0,-5]
while True:
print('1-Átlag 2-Min 3-Max 4-Fagy 5-Javít '+
'6-Diagram 0-Kilép')
v = input('Választás: ')
if v == '1':
print('Átlag:',sum(feb)/len(feb))
elif v == '2':
hideg = min(feb)
print('Minimum:',hideg,'Nap:',
feb.index(hideg)+1)
elif v == '3':
meleg = max(feb)
print('Maximum:',meleg,'Nap:',
feb.index(meleg)+1)
elif v == '4':
print('Fagyos napok:')
elif v == '5':
print('Javítás')
elif v == '6':
pass
else:
break
|
# Mit vegyek fel?
# Be: t
t = int(input('Hány fok van? '))
# Ha t < 10
# Ki: kabátot vegyél fel!
# Egyébként ha t < 20
# Ki: pulóvert vegyél fel!
# Egyébként
# Ki: pólót vegyél fel!
if t < 10:
print('Kabátot vegyél fel!')
elif t < 20:
print('Pulóvert vegyél fel!')
else:
print('Pólót vegyél fel!')
|
# -*- coding: utf-8 -*-
def fib(n):
a, b = 1, 1
while n:
a, b = b, a + b
yield a
n -= 1
if __name__ == '__main__':
# [1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
print([i for i in fib(10)])
|
import thorpy, pygame
application = thorpy.Application((500,500), "Launching alerts")
# ****************** First launcher : button 1 ******************
#This launcher launches a simple button
my_element = thorpy.make_button("I am a useless button\nClick outside to quit.")
button1 = thorpy.make_button("Launcher 1")
#we set click_quit=True below, because we did not provide a "ok" and/or "cancel"
#button to the user. Element disappears When user clicks outside it.
thorpy.set_launcher(button1, my_element, click_quit=True)
# ****************** Second launcher : button 2 ******************
#here the element to be launched is a box with ok and cancel buttons + custom
#elements. We can also use make_ok_box, with only 1 text.
#Note that DONE_EVENT and CANCEL_EVENT are posted accordingly at unlaunch.
box = thorpy.make_ok_cancel_box([thorpy.make_button(str(i)) for i in range(8)],
ok_text="Ok", cancel_text="Cancel")
button2 = thorpy.make_button("Launcher 2")
thorpy.set_launcher(button2, box)
# ****************** Third launcher : button 3 ******************
#This launcher launches a box, set it green, and changes screen color when
#unlaunched.
button3 = thorpy.make_button("Launcher 3")
other_box = thorpy.make_ok_box([thorpy.make_text("Color is gonna change...")])
my_launcher = thorpy.set_launcher(button3, other_box)#this time get the launcher
#we specify some custom operations that have to be done before/after launching:
def my_func_before():
my_launcher.launched.set_main_color((0,255,0)) #change launched box color
my_launcher.default_func_before() #default stuff
def my_func_after():
background.set_main_color((0,100,100)) #change background color
my_launcher.default_func_after() #default stuff
my_launcher.func_before = my_func_before
my_launcher.func_after = my_func_after
# ****************** Fourth launcher : event ******************
#This launcher is not linked to a ThorPy element, but instead user can activate
#it by pressing SPACE
unlaunch_button = thorpy.make_ok_box([thorpy.make_text("Ready to unlaunch?")])
unlaunch_button.stick_to("screen", "top", "top")
invisible_launcher = thorpy.get_launcher(unlaunch_button, autocenter=False)
# set focus to False for non-blocking behaviour:
##invisible_launcher.focus = False
#this reaction will be added to the background:
reac = thorpy.ConstantReaction(pygame.KEYDOWN, invisible_launcher.launch,
{"key":pygame.K_SPACE})
#add a text so user knows what to do
text4 = thorpy.make_text("Press space to launch invisible_launcher", 15, (0,0,255))
background = thorpy.Background(elements=[text4, button1, button2, button3])
background.add_reaction(reac)
thorpy.store(background)
menu = thorpy.Menu(background)
menu.play()
application.quit() |
input_file = 'data.txt'
# input_file = 'testdata.txt'
with open(input_file, 'r') as f:
data = f.readlines()
ROCK = 1
PAPER = 2
SCISSORS = 3
mapA = {'A': ROCK,
'B': PAPER,
'C': SCISSORS}
mapX = {'X': ROCK,
'Y': PAPER,
'Z': SCISSORS}
point_sum = 0
def compareAX(A, X):
"""
>>> compareAX(1, 1)
3
>>> compareAX(2, 1)
1
>>> compareAX(3, 1)
2
>>> compareAX(1, 2)
4
>>> compareAX(2, 2)
5
>>> compareAX(3, 2)
6
>>> compareAX(1, 3)
8
>>> compareAX(2, 3)
9
>>> compareAX(3, 3)
7
"""
win = {ROCK: PAPER,
PAPER: SCISSORS,
SCISSORS: ROCK}
draw = {ROCK: ROCK,
PAPER: PAPER,
SCISSORS: SCISSORS}
loose = {ROCK: SCISSORS,
PAPER: ROCK,
SCISSORS: PAPER}
if X == 1:
return loose[A] + 0
if X == 2:
return draw[A] + 3
if X == 3:
return win[A] + 6
for line in data:
A, X = line.strip().split(' ', maxsplit=ROCK)
A = mapA[A]
X = mapX[X]
turn_sum = compareAX(A, X)
point_sum += turn_sum
print(point_sum)
|
input_file = 'data.txt'
# input_file = 'testdata.txt'
with open(input_file, 'r') as f:
data = f.readlines()
priorities = 0
def get_priority(a):
"""
>>> get_priority('a')
1
>>> get_priority('p')
16
>>> get_priority('z')
26
>>> get_priority('A')
27
>>> get_priority('P')
42
>>> get_priority('Z')
52
"""
if a.islower():
return ord(a) - ord('a') + 1
return ord(a) - ord('A') + 27
for line in data:
line = line.strip()
length = len(line)
assert length % 2 == 0
half_length = int(length/2)
first = line[:half_length]
second = line[half_length:]
common = None
for a in first:
if a in second:
common = a
priority = get_priority(common)
priorities += priority
print(priorities)
|
"""
This file will contain all the functions which will allow us to interact with PostgreSQL (our relational DB).
Note: we have created the user and the database using pgAdmin.
"""
import psycopg2
from timeSeriesDB import resources as res
from influxdb import InfluxDBClient
def connect_postgres():
"""
This function will create a session for us in order to work with the created database in PostgreSQL
Since the database is already created, the values of these fields will be permanents
:return: the connection which will allow us to interact with the database; None if we could not create a connection
"""
try:
conn = psycopg2.connect(database="covid_world", user="postgres", password="postgres")
return conn
except Exception as e:
print(e)
return None
def commit_changes(conn, cur):
"""
Commit and save changes of the operation we did
:param conn: the connection that will allow us to interact with the database
:param cur: the pointer to the database
:return:
"""
conn.commit() # <--- makes sure the change is shown in the database
conn.close()
cur.close()
def create_table(table_name):
"""
Create a new table to our relational database
The fields can not be changed since they are related to the fields we have created in the Time Series Database
Fields
-------------------------------------------------------------------------------------
month (text, PK) -> will be used to relate the relational DB with the measurements of the Time Series Database
avg_confirmed (float) -> will contain the average number of confirmed cases in a month
avg_deceased (float) -> will contain the average number of deceased cases in a month
avg_recovered (float) -> will contain the average number of recovered cases in a month
total_confirmed (integer) -> will contain the total number of confirmed cases in a month
total_deceased (integer) -> will contain the total number of deceased cases in a month
total_recovered (integer) -> will contain the total number of recovered cases in a month
total_days (integer) -> will contain the total number of days that we have inserted data in a month
The total_* fields will be useful in order to recompute the avg_* fields in case a point is modified or inserted in the TS database
:param table_name: the name to be given to the table
:return:
"""
conn = connect_postgres()
# If we could not connected to the database we will exit
if not conn:
print("Could not connect to the database")
return
# Like a pointer to the database
cur = conn.cursor()
try:
cur.execute(f"CREATE TABLE {table_name} (month text PRIMARY KEY, avg_confirmed float, avg_deceased float, avg_recovered float, "
f"total_confirmed integer, total_deceased integer, total_recovered integer, total_days integer);")
print("Table created!")
except Exception as e:
print(e)
else:
commit_changes(conn, cur)
def insert_data(table_name, month, avg_confirmed, avg_deceased, avg_recovered, total_confirmed, total_deceased, total_recovered, total_days):
"""
Insert the computed results for the specific month in the table
:param table_name: the name of the table where we want to insert the data
:param month: the name of the month which is a unique value
:param avg_confirmed: the average number of confirmed cases for the month
:param avg_deceased: the average number of deceased cases for the month
:param avg_recovered: the average number of recovered cases for the month
:param total_confirmed: the total number of confirmed cases for the month
:param total_deceased: the total number of deceased cases for the month
:param total_recovered: the total number of recovered cases for the month
:param total_days: the total number of days for which we have data for that month
:return:
"""
conn = connect_postgres()
# If we could not connected to the database we will exit
if not conn:
return
# Like a pointer to the database
cur = conn.cursor()
try:
cur.execute(f"INSERT INTO {table_name} VALUES ('{month}', {avg_confirmed}, {avg_deceased}, {avg_recovered}, {total_confirmed}, {total_deceased}"
f", {total_recovered}, {total_days});")
print("Data inserted!")
except Exception as e:
print(e)
else:
commit_changes(conn, cur)
def update_data(table_name, month, avg_confirmed, avg_deceased, avg_recovered, total_confirmed, total_deceased, total_recovered, total_days):
"""
Update the computed results for the specific month in the table
:param table_name: the name of the table where we want to insert the data
:param month: the name of the month which is a unique value
:param avg_confirmed: the average number of confirmed cases for the month
:param avg_deceased: the average number of deceased cases for the month
:param avg_recovered: the average number of recovered cases for the month
:param total_confirmed: the total number of confirmed cases for the month
:param total_deceased: the total number of deceased cases for the month
:param total_recovered: the total number of recovered cases for the month
:param total_days: the total number of days for which we have data for that month
:return:
"""
conn = connect_postgres()
# If we could not connected to the database we will exit
if not conn:
return
# Like a pointer to the database
cur = conn.cursor()
try:
cur.execute(f"UPDATE {table_name} SET avg_confirmed={avg_confirmed}, avg_deceased={avg_deceased}, avg_recovered={avg_recovered}, "
f"total_confirmed={total_confirmed}, total_deceased={total_deceased}, total_recovered={total_recovered}, total_days={total_days} "
f"WHERE month='{month}';") # PK
print("Data updated!")
except Exception as e:
print(e)
else:
commit_changes(conn, cur)
def delete_data(table_name, month):
"""
Delete a row of the table by his PK
:param table_name: the name of the table which contain the row we want to delete
:param month: the PK that will allow to identify the row and delete it
:return:
"""
conn = connect_postgres()
# If we could not connected to the database we will exit
if not conn:
return
# Like a pointer to the database
cur = conn.cursor()
try:
cur.execute(f"DELETE FROM {table_name} WHERE month='{month}';") # PK
print("Data deleted!")
except Exception as e:
print(e)
else:
commit_changes(conn, cur)
def get_data(table_name, atr_tuple=None, dicc_conditions=None):
"""
Get data from a table
:param table_name: Name of the table where we will select the data
:param atr_list: Tuple of attributes que want to select
:param dicc_conditions: Dictionary of conditions with format key = column, value = value column
:return: List of data selected
"""
conn = connect_postgres()
# If we could not connected to the database we will exit
if not conn:
print("Could not connect to the database")
return
# Like a pointer to the database
cur = conn.cursor()
try:
columns_select = '*'
if atr_tuple:
columns_select = atr_tuple
if dicc_conditions:
condition = ''
keys = list(dicc_conditions.keys())
condition += f"{keys[0]}='{dicc_conditions[keys[0]]}'"
for key_id in range(1, len(keys)):
key = list(dicc_conditions.keys())[key_id]
condition += f"AND {key}='{dicc_conditions[key]}'"
print(f"SELECT {columns_select} FROM {table_name} WHERE {condition};")
cur.execute(f"SELECT {columns_select} FROM {table_name} WHERE {condition};")
else:
cur.execute(f"SELECT {columns_select} FROM {table_name};")
return list(cur.fetchall())[0]
except Exception as e:
print(e)
def compute_data_from_time_series(table_name, db_name, month):
"""
Read data from the time series data and compute the necessary data in order to write to the relational table
:param table_name: where we will write the data computed
:param db_name: the name of the time series database from which we will collect the data
:param month: the measurement name from which we will read the data and the PK to be writen in the relational database
:return:
"""
# Create new client to connect with InfluxDB
try:
client = InfluxDBClient(host="localhost", port=8086)
except Exception as e:
print(e)
else:
# Select database
res.select_database(client, db_name)
lista_tablas = get_data('information_schema.tables', ('table_name'), {'table_schema': 'public'})
if lista_tablas:
lista_tablas = [tupla[0] for tupla in lista_tablas]
else:
lista_tablas = []
print(f"lista tablas: {lista_tablas}")
# init
dicc_years = {}
# Get the data we inserted in the time series database of each month
query_output = res.get_month_data_time_series(client, month)
# Compute data
for data in query_output:
# Check the year of the data
time = data['time'].split("-")[0]
# If is a new year of this month we creat a new key for this year with the values, we need this cause we
# store all the years data in the same mesuarement in influxdb
if time not in list(dicc_years.keys()):
dicc_years[time] = {'total_confirmed': 0, 'total_deceased': 0, 'total_recovered': 0, 'days': 0,
'avg_confirmed': 0, 'avg_deceased': 0, 'avg_recovered': 0}
if table_name+time not in lista_tablas:
create_table(table_name+time)
lista_tablas.append(table_name+time)
dicc_years[time]['total_confirmed'] += int(data['dailyconfirmed'])
dicc_years[time]['total_deceased'] += int(data['dailydeceased'])
dicc_years[time]['total_recovered'] += int(data['dailyrecovered'])
dicc_years[time]['days'] += 1
for key in list(dicc_years.keys()):
days = dicc_years[key]['days']
dicc_years[key]['avg_confirmed'] = round(dicc_years[key]['total_confirmed'] / days, 2)
dicc_years[key]['avg_deceased'] = round(dicc_years[key]['total_deceased'] / days, 2)
dicc_years[key]['avg_recovered'] = round(dicc_years[key]['total_recovered'] / days, 2)
# Write the data into Table
insert_data(table_name+key, month, dicc_years[key]['avg_confirmed'], dicc_years[key]['avg_deceased'],
dicc_years[key]['avg_recovered'], dicc_years[key]['total_confirmed'],
dicc_years[key]['total_deceased'], dicc_years[key]['total_recovered'], days)
print(get_data('india_covid_2020', dicc_conditions={"month": 'May'})) |
"""
Basic mathematical functions operate element-wise on arrays. They are available both as operator overloads and as functions in the NumPy module.
import numpy
a = numpy.array([1,2,3,4], float)
b = numpy.array([5,6,7,8], float)
print a + b #[ 6. 8. 10. 12.]
print numpy.add(a, b) #[ 6. 8. 10. 12.]
print a - b #[-4. -4. -4. -4.]
print numpy.subtract(a, b) #[-4. -4. -4. -4.]
print a * b #[ 5. 12. 21. 32.]
print numpy.multiply(a, b) #[ 5. 12. 21. 32.]
print a / b #[ 0.2 0.33333333 0.42857143 0.5 ]
print numpy.divide(a, b) #[ 0.2 0.33333333 0.42857143 0.5 ]
print a % b #[ 1. 2. 3. 4.]
print numpy.mod(a, b) #[ 1. 2. 3. 4.]
print a**b #[ 1.00000000e+00 6.40000000e+01 2.18700000e+03 6.55360000e+04]
print numpy.power(a, b) #[ 1.00000000e+00 6.40000000e+01 2.18700000e+03 6.55360000e+04]
"""
import numpy as np
array_A = list()
array_B = list()
n, m = [int(i) for i in input().strip().split()]
for elements in range(n):
np.array(array_A.append(list(map(int, input().strip().split()))))
for elements in range(n):
np.array(array_B.append(list(map(int, input().strip().split()))))
print(np.add(array_A, array_B))
print(np.subtract(array_A, array_B))
print(np.multiply(array_A, array_B))
print(np.floor_divide(array_A, array_B))
print(np.mod(array_A, array_B))
print(np.power(array_A, array_B))
|
## Chapter 05 | Exercise 01
# Write a program which repeatedly reads numbers until the user enters “done”.
# Once “done” is entered, print out the total, count, and average of the numbers.
# If the user enters anything other than a number, detect their mistake using try and except
# and print an error message and skip to the next number.
## Redoing Assignment to incorporate lists from later lecture.
## QUESTION:
# Is there a way to construction this with a "for...in" loop? What's critical in making the decision between "for...in" and "while"?
# I suspect "while" is the only way since the list is initially empty
# Kicking things off with a greeting to guide user
print(
"Enter as many numbers as you wish to calculate their sum and average. When finished, enter 'done' instead of a number."
)
# Creating an empty list to append User_Input values
User_Numbers = list()
while True:
## QUESTION: why is the loop breaking if I start with a string value or when initially entering 'done'? This behavior did not occur prior to the introduction of lists.
User_Input = input("Enter a number: ")
if User_Input == "done":
break
try:
_Number = float(User_Input)
# User_Numbers.append(_Number) ## QUESTION: would it be best to nest 'list.append' within try? Pros/Cons? Not seeing difference in output after moving this to line 34.
except:
print(
f"Error: {_Number} is not a valid entry; please enter a numerical value to continue or 'done' to exit."
)
continue
User_Numbers.append(_Number)
Total_List_Value = sum(User_Numbers)
Average_List_Value = Total_List_Value / len(User_Numbers)
print("Total:", Total_List_Value)
print("Count:", len(User_Numbers))
print("Average", Average_List_Value)
|
## Chapter 04 | Exercise 01
## Section 4.5: Random Numbers
# Run the program (pg. 46) on your system and see what numbers you get.
# Run the program more than once and see what numbers you get.
import random
for i in range(10):
x = random.random()
print(x)
|
# ASSIGNMENT INSTRUCTIONS | Ch 08, Problem 04
#
# Open the file romeo.txt and read it line by line. For each line, split the
# line into a list of words using the split() method. The program should
# build a list of words. For each word on each line check to see if the word is
# already in the list and if not append it to the list. When the program completes,
# sort and print the resulting words in alphabetical order.
fname = input("Enter file name: ")
fh = open(fname)
lst = list()
for line in fh:
# QUESTION
# The below lines (14, 15)... is there a way to combine them?
# Or is the below best practice in python?
line = line.rstrip()
words = line.split()
# QUESTION
# Is there another way to do this?
# Is it best to track duplicates with another list/set?
for word in words:
if word not in lst:
lst.append(word)
print(sorted(lst))
# Successfully completed this assignment
# 12/12/2019
|
## Chapter 12 | Exercise 03 (Week 4)
## Following Links in Python
"""
In this assignment you will write a Python program that expands on http://www.py4e.com/code3/urllinks.py. The program will use urllib to read the HTML
from the data files below, extract the href= vaues from the anchor tags, scan for a tag that is in a particular position relative to the first name in
the list, follow that link and repeat the process a number of times and report the last name you find.
We provide two files for this assignment. One is a sample file where we give you the name for your testing and the other is the actual data you need to
process for the assignment
Sample problem: Start at http://py4e-data.dr-chuck.net/known_by_Fikret.html
Find the link at position 3 (the first name is 1). Follow that link. Repeat this process 4 times. The answer is the last name that you retrieve.
Sequence of names: Fikret Montgomery Mhairade Butchi Anayah
Last name in sequence: Anayah
Actual problem: Start at: http://py4e-data.dr-chuck.net/known_by_Colvin.html
Find the link at position 18 (the first name is 1). Follow that link. Repeat this process 7 times. The answer is the last name that you retrieve.
Hint: The first character of the name of the last page that you will load is: A
Strategy
The web pages tweak the height between the links and hide the page after a few seconds to make it difficult for you to do the assignment without writing a
Python program. But frankly with a little effort and patience you can overcome these attempts to make it a little harder to complete the assignment without
writing a Python program. But that is not the point. The point is to write a clever Python program to solve the program.
"""
import urllib.request, urllib.parse, urllib.error
from bs4 import BeautifulSoup
import ssl
# Ignore SSL certificate errors
ctx = ssl.create_default_context()
ctx.check_hostname = False
ctx.verify_mode = ssl.CERT_NONE
url = input("Enter URL: ")
count = input("Enter count: ") # number of times to loop
position = input("Enter position: ") # to pull specific href url
icount = int(count)
iposition = int(position)
## QUESTION: How does one determine whether starting at 1 is more appropriate rather than 0? I initially assumed 0, but did not get the desired output.
i = 1
targetUrl = url
while i <= icount:
print(targetUrl)
html = urllib.request.urlopen(targetUrl, context=ctx).read()
soup = BeautifulSoup(html, "html.parser")
# Retrieve all of the anchor tags
## QUESTION: How does one determine whether the "minus 1" is necessary?
targetTag = soup("a")[iposition - 1]
if i == icount:
print(targetTag.get("href", None))
print(targetTag.contents[0])
targetUrl = targetTag.get("href", None)
i += 1
|
## Chapter 12 | Exercise 02 (Week 4)
## Scraping Numbers from HTML using BeautifulSoup
"""
In this assignment you will write a Python program similar to http://www.py4e.com/code3/urllink2.py. The program will use urllib to read the HTML from the data files below, and parse the data, extracting numbers and compute the sum of the numbers in the file.
We provide two files for this assignment. One is a sample file where we give you the sum for your testing and the other is the actual data you need to process for the assignment.
Sample data: http://py4e-data.dr-chuck.net/comments_42.html (Sum=2553)
Actual data: http://py4e-data.dr-chuck.net/comments_332715.html (Sum ends with 10)
You do not need to save these files to your folder since your program will read the data directly from the URL. Note: Each student will have a distinct data url for the assignment - so only use your own data url for analysis.
You are to find all the <span> tags in the file and pull out the numbers from the tag and sum the numbers.
"""
from urllib.request import urlopen
from bs4 import BeautifulSoup
import ssl
# Ignore SSL certificate errors
ctx = ssl.create_default_context()
ctx.check_hostname = False
ctx.verify_mode = ssl.CERT_NONE
url = input("Enter URL: ")
html = urlopen(url, context=ctx).read()
soup = BeautifulSoup(html, "html.parser")
# Retrieve all of the <span> tags
tags = soup("span")
commentsList = list()
for tag in tags:
# Look at the parts of a tag
# print("TAG:", tag)
# print("Comments:", tag.contents[0])
commentsList.append(tag.contents[0])
# Creating a loop to convert commentsList to string type and sum all numbers
## Question: Is there a better way? I was running into issues with list type and couldn't manipulate the contents of list.
commentsTotal = 0
for count in commentsList:
commentsTotal += int(count)
print(commentsTotal)
print(commentsList)
|
class Node:
def __init__(self,val):
self.__val=val
self.__left=None
self.__right=None
def getVal(self):
return self.__val
def getLeft(self):
return self.__left
def getRight(self):
return self.__right
def setLeft(self,node):
self.__left=node
def setRight(self,node):
self.__right=node
class BinaryTree:
def __init__(self):
self.__root=None
def getRoot(self):
return self.__root
def setRoot(self, node):
self.__root=node
def printValues(self,node):
if node==None:
return
self.printValues(node.getLeft())
print(node.getVal())
self.printValues(node.getRight())
if __name__=="__main__":
node1=Node(12)
node2=Node(5)
node3=Node(17)
node1.setLeft(node2)
node1.setRight(node3)
node4=Node(4)
node5=Node(6)
node2.setLeft(node4)
node2.setRight(node5)
node6=Node(3)
node4.setLeft(node6)
node7=Node(19)
node3.setRight(node7)
node8=Node(18)
node9=Node(21)
node7.setLeft(node8)
node7.setRight(node9)
binaryTree=BinaryTree()
binaryTree.setRoot(node1)
binaryTree.printValues(node1) |
# # create a class instance of an employee
# class Employee:
# raise_amount = 1.05
# num_of_employees = 0
# def __init__(self, first_name, last_name, email, salary):
# self.first_name = first_name
# self.last_name = last_name
# self.email = email
# self.salary = salary
# Employee.num_of_employees += 1
# def full_name(self):
# return '{} {}'.format(self.first_name, self.last_name)
# def apply_raise(self):
# self.pay = int(self.salary * self.raise_amount)
# return self.pay
# @classmethod
# def set_raise_amt(cls, amount):
# cls.raise_amount = amount
# emp1 = Employee('Brain', 'Paul', '[email protected]', 70000)
# # print (emp1.email)
# # print(emp1.apply_raise())
# # print (Employee.num_of_employees)
# print (Employee.set_raise_amt)
# Python program to demonstrate
# use of class method and static method.
from datetime import date
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
# a class method to create a Person object by birth year.
@classmethod
def fromBirthYear(cls, name, year):
return cls(name, date.today().year - year)
# a static method to check if a Person is adult or not.
@staticmethod
def isAdult(age):
return age > 18
person1 = Person('mayank', 21)
person2 = Person.fromBirthYear('mayank', 1996)
print (person1.age)
print (person2.age)
# print the result
print (Person.isAdult(22))
|
# test data = [10,1,20,3,4,6,0]
def insertionsort(ulist):
for i in range(1,len(ulist)):
current=ulist[i]
while i>0 and ulist[i-1]>current:
ulist[i]=ulist[i-1]
ulist[i-1]=current
i=i-1
print(ulist)` 1 |
import time
start = time.time()
for i in range(1,100000001):
'Number {} squared is {} and cubed is {}'.format(i, i**2, i**3)
#print('Number {} squared is {} and cubed is {}'.format(i, i**2, i**3))
end = time.time()
total_time = end - start
print(total_time,'seconds')
print(total_time/60,'minutes')
|
"""Simple helper to paginate query
"""
import math
from mongoengine.queryset import QuerySet
DEFAULT_PAGE_SIZE = 10
DEFAULT_PAGE_NUMBER = 1
__all__ = ("Pagination",)
class Pagination(object):
"""
This is class for paginate
"""
def __init__(self, iterable, page=None, per_page=None):
self.iterable = iterable
page = page if page and page > 0 else DEFAULT_PAGE_NUMBER
per_page = per_page if per_page else DEFAULT_PAGE_SIZE
self.page = page
self.per_page = per_page
if isinstance(iterable, QuerySet):
self.total = iterable.count()
else:
self.total = len(iterable)
start_index = (page - 1) * per_page
end_index = page * per_page
self.items = iterable[start_index:end_index]
if isinstance(self.items, QuerySet):
self.items = self.items.select_related()
if not self.items and page != 1:
raise Exception
@property
def pages(self):
"""The total number of pages"""
return int(math.ceil(self.total / float(self.per_page)))
def prev(self, error_out=False):
"""Returns a :class:`Pagination` object for the previous page."""
assert self.iterable is not None, ('an object is required '
'for this method to work')
iterable = self.iterable
if isinstance(iterable, QuerySet):
iterable._skip = None
iterable._limit = None
return self.__class__(iterable, self.page - 1, self.per_page)
@property
def prev_num(self):
"""Number of the previous page."""
return self.page - 1
@property
def has_prev(self):
"""True if a previous page exists"""
return self.page > 1
def next(self, error_out=False):
"""Returns a :class:`Pagination` object for the next page."""
assert self.iterable is not None, ('an object is required '
'for this method to work')
iterable = self.iterable
if isinstance(iterable, QuerySet):
iterable._skip = None
iterable._limit = None
return self.__class__(iterable, self.page + 1, self.per_page)
@property
def has_next(self):
"""True if a next page exists."""
return self.page < self.pages
@property
def next_num(self):
"""Number of the next page"""
return self.page + 1
def iter_pages(self, left_edge=2, left_current=2,
right_current=5, right_edge=2):
last = 0
for num in range(1, self.pages + 1):
if (
num <= left_edge or
num > self.pages - right_edge or
(self.page - left_current <= num <= self.page + right_current)
):
if last + 1 != num:
yield None
yield num
last = num
if last != self.pages:
yield None
def paginate(self, schema):
return schema.dump(self.items, many=True), {
"total": self.total,
"total_page": self.pages,
"page": self.page,
"limit": self.per_page
}
|
from typing import Generator
def read_lines(file_path: str) -> Generator[str, None, None]:
""" Generator that yields clean lines from 'input.txt'; relative to the current working directory. """
with open(file_path, 'r') as fp:
for line in fp.readlines():
yield line.strip()
|
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author:Speciallan
class Solution(object):
def scoreOfParentheses(self, S):
"""
:type S: str
:rtype: int
"""
if len(S) == 0:
return 0
S = S.replace('()', '1')
arr = []
total = 0
for i in range(0, len(S)):
if S[i] == '(':
arr.append(total)
total = 0
elif S[i] == ')':
total = total *2 + arr.pop()
else:
total += int(S[i])
return total
if __name__ == "__main__":
S = "(()(()))"
solution = Solution()
result = solution.scoreOfParentheses(S)
print(result) |
#!/usr/bin/env python3
import psycopg2
from psycopg2 import Error
DBNAME = "news"
# 1. What are the most popular three articles of all time?
query1 = """Select articles.title AS article, count(*) AS views
FROM log, articles
WHERE log.path = (concat('/article/',articles.slug))
GROUP BY article
ORDER BY views DESC
LIMIT 3;
"""
# 2. Who are the most popular article authors of all time?
query2 = "select name, sum(views) as views from authors,\
popular_authors where authors.id = popular_authors.author\
group by name order by views desc;"
# 3. On which days did more than 1% of requests lead to errors?
query3 = "select * from error_per where err_persent > 1.0;"
def create_conn(query):
"""Connect to PostgreSQL databse and returns a database connection."""
try:
conn = psycopg2.connect(database=DBNAME)
cursor = conn.cursor()
cursor.execute(query)
result = cursor.fetchall()
return result
except Exception as e:
print(e)
exit(1)
def popular_articles(query1):
""" This method will return top three popular articles."""
result = create_conn(query1)
print("Popular articles:")
for i, (article, view) in enumerate(result, 1):
article_view = "{}. {} -- {} views".format(i, article, view)
print(article_view)
def popular_authors(query2):
"""This method will print top most popular article authors."""
result = create_conn(query2)
print("Popular authors:")
for i, (author, view) in enumerate(result, 1):
author_view = "{}. {} -- {} views".format(i, author, view)
print(author_view)
def log_error(query3):
"""This method will print which days more requests goes to errors."""
result = create_conn(query3)
print("More then 1% error days: ")
for i, (day, errors) in enumerate(result, 1):
err_day = "{}. {} -- {} %".format(i, day, errors)
print(err_day)
if __name__ == '__main__':
popular_articles(query1)
popular_authors(query2)
log_error(query3)
|
from __future__ import print_function
from collections import defaultdict
class Node(object):
def __init__(self, value):
self.value = value
self.isvisited = False
def __str__(self):
return (self.value)
class Graph(object):
def __init__(self):
self.vertices = defaultdict(list)
def addEdge(self, start, end):
self.vertices[start].append(end)
def BFS(self, start):
if start is None:
return None
queue = []
queue.append(start)
while(len(queue) > 0):
element = queue.pop(0)
if element.isvisited is False:
element.isvisited = True
print (element.value)
for item in self.vertices[element]:
if item.isvisited is False:
queue.append(item)
def DFS(self, start):
if start is None:
return None
start.isvisited = True
for item in self.vertices[start]:
if item.isvisited is False:
self.DFS(item)
print (start.value)
def DFS_iterate(self, start):
if start is None:
return None
staging, visited = [], []
staging.append(start)
while len(staging) > 0:
for item in staging:
print (item.value, end='')
for item in visited:
print (item.value, end='')
s = staging.pop(0)
s.isvisited = True
visited.append(s)
for item in self.vertices[s]:
if item.isvisited is False:
staging.append(item)
for item in visited:
print (item.value)
g = Graph()
node0 = Node(0)
node1 = Node(1)
node2 = Node(2)
node3 = Node(3)
g.addEdge(node0, node1)
g.addEdge(node0, node2)
g.addEdge(node1, node2)
g.addEdge(node2, node0)
g.addEdge(node2, node3)
g.addEdge(node3, node3)
print ("Following is Breadth First Traversal"
" (starting from vertex 2)")
#g.BFS(node2)
print ("Following is Depth First Traversal"
" (starting from vertex 2)")
g.DFS_iterate(node2)
|
# -*- coding: utf-8 -*-
"""
Created on Thu Jan 16 19:48:59 2020
@author: ANGELO
"""
def hiEverybody(myList):
for name in myList:
print("Hi,", name)
hiEverybody(["Adam","John","Lucy"])
def createList(n):
myList = []
for i in range (n):
myList.append(i)
return myList
print(createList(5)) |
# -*- coding:utf-8 -*-
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
# 思路:
# 1. 先判断是否存在环,若存在,返回一个环内节点
def getNodeOfLoop(self, pHead):
if pHead is None:
return None
# 两个指针,一快,一慢
p_slow = pHead
p_fast = p_slow.next
while p_fast is not None: # 快指针没有到头
if p_fast == p_slow: # 找到相遇的节点
return p_fast
p_slow = p_slow.next # 慢指针走一步
p_fast = p_fast.next # 快指针走两步
if p_fast is not None:
p_fast = p_fast.next
return None
# 2. 统计环内节点数目
def CountNodeOfLoop(self, tmp_p):
count = 1
meet_node = tmp_p
while tmp_p.next != meet_node:
tmp_p = tmp_p.next
count += 1
return count
# 3. 找到入口节点
def EntryNodeOfLoop(self, pHead):
meet_node = self.getNodeOfLoop(pHead) # 返回环内节点
if meet_node is None:
return None
num = self.CountNodeOfLoop(meet_node) # 统计环内节点数目
# 找入口节点: 两个节点,一个节点先走 n 步, 然后二者同样速度后移
p_pre = pHead
p_beh = pHead
for i in range(num):
p_pre = p_pre.next
while p_beh != p_pre:
p_pre = p_pre.next
p_beh = p_beh.next
return p_pre |
# -*- coding:utf-8 -*-
class Solution:
# s字符串
def isInt(self, s):
# 整数判断:
# 1. 为空
# 2. +,- 或者 1-9 开头,后面取值全是0-9
# (2.1) + 或者 - 开头,后面需要有值
# (2.2) 1-9开头,后面可以无值
if len(s)==0:
return True
if s[0]=='+' or s[0]=='-':
if len(s) == 1:
return True # 只有一个 + - 不匹配
else:
s = s[1:] # 进行下一步匹配
if s[0] > '0' and s[0]<='9': # 最高位不为 0
sign = True
for index in range(1, len(s)):
if s[index]<'0' or s[index]>'9':
sign = False
break
return sign
elif s[0] == '0' and len(s)==1: # 最后是0,但是整数只有0
return True
else:
return False
def isFloat(self, s):
# 1. 没有小数
# 2. 以.开头, 后面是常规数字
if len(s)==0:
return True
if s[0]=='.':
if len(s)==1:
return False
else:
# 判断小数点后的数字部分
sign = True
for index in range(1, len(s)):
if s[index]<'0' or s[index]>'9':
sign = False
break
return sign
else: # 没有以 '.' 开头
return False
def isIndex(self, s):
# 指数部分
if len(s)==0:
return True
if (s[0] == 'e' or s[0] == 'E') and len(s)>1:
# 与判断整数逻辑大体相似
return self.isInt(s[1:])
else: # 不是以 e 开头
return False
def isNumeric(self, s):
# 异常状态
if s is None or s == "":
return False
# 分别找出整数,小数和指数部分
start = index = 0
s_len = len(s)
while index<s_len and s[index]!='.' and s[index]!='e' and s[index]!='E':
index += 1
s1 = s[start:index] # 整数部分
start = index
while index<s_len and s[index]!='e' and s[index]!='E':
index += 1
s2 = s[start:index] # 小数部分
start = index
while index<s_len:
index+=1
s3 = s[start:index] # 指数部分
## 判断 s1, s2, s3 是否符合要求
# 边界条件:
# 1. s1 不存在,s2 必须存在,且 s3 不能存在
# 2. s1 存在,但是只有 +-, s2 必须存在 且 s3不能存在
if len(s1)==0 or (len(s1)==1 and (s1[0]=='+' or s[1]=='-')):
if len(s2) ==0 or len(s3)>0:
return False
# 判断整数部分,小数部分,指数部分是否都符合规范
return self.isInt(s1) and self.isFloat(s2) and self.isIndex(s3)
# write code here
sol = Solution()
positive_list = ['100', '+1.00', '-1.03', '0.123', '.123', '-1e2', '5E-3', '-.123']
negetive_list = ['100.e3', 'e3', '', '.e', '1.abc']
print([sol.isNumeric(each) for each in positive_list])
print([sol.isNumeric(each) for each in negetive_list]) |
# -*- coding:utf-8 -*-
class Solution:
def LeftRotateString(self, s, n):
# 思路: 将循环右移 取余
# 1. 长度为 len 的字符串,左移 len 还是它本身
# 2. 循环左移 n 相当于将 字符串 0-n的字符串 补 n-len的字符串后面
str_len = len(s) # 字符串长度
if str_len < 1: # 特殊情况,字符串为空
return ""
final_n = n%str_len
return s[n:] + s[0:n]
# write code here |
# Several common sorting algorithms: ascending
# 1. Bubble Sort
def bubble_sort(nums):
nums_len = len(nums)
for i in range(0, nums_len):
sign = True
for j in range(0, nums_len-i-1):
if nums[j+1] < nums[j]:
sign = False
nums[j], nums[j+1] = nums[j+1], nums[j]
if sign:
break
return nums
# 2. Selection Sort
def selection_sort(nums):
nums_len = len(nums)
for i in range(0, nums_len):
min_index = i
for j in range(i+1, nums_len):
if nums[j] < nums[min_index]:
min_index = j
nums[i], nums[min_index] = nums[min_index], nums[i]
return nums
# 3. Insertion Sort
def insertion_sort(nums):
nums_len = len(nums)
for i in range(1, nums_len):
value = nums[i]
insert_index = i-1
while insert_index >= 0 and nums[insert_index] > value:
nums[insert_index + 1] = nums[insert_index]
insert_index -= 1
nums[insert_index+1] = value
return nums
# 4. Insert Sort (希尔排序是升级版的插入排序)
def shell_sort(nums):
nums_len = len(nums)
gap = nums_len // 2
while gap > 0:
for i in range(gap, nums_len):
value = nums[i]
insert_index = i-gap
while insert_index >= 0 and nums[insert_index] > value:
nums[insert_index + gap] = nums[insert_index]
insert_index -= gap
nums[insert_index + gap] = value
gap = gap // 2
return nums
# 5. Merge Sort
def merge_sort(nums, l, r): # 初始的 l=0; r= len(arr)-1
def merge(arr, l, mid, r):
tmp_arr = [0]*(r-l+1)
p1, p2 = l, mid+1
# compare two arr, select smaller one to fill temporary array
index = 0
while p1 <= mid and p2 <= r:
if arr[p1]<=arr[p2]:
tmp_arr[index]=arr[p1]; p1+=1
else:
tmp_arr[index]=arr[p2]; p2+=1
index += 1
if p1<=mid:
tmp_arr[index:]=arr[p1:mid+1]
elif p2<=mid:
tmp_arr[index:]=arr[p2:r+1]
# 转移到原数组上
arr[l:r+1] = tmp_arr
if l >= r:
return
mid = (l+r)//2
merge_sort(nums, l, mid)
merge_sort(nums, mid+1, r)
merge(nums, l, mid, r)
return nums
# 6. Quick Sort
def qucik_sort(nums, low, high): # 这里起始 low=0, high=len(nums)-1
def partition(arr, low, high):
key = arr[low]
while low < high:
while low < high and arr[high] >= key:
high -= 1
arr[low] = arr[high]
while low < high and arr[low] <= key:
low += 1
arr[high] = arr[low]
arr[low] = key
return low
if low<high:
pos = partition(arr, low, high)
qucik_sort(arr, low, pos-1)
qucik_sort(arr, pos+1, high)
return nums
# 7. Heap Sort: 以小顶堆为例
def heap_sort(arr):
length = len(arr)
arr.insert(0, 0) # 在头插一个元素,保证下标从1开始
def adjust_heap(arr, start, length): # 从索引start开始,调整以它为顶点的堆
key = arr[start]
while start <= length:
child_index = 2*start
# 如果有两个孩子,找到比较下的一个
if child_index < length and arr[child_index]>arr[child_index+1]:
child_index += 1
if key > arr[child_index]: # 将较小的节点调整上去
arr[start]=arr[child_index]
start = child_index
else: # start节点就是最小节点
break
arr[start] = key
# 构建最小堆
for i in range(length//2, 0, -1): # 从后往前 对每个元素 自顶向下的 调整堆
adjust_heap(arr, i, length)
# 输出最小堆的排序序列
for i in range(length, 1, -1):
# 堆顶记录和最后一个元素互换
arr[1], arr[i] = arr[i], arr[1]
# 重新调整 1 ~ i-1 为小顶堆
adjust_heap(arr, 1, i-1)
# 最终数组按照从后往前的顺序 为升序, 翻转成正常的升序序列
return arr.reverse()
# 8. Count Sort
def count_sort(nums):
# 不是基于比较的,而是基于数组下标的,只适用于 整数数组,且极差较小的数组
max_value, min_value = max(nums), min(nums)
count_arr = [0]*(max_value-min_value+1)
# 第一次遍历,填充数组
for each in nums:
count_arr[each-min_value]+=1
# 频率数组, 保持稳定排序
for i in range(0, len(count_arr)-1):
count_arr[i+1] += count_arr[i]
# 从后向前遍历,保持稳定排序 ,
new_nums = [None]*len(nums)
for each in nums[::-1]:
new_nums[count_arr[each-min_value]-1] = each
count_arr[each-min_value] -= 1
return new_nums
# 9. bucket sort
def bucket_sort(nums):
max_value, min_value = max(nums), min(nums)
# 设置桶的数量,以及桶的跨度
bucket_num = 10
span = (max_value - min_value)//bucket_num + 1
bucket_list = [[] for i in range(10)]
# 遍历数组,将数据放入桶中
for each in nums:
bucket_list[(each - min_value)//span].append(each)
# 将每个桶排序
for bucket in bucket_list:
bucket.sort()
# 给每个桶排序后,合并所有的桶
return [ i for bucket in bucket_list for i in bucket]
if __name__=="__main__":
sort_func_map = {
'bubble sort:\t': bubble_sort,
'selection sort:\t': selection_sort,
'insertion sort\t': insertion_sort,
'shell sort\t': shell_sort,
'merge sort\t': merge_sort,
'quick sort\t': qucik_sort,
'heap sort\t': heap_sort,
'count sort\t': count_sort,
'bucket sort\t': bucket_sort
}
for key in sort_func_map:
nums = [8,10,2,9,35,23,4,6,7,2,3,4,17]
print(key, sort_func_map[key](nums))
|
# -*- coding:utf-8 -*-
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
# 使用栈的方式
'''
class Solution:
# 返回从尾部到头部的列表值序列,例如[1,2,3]
def printListFromTailToHead(self, listNode):
array_list = []
ll = listNode
while ll is not None:
array_list.append(ll.val)
ll = ll.next
return array_list[::-1]
# write code here
'''
# 使用递归函数,速度和内存会更快些
class Solution:
# 返回从尾部到头部的列表值序列,例如[1,2,3]
def recursion(self, ll, array_list):
if ll is None:
return;
if ll.next is not None:
self.recursion(ll.next, array_list)
array_list.append(ll.val)
def printListFromTailToHead(self, listNode):
array_list = []
self.recursion(listNode, array_list)
return array_list
# write code here |
class Solution:
# 返回ListNode
# 思路:不借助额外存储空间
def ReverseList(self, pHead):
# write code here
if pHead is None:
return pHead
p0 = None
p1 = pHead
while p1 is not None:
tmp = p1.next # 获得下一个节点
# 每次改变一个链接方向
p1.next = p0
# 都往后移动一个节点
p0 = p1
p1 = tmp
return p0
# 思路特点总结: 步步为营,每次移动一个单位 |
from random import shuffle
class Card:
number_face = {11: "jack", 12: "queen", 13: "king"}
def __init__(self, number, suit):
self.number = number
self.suit = suit
self.has_face = False
# Try catch block?
if self.suit == "clubs" or self.suit == "spades":
self.color = "black"
elif self.suit == "hearts" or self.suit == "diamonds":
self. color = "red"
if number > 10:
self.face = self.number_face[number]
self.number = 10
self.has_face = True
def __str__(self):
result = ""
if self.has_face:
result += self.face + " "
else:
result += str(self.number) + " "
result += str(self.suit)
return result
class Deck:
suit_color = {"clubs": "black", "spades": "black", "hearts": "red", "diamonds": "red"}
def __init__(self):
self.cards = list()
#Used cards pile
self.used = list()
for suit in self.suit_color:
for number in range(1, 14):
new_card = Card(number, suit)
self.cards.append(new_card)
shuffle(self.cards)
def get_card(self):
if len(self.cards) == 0:
self = Deck()
return self.cards.pop()
class Player:
amount = 0
def __init__(self):
self.hand = list()
def draw(self, deck):
self.hand.append(deck.get_card())
def get_value(player):
# First add all the non ones
non_ones = [card.number for card in player.hand]
value = sum(non_ones)
num_ones = len(player.hand) - len(non_ones)
# Now add all the ones
for i in range(num_ones):
if value + 11 + num_ones - (i + 1) <= 21:
value += 11
else:
value += 1
return value
def display_hands(player1, player2):
# Display the hands
print("Hands:")
print("----------------")
print("Player 1 hand: ")
for card in player1.hand:
print(card)
print("Player 2 hand: ")
for card in player2.hand:
print(card)
def play_round(player1, player2):
# find the value of each player's hand
# Instantiate deck
deck = Deck()
# Each player draws two cards
player1.draw(deck)
player1.draw(deck)
player2.draw(deck)
player2.draw(deck)
display_hands(player1, player2)
# Allow users to decide whether or not to hit or stay
p1_done = False
p2_done = False
winner = None
while(not p1_done or not p2_done):
print("Player 1, hit or stay (h/s)?: ")
user_input = input()
user_input = user_input.upper()
if user_input == "H":
player1.draw(deck)
display_hands(player1, player2)
print()
if get_value(player1) > 21:
return "Player 2"
else:
p1_done = True
print("Player 2, hit or stay (h/s)?: ")
user_input = input()
user_input = user_input.upper()
if user_input == "H":
player2.draw(deck)
display_hands(player1, player2)
print()
if get_value(player2) > 21:
return "Player 1"
else:
p2_done = True
# Determine who the winner is
player1_score = get_value(player1)
player2_score = get_value(player2)
if player1_score > player2_score:
return "Player1"
elif player2_score > player1_score:
return "Player2"
else:
return "Tie"
# The CLI
game_end = False
while(not game_end):
print("Press enter to start or q to exit")
user_input = input()
user_input = user_input.upper()
if user_input == "Q":
break
player1 = Player()
player2 = Player()
print("The winner is " + play_round(player1, player2))
print("Would you like to play again? (Y/N)")
user_input = input()
user_input = user_input.upper()
if user_input == "N":
game_end = True
|
number = 1
count = 0
largest = 0
while (number > 0):
number = float(input('Please enter a number'))
if (number > largest):
largest = number
print('Largest Number = ',largest)
|
def add(**arg):
sum = 0
for value in arg.values():
sum = sum + value
return sum
def multiple(a,b):
mul = a * b
return mul
print(add(a=5,b=7,c=8,d=10))
|
'''Diff_string will take two string as input and retrun the location where first diff occured'''
string1 = input('Please enter a name ')
string2 = input ('Please enter second name ')
def match_func(string1, string2):
i = 0
mismatch = 'N'
while i < len(string1) and i < len(string2) :
if string1[i] != string2[i]:
mismatch = 'Y'
break
i = i + 1
if mismatch == 'Y':
return(i)
else:
if len(string1) == len(string2):
return(-1)
else:
return(i)
Retrun_code = match_func(string1,string2)
if Retrun_code == -1 :
print('Strings are same')
else:
print('String are differ at position ', Retrun_code)
|
# basic types - numbers
# int() converts string to an interger
print(int('5') + int('3')) |
import os
import csv
# Path to collect data from the Resources folder
PybankCSV = os.path.join('Resources', 'budget_data.csv')
# Read in the CSV file
with open(PybankCSV, 'r') as csvfile:
# Split the data on commas
csvreader = csv.reader(csvfile, delimiter=',')
header = next(csvreader)
total = 0
count_months = 0
avg_change = 0
x = 0
diff_list = []
dict_dates = {}
for row in csvreader:
count_months = count_months + 1
total = total + int(row[1])
if x == 0:
x = int(row[1])
else:
diff = int(row[1]) - x
diff_list.append(diff)
dict_dates.update({diff:row[0]})
x = int(row[1])
greatest = max(diff_list)
least = min(diff_list)
avg_change = sum(diff_list) / (count_months - 1)
print("-----------------------------------")
print("Financial Analysis")
print("-----------------------------------")
print("Total Months: " + str(count_months))
print("Total: $" + str(total))
print("Average Change: $" + str(avg_change))
print("Greatest Increase in Profits: " + dict_dates.get(greatest) + " $(" + str(greatest) + ")")
print("Greatest Decrease in Profits: " + dict_dates.get(least) + " $(" + str(least) + ")")
f = open("file.txt", "w")
text = f"""
----------------------------------
Financial Analysis
Total Months: {str(count_months)}
Total: ${total}
Average Change: ${avg_change}
Greatest Increase in Profits: {dict_dates.get(greatest)} $({str(greatest)})
Greatest Decrease in Profits: {dict_dates.get(least)} $({str(least)})
"""
f.write(text)
f.close |
"""
scraper.py defines the YahooScraper class to scrape yahoo for finance data.
"""
import pickle
import re
import requests
class YahooScraper():
"""Scrapes Yahoo Finance for data"""
def __init__(self, features, feature_source_map, source_path):
self.features = features
self.feature_source_map = feature_source_map
self.model = self.load_model(source_path)
def load_model(self, source='model.pkl'):
"""Loads the model to use to predict
:param source: the source pkl
"""
return pickle.load(open(source))
def check_invest(self, ticker):
"""Determines whether someone should invest in a given ticker
:param ticker: the stock ticker
:returns: True or False for whether one should invest
"""
source = self.get_latest_source(ticker)
feature_vector = self.scrape(source)
feature_vector["stock_p_change"] = self.get_stock_p_change(ticker)
feature_vector["sp500_p_change"] = self.get_sp500_p_change()
x = []
for f in self.features:
if feature_vector[f] == "N/A":
x.append(0.0)
else:
x.append(feature_vector[f])
evaluation = self.model.predict(x)[0]
return evaluation
def get_stock_p_change(self, ticker):
"""Gets the percentage change between the current stock price and
the stock price one year ago
:param ticker: the stock ticker
:returns: a tuple of the stock pct change and the current stock value
"""
url = "http://finance.yahoo.com/d/quotes.csv?s=" + ticker + "&f=pm6"
resp = requests.get(url)
results = resp.text.split(',')
current_price = float(results[0])
percent_change = float(results[1][1:-2]) / 100
return (percent_change, current_price)
def get_sp500_p_change(self):
"""Get the percentage change between the current S&P500 price and
the S&P500 price one year ago
:returns: a tuple of the S&P500 pct change and the current S&P500 value
"""
url = "http://finance.yahoo.com/d/quotes.csv?s=^GSPC&f=bm6"
return (0.0, 0.0)
def get_latest_source(self, ticker):
"""Gets the most recent Yahoo Finance data for a ticker
:param ticker: the stock ticker
:returns: the latest HTML source for the ticker
"""
url = "http://finance.yahoo.com/q/ks?s=" + ticker + "+Key+Statistics"
resp = requests.get(url)
if resp.status_code != 200:
raise ValueError("Invalid ticker")
return resp.text
def scrape(self, source):
"""Scrapes HTML files for data and saves it as a CSV.
:param source: Yahoo Finance HTML page source
:returns: a dict of feature/value pairs scraped from the source
"""
feature_vector = {}
for feature in self.features:
source_feature = self.feature_source_map[feature]
if source_feature == "N/A":
feature_vector[feature] = "N/A"
continue
if source_feature == "Ticker":
feature_vector[feature] = ticker
continue
r = re.escape(source_feature) + r'.*?(\d{1,8}\.\d{1,8}M?B?|N/A)%?'
try:
val = re.search(r, source).group(1)
except AttributeError:
val = "N/A"
try:
if "B" == val[-1]:
val = float(val[:-1]) * (10 ** 9)
elif "M" == val[-1]:
val = float(val[:-1]) * (10 ** 6)
except ValueError:
val = "N/A"
feature_vector[feature] = val
return feature_vector
|
#!/cconjecture/ex.py
import algorithm as a
def getInput():
num = input("what number do you want to test?")
while True:
try:
num = int(num)
if num > 0:
return num
else:
print("please enter an integer greater than 0")
continue
except ValueError:
print("please enter an integer")
continue
def run():
n = getInput()
print("starting value: ")
print(n)
while n != 1:
n = a.conjecture(n)
print(n)
ex = input("would you like to test another number?")
if ex == "no":
return None
else:
run()
run()
|
import csv
import json
INPUT_CSV = 'data.csv'
YEAR = '2016'
def csv_to_json(input_file):
csv_file = open(input_file, 'r')
json_file = open('data.json', 'w')
reader = csv.DictReader(csv_file)
list = []
# Makes list of dictionaries of which country has how much renewable energy for the year
for row in reader:
if row['TIME'] == YEAR and row['MEASURE'] == "PC_PRYENRGSUPPLY" and row["Value"] != "":
list.append({'country': row['LOCATION'],
'value': row['Value']})
json.dump(list, json_file)
if __name__ == "__main__":
csv_to_json(INPUT_CSV)
|
import random
difficulty = input("What difficulty would you like? easy, medium or hard\n").lower()
guess_limit = 6
chances_left = 6
guess_taken = 0
while difficulty == "easy":
try:
random_number = random.randint(1, 10)
guess = int(input("Enter a number between 1 - 10: "))
guess_taken += 1
chances_left -= 1
print(f"You have {chances_left} guesses left")
if random_number == guess:
print("You got it right")
break
elif guess_taken == guess_limit:
print("Game Over")
break
else:
if guess > random_number:
print("Your guess was out of range")
else:
print("That was wrong")
except ValueError:
print("Only numbers are allowed")
guess_limit = 4
chances_left = 4
guess_taken = 0
while difficulty == "medium":
try:
random_number = random.randint(1, 20)
guess = int(input("Enter a number between 1 - 20: "))
guess_taken += 1
chances_left -= 1
print(f"You have {chances_left} guesses left")
if random_number == guess:
print("You got it right")
break
elif guess_taken == guess_limit:
print("Game Over")
break
else:
if guess > random_number:
print("Your guess was out of range")
else:
print("That was wrong")
except ValueError:
print("Only numbers are allowed")
guess_limit = 3
chances_left = 3
guess_taken = 0
while difficulty == "hard":
try:
random_number = random.randint(1, 50)
guess = int(input("Enter a number between 1 - 50: "))
guess_taken += 1
chances_left -= 1
print(f"You have {chances_left} guesses left")
if random_number == guess:
print("You got it right")
break
elif guess_taken == guess_limit:
print("Game Over")
break
else:
if guess > random_number:
print("Your guess was out of range")
else:
print("That was wrong")
except ValueError:
print("Only numbers are allowed") |
#!/bin/python
import sys
import copy
from cell import Cell
from board import Board
from minimax import getNextMove
from minimax import interfaceBoard
class DoubleCard():
def __init__(self):
self.board = Board()
self.turn = 0
self.prev_board = copy.deepcopy(self.board)
self.trace = True
self.prev_move = []
self.history = []
self.player_option = 1
self.ai_player = 99999
def start_menu(self):
print("Welcome to Double Card Game!")
while (True):
option = input("""============================
Select Game Mode:
1) Player VS Player
2) Player VS AI
Option: """)
self.flush()
if option == '1':
print("Player VS Player Mode Selected")
self.win_condition()
self.flush()
break
elif option == '2':
print("Player VS AI Mode Selected")
self.ai_condition()
self.flush()
self.win_condition()
self.flush()
break
else:
print("Invalid option selected!")
def ai_condition(self):
trace_text = "Do you want to have an output of the trace?(Y/N): "
choice_text = """Choose AI to start 1st or 2nd:
1) 1st
2) 2nd
Option: """
while(True):
choice=input(trace_text)
if choice in ['Y', 'N']:
if choice == 'Y':
self.trace = True
else:
self.trace = False
break
self.flush()
while(True):
self.flush()
choice=input(choice_text)
if choice in ['1', '2']:
self.ai_player = int(choice)
break
def win_condition(self):
choice_text = """Choose Player 1 Winning condition:
1) Colors
2) Dots
Option: """
while(True):
choice=input(choice_text)
if choice in ['1', '2']:
self.player_option = int(choice)
break
self.flush()
def letter_to_int(self, move):
letter_map = {'A':0, 'B':1, 'C':2, 'D':3, 'E':4, 'F':5, 'G':6, 'H':7}
return letter_map.setdefault(move, None)
def start(self):
self.first_load()
while True:
if self.history:
print ("Turn {}: Move placed is {}".format(self.turn, self.history[-1]))
print (self.board)
if self.turn == 40:
break
self.command_parser()
self.prev_board = copy.deepcopy(self.board)
print("Game End with Draw")
def first_load(self):
self.start_menu()
def print_history(self):
for x,y in enumerate(self.history):
print("""Turn {}:
Player {} : {}""".format(x+1,x%2+1,y))
def same_move(self, parsed_command):
prev_move = self.prev_move
if len(prev_move)!= 7:
return False
if parsed_command == prev_move:
return True
if set(parsed_command[0:4]) == set(prev_move[0:4]):
print(parsed_command[4])
if parsed_command[4] == prev_move[4]:
return True
return False
def move_prev_card(self, parsed_command):
prev_move = self.prev_move
if len(prev_move)!= 7:
prev_card = self.prev_move[2:4]
else:
prev_card = self.prev_move[5:7]
c1 = parsed_command[0:2]
c2 = parsed_command[2:4]
if prev_card == c1 or prev_card == c2:
return True
return False
def string_to_int(self, commands_list):
for x,y in enumerate(commands_list):
if y.isnumeric():
commands_list[x] = int(y)
return commands_list
def validate(self, cmds):
valid = True
move_type = len(cmds)
cmds = self.string_to_int(cmds)
if move_type == 1:
if cmds != "history": # View History
valid = False
elif move_type == 4: # Regular Move (eg. 0 7 A 1)
int_letter = self.letter_to_int(cmds[2])
if cmds[0] != 0:
valid = False
elif type(cmds[1]) != int:
valid = False
elif type(cmds[3]) != int:
valid = False
elif cmds[1] > 8 or cmds[1] <1:
valid = False
elif int_letter is None:
valid = False
elif cmds[3] > 12 or cmds[3] <1:
valid = False
elif move_type == 7: # Recycling move (eg. A 1 A 2 7 A 1)
int_letter_0 = self.letter_to_int(cmds[0])
int_letter_2 = self.letter_to_int(cmds[2])
int_letter_5 = self.letter_to_int(cmds[5])
if int_letter_0 is None:
valid = False
elif type(cmds[1]) != int:
valid = False
elif type(cmds[3]) != int:
valid = False
elif type(cmds[4]) != int:
valid = False
elif type(cmds[6]) != int:
valid = False
elif cmds[1] > 12 or cmds[1] <1:
valid = False
elif int_letter_2 is None:
valid = False
elif cmds[3] > 12 or cmds[3] <1:
valid = False
elif cmds[4] > 8 or cmds[4] <1:
valid = False
elif int_letter_5 is None:
valid = False
elif cmds[6] > 12 or cmds[6] <1:
valid = False
else:
valid = False
return valid
def command_parser(self):
curr_player = self.turn%2 + 1
curr_ai = (self.ai_player == curr_player)
if not curr_ai:
command = input("[{}'s Turn] Place your move: ".format("Player {}".format(curr_player)))
else:
ai_type = 0 if self.player_option == 1 else 1
if self.turn >= 24:
command = getNextMove(self.board, ai_type, show_stats=self.trace,recycling=True,prev_move=self.history[-1])
else:
command = getNextMove(self.board, ai_type, show_stats=self.trace)
# command = "0 2 A 1" # TODO place output of minimax algo here
print("[AI's Turn] Place your move: {}".format(command))
self.flush()
print ("{player} Input: {command}".format(player="Player" if not curr_ai else "AI" ,command=command))
parsed_command = command.split(' ')
if parsed_command[0] == 'history':
self.print_history()
return
if parsed_command[0] == 'export':
print(interfaceBoard(self.board))
return
if not self.validate(parsed_command):
self.illegal_move("Invalid command!")
return
elif parsed_command[0] == 0:
if len(parsed_command) != 4:
print("Invalid Move!")
return
if self.turn >= 24:
print("Cannot use Regular Moves!")
return
else:
start_cell = self.letter_to_int(parsed_command[2]) + (parsed_command[3]-1)*8
self.place_card(parsed_command[1], start_cell)
self.prev_move = parsed_command
self.history.append(command)
else:
if len(parsed_command) != 7 or self.turn <24:
print("Invalid Move!")
return
if self.same_move(parsed_command):
self.illegal_move("Same Move")
return
if self.move_prev_card(parsed_command):
self.illegal_move("Moving Same Card as Previous Move")
return
start_cell = self.letter_to_int(parsed_command[0]) + (parsed_command[1]-1)*8
neighbour_cell = self.letter_to_int(parsed_command[2]) + (parsed_command[3]-1)*8
new_cell = self.letter_to_int(parsed_command[5]) + (parsed_command[6]-1)*8
if self.remove_card(start_cell, neighbour_cell):
self.place_card(parsed_command[4], new_cell)
if self.board == self.prev_board:
self.illegal_move("Move did not change to the board")
self.turn -= 1
return
self.prev_move = parsed_command
self.history.append(command)
def check_win(self, cell_num):
directions =['vertical', 'horizontal', 'diag-left', 'diag-right']
wins = [0,0,0,0]
winning_nums = [2*3*5*7, 3*5*7*11, 5*7*11*13, 7*11*13*17]
for direction in directions:
x = self.tabulate(cell_num, direction)
for y,z in enumerate(x):
if list(filter(lambda x: z%x==0, winning_nums)):
# print("Possible win with {}".format(direction))
wins[y] = 1
return wins
def remove_card(self, start_cell, neighbour_cell):
# check if cells are linked
c1 = self.board.get(start_cell)
c2 = self.board.get(neighbour_cell)
def in_bound(cell_num):
return cell_num >= 0 and cell_num < 8*12
illegal = False
if c1.link == c2.id and c2.link == c1.id:
c1.clear()
c2.clear()
for c in [start_cell,neighbour_cell]:
if in_bound(c+8):
if self.board.get(c+8).occupied:
illegal = True
else:
illegal = True
if illegal:
self.illegal_move("Removal not possible")
return False
return True
def illegal_move(self, reason):
print("Illegal Move! - {}".format(reason))
self.board = copy.deepcopy(self.prev_board)
def tabulate(self, cell_num, direction):
red = 1
white = 1
cross = 1
circle = 1
primes = [2,3,5,7,11,13,17]
if direction == 'horizontal':
extend_cell_num = cell_num+3
if int(extend_cell_num / 8) != int(cell_num / 8):
extend_cell_num = (int(cell_num / 8)+1)*8-1
if direction == "vertical":
extend_cell_num = cell_num+3*8
if direction == 'diag-left':
extend_cell_num = cell_num+3*8+3
if direction == 'diag-right':
extend_cell_num = cell_num+3*8-3
for x in range(7):
curr_cell = None
if direction == 'vertical':
curr_cell_num = extend_cell_num-8*x
elif direction == 'horizontal':
curr_cell_num = extend_cell_num-x
if int(curr_cell_num / 8) != int(cell_num / 8):
continue
elif direction == 'diag-left':
curr_cell_num = extend_cell_num-8*x-x
if int(curr_cell_num / 8) != int(cell_num / 8)+3-x:
continue
elif direction == 'diag-right':
curr_cell_num = extend_cell_num-8*x+x
if int(curr_cell_num / 8) != int(cell_num / 8)+3-x:
continue
# check if out of board
if curr_cell_num >= 0 and curr_cell_num < 8*12:
curr_cell = self.board.get(curr_cell_num)
if curr_cell is None:
continue
if curr_cell.color is 'Red':
red *= primes[x]
elif curr_cell.color is 'White':
white *= primes[x]
if curr_cell.symbol == '\u2022':
circle *= primes[x]
elif curr_cell.symbol == '\u25E6':
cross *= primes[x]
return [red, white, circle, cross]
def place_card(self, variant, start_cell):
neighbour_cell = start_cell+1 if variant%2 == 1 else start_cell+8
if self.check_illegal(start_cell, neighbour_cell):
self.illegal_move("Placement not possible")
return
color = 'Red' if variant in [1,4,5,8] else 'White'
symbol = '\u25E6' if variant in [2,3,5,8] else "\u2022"
def opp_color(color):
return 'White' if color is 'Red' else 'Red'
def opp_symbol(symbol):
return "\u2022" if symbol == '\u25E6' else '\u25E6'
self.board.get(start_cell).fill(color, symbol, neighbour_cell, variant)
self.board.get(neighbour_cell).fill(opp_color(color), opp_symbol(symbol), start_cell, variant)
wins = self.check_win(start_cell)
wins.extend(self.check_win(neighbour_cell))
self.who_win(wins)
self.turn += 1
def who_win(self, result):
player = self.turn % 2 + 1
player1_win = False
player2_win = False
win_cases = [i for i, x in enumerate(result) if x == 1]
if [i for i in [0,1,4,5] if i in win_cases]:
if self.player_option == 1:
player1_win = True
else:
player2_win = True
if [i for i in [2,3,6,7] if i in win_cases]:
if self.player_option == 1:
player2_win = True
else:
player1_win = True
if player1_win and player2_win:
print("Player {} wins".format(player))
elif player1_win:
print("Player 1 wins")
elif player2_win:
print("Player 2 wins")
if player2_win or player1_win:
print(self.board)
exit()
def flush(self):
print(chr(27) + "[2J")
def check_illegal(self, start_cell, neighbour_cell):
# check if out of bound
def check_in_bound(cell):
return cell < 8*12 and cell >= 0
def floating_cell(cell):
if cell-8 <0:
return False
else:
return self.board.get(cell-8).occupied == False
def occupied_cell(cell):
return self.board.get(cell).occupied
if check_in_bound(start_cell) and check_in_bound(neighbour_cell):
if occupied_cell(start_cell) or occupied_cell(neighbour_cell):
# print("HERE OCCUPIED")
return True
if floating_cell(start_cell) or floating_cell(neighbour_cell):
if neighbour_cell - start_cell == 8:
return floating_cell(start_cell) and floating_cell(neighbour_cell)
# print("HERE FLOATING")
return True
if neighbour_cell - start_cell == 1:
return int(neighbour_cell/8) != int(start_cell/8)
return False
else:
return True
x = DoubleCard()
x.start()
|
#!/Users/amod/venv/bin/python
#Date: 27march 2020
# this program takes inputs fom the user and sorts them into numbers and strings
a = input("type anything")
b = input("type anything")
c = input("type anything")
d = input("type anything")
e = input("type anything")
f = input("type anything")
g = input("type anything")
h = input("type anything")
i = input("type anything")
j = input("type anything")
tuple = (a, b, c, d, e, f, g, h, i, j)
num = [i for i in tuple if i.isdigit()]
str = [i for i in tuple if i.isalpha()]
print(num)
print(str) |
#!/Users/amod/venv/bin/python
# Author Name : Amod gawade
# Date : 20 march 2020
print("Program start")
# Taking input from user
k = input("Enter a value for speed(in KmPH) : ")
# converting to miles per hour
m = int(k)/1.609
print("The speed in miles per hour is %.2f" % m)
print("Program ends")
|
#!/Users/amod/venv/bin/python
# Author name : Amod Gawade
# Date : 29 March 2020
print("Program starts")
# Taking input from user
num1 = input("Enter a Value : ")
# Calculating the sqrt of num1
square_root = int(num1)**0.5
print("The square root of %s is %f" % (num1, square_root))
print("Program ends")
|
#!/Users/amod/venv/bin/python
# Author : Amod Gawade
# Date:29 march 2020
print("Program Starts")
# Requesting the Inputs to add two numbers
a = input("Enter a value of A: ")
b = input("Enter a value of B: ")
# Performing the Arithmetic Addition
c = (int(a)+int(b))
# Printing the Result statements
print("The Addition of %s and %s is %d" % (a, b, c))
print("Program Ends")
|
list=[1,2,3,4,5,6,7,8,9]
def listdouble():
for i in range(len(list)):
if list[i]%2==1:
print('tek ededleri goster: ', list[i] )
else:
print('cut ededleri goster: ', list[i])
listdouble() |
x=3
y=50
def bolunme3():
for i in range(x,y):
if i%3==0:
print("three: ", [i])
bolunme3()
def bolunme5():
for i in range(x,y):
if i%5==0:
print("Five: ", [i])
bolunme5()
def bolunme3ve5():
for i in range(x,y):
if i%3==0 and i%5==0:
print("threeFive: ", [i])
bolunme3ve5()
def bolunmur():
for i in range(x,y):
if i%3!=0 and i%5!=0:
print( '3e ve 5e bolunmeyen ededler: ', [i])
bolunmur() |
shopping_list = ["milk", "ham", "spam", "pasta"]
item_to_find = "spam"
found_at = None
# for index in range(len(shopping_list)):
# if shopping_list[index] == item_to_find:
# found_at = index
# break
if item_to_find in shopping_list:
found_at = shopping_list.index(item_to_find)
if found_at is not None:
print("found at {}".format(found_at))
else:
print("{} not found".format(item_to_find))
|
"""Implement a base class for games created using PyGame."""
import pygame
class Game:
"""Base class for a PyGAme game."""
def __init__(self):
"""Initializes the game object."""
self.running = False
def run(self):
"""Runs the game."""
self.running = True
while self.running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
self.running = False |
################ PERFORMING PREPROCESSING OF INPUT TEXT ###################
def preprocess_text(df, column):
import re
for i in range(len(df)):
###### REMOVING SPECIAL CHARACTERS
df.loc[i, column] = re.sub(r'\W', ' ', str(df.loc[i, column]))
###### REMOVING ALL SINGLE CHARACTERS
df.loc[i, column] = re.sub(r'\s+[a-zA-Z]\s+', ' ', str(df.loc[i, column]))
###### REMOVING MULTIPLE SPACES WITH SINGLE SPACE
df.loc[i, column] = re.sub(r'\s+', ' ', str(df.loc[i, column]))
return df
############################# |
from unittest import TestCase
from recon import Reconciliation
from decimal import Decimal
class ReconciliationTest(TestCase):
"""Customer Account Reconciliation Tests"""
def setUp(self):
self.recon = Reconciliation()
def test_empty(self):
"""test that new/empty Reconcillation object has not security balances"""
self.assertEqual({}, self.recon.balance)
def test_one_item_non_zero(self):
"""test that reconcile does not return entry for security with zero balance"""
self.recon.add("WFM", 100)
self.assertEqual({'WFM': 100}, self.recon.balance)
def test_one_item_non_zero_with_reconcile(self):
"""test that reconcile does return entry for security with non-zero balance"""
self.recon.add("WFM", 100)
self.recon.subtract("WFM", 50)
self.assertEqual({'WFM': -50}, self.recon.reconcile())
def test_sample1(self):
"""test with sample data provided"""
self.recon.add('GOOG', '200')
self.recon.add('AAPL', '100')
self.recon.add('SP500', 175.75)
self.recon.add('Cash', 1000)
self.recon.subtract('AAPL', 100)
self.recon.add('Cash', 30000)
self.recon.add('GOOG', 10)
self.recon.subtract('Cash', 10000)
self.recon.add('Cash', 1000)
self.recon.subtract('Cash', 50)
self.recon.add('Cash', 50)
self.recon.add('TD', 100)
self.recon.subtract('Cash', 10000)
self.recon.subtract('GOOG', 220)
self.recon.subtract('SP500', 175.75)
self.recon.subtract('Cash', 20000)
self.recon.subtract('MSFT', 10)
actual = self.recon.reconcile()
expected = {}
expected['Cash'] = Decimal(8000)
expected['GOOG'] = Decimal(10)
expected['TD'] = Decimal(-100)
expected['MSFT'] = Decimal(10)
self.assertEqual(expected, actual)
|
#Problem link: https://www.spoj.com/problems/TEST/
#Time complexity: O(1)
#Space complexity: O(1)
ip = True
while True:
n = int(input())
if n==42:
break
print(n)
|
#Ask user for name
name =input("What is your Name? : ")
#Ask user for age
age =input("What is your age ? : ")
#ask user for city
city = input("What city do you live in ? : ")
#Ask user what they enjoy
love=input("What do you love doing? : ")
#Create output text
string = "Your name is {} and you are {}yrs old and live in {} and you love {}"
output = string.format(name,age,city,love)
#print output screen
print(output)
|
known_users=["Alice","Bob","Clair","Dan","Emma","Fred","George","Harry"]
while True:
print("Hey,Hi! My name is Rohit,")
name=input("What is your name").strip().capitalize()
if name in known_users:
print("Ooh, Hello {}".format(name))
remove=input("Would you like to delete your name from system(y/n): ").lower()
if remove =="y":
known_users.remove(name)
print(known_users)
elif remove=="n":
print("No problem,You can stay")
else:
print("Hmm I don't think i have met you yet {}".format(name))
add= input("Would you like to be in our system(y/n):").strip().lower()
if add =="y":
known_users.append(name)
print(known_users)
elif add=="n":
print("No problem, See you")
|
"""
itertools提供了非常有用的用于操作迭代对象的函数
"""
# "无限"迭代器
"""
count(n) :无限数自然数,间隔为n
cycle(str) :无限重复str
repeat(t, n) :重复t n次
"""
import itertools
natuals = itertools.count(1)
# for n in natuals:
# print(n)
# 使用takewhile()函数截取有限序列
ns = itertools.takewhile(lambda x: x <= 10, natuals)
print(list(ns))
"""Chain()将一组迭代对象*串联*起来,形成一个更大的迭代器"""
for c in itertools.chain('ABC', 'XYZ'):
print(c)
"""groupby()把迭代器中相邻的重复元素挑出来放在一起"""
for key, group in itertools.groupby('AAABBBCCAAA'):
print(key, list(group)) # 将相同的元素当作一组
for key, group in itertools.groupby('AaaBBbcCAAa', lambda c: c.upper()):
print(key, list(group))
"""
itertools模块提供的全部是处理迭代功能的函数,它们的返回值不是list,而是Iterator
只有用for循环迭代的时候才真正计算。
""" |
"""
用sayncio提供的@asyncio.coroutine 可以把一个generator标记为coroutine类型,
然后在coroutine内部用yield from调用另一个coroutine实现异步操作
为了简化并更好地标记异步IO,从Python3.5开始引入新的语法saync和await,可以让coroutine的代码更简洁易读
具体规则:
1. asyncio.coroutine 替换为 async
2. yield from 替换为 await
"""
# 与sayncio对比
import asyncio
async def hello():
print('Hello world!')
r = await asyncio.sleep(1)
print("hello again")
|
"""
Iterator=map(func, Iterable)
"""
from functools import reduce
def f(x):
return x*x
r = map(f, [1, 2, 3, 4, 5, 6, 7, 8, 9])
print(list(r))
# int->str
print(list(map(str, [1, 2, 3, 4, 5, 6, 7, 8, 9])))
"""
reduce(f,[x1, x2, x3, x4]) = f(f(f(x1,x2),x3),x4)
"""
def add(x, y):
return x+y
print(reduce(add, [1, 3, 5, 7, 9]))
def fn(x, y):
return x*10+y
print(reduce(fn, [1, 3, 5, 7, 9]))
def str2int(s):
def fn(x, y):
return x*10+y
def char2num(s):
return{'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5,
'6': 6, '7': 7, '8': 8, '9': 9}[s]
return reduce(fn, map(char2num, s))
print(str2int('4568456'))
# return list[(int)]
def char2num(s):
return {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5,
'6': 6, '7': 7, '8': 8, '9': 9}[s]
def str2int1(s):
return reduce(lambda x, y: x*10+y, map(char2num, s))
""" 练习 """
# Qustion 1
def normalize(name):
L = ''
# i = 0
# L.append(name[i].upper())
# append会使str断开,使用str的+操作
# L = L + name[i].upper()
# while i < len(name)-1:
# i = i + 1
# L=L + name[i].lower()
L = L + name[0].upper()
L = L + name[1:].lower()
return L
L1 = ['adam', 'jACk', 'berT']
print(list(map(normalize, L1)))
# Qustion 2
def prod(L):
return reduce(lambda x, y: x*y, map(char2num, L))
print(prod('235'))
# Qustion 3
def str2float(s):
s1 = s.split('.')
def char2int1(s):
return {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5,
'6': 6, '7': 7, '8': 8, '9': 9}[s]
flo = reduce(lambda x, y: x*10+y, map(char2int1, s1[0]))
flo = flo + 0.1*reduce(lambda x, y: x*pow(10, -1)+y, sorted(list(map(char2int1, s1[1])), reverse=True))
return flo
print(str2float('123.456'))
lis = [4, 5, 6]
lis.sort()
print(lis) |
"""
可迭代对象(Iterable):可以直接作用于for循环的数据类型
包括:
- 集合数据类型,如list tuple dict set str
- generator,() and generator function(yield)
"""
from collections import Iterable
from collections import Iterator
"""判断一个对象是否是Iterable对象"""
print(isinstance((x for x in range(10)), Iterable))
print(isinstance([], Iterable))
print(isinstance({}, Iterable))
print(isinstance('abc', Iterable))
print(isinstance(100, Iterable))
"""判断一个对象是否是Iterator"""
print(isinstance((x for x in range(10)), Iterator))
print(isinstance([], Iterator))
print(isinstance({}, Iterator))
print(isinstance('abc', Iterator))
print(isinstance(100, Iterator))
"""
能够直接使用for循环是 Iterable
能够调用next()函数是 Iterator
list dict str 是Irerable,但不是Iterator
可以通过调用iter()使它们变成Iterator
for循环本质就是先iter(Iterable),再不断调用next(i)
"""
print(isinstance(iter({}), Iterator))
|
"""
TCP是建立可靠连接,并且通信双方都可以以流的形式发送数据
相比TCP,UDP则是面向无连接的协议
使用UDP协议时,不需要建立连接,只需要知道对方的IP地址和端口号,就可以直接发数据包。但是,能不能到达就不知道了。
虽然用UDP传输数据不可靠,但它的优点是和TCP比,速度快,对于不要求可靠到达的数据,就可以使用UDP协议。
"""
import socket
# 使用UDP协议
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
# 绑定端口
s.bind(('127.0.0.1', 9999))
print('Bind UDP on 9999')
while True:
# 接收数据
data, addr = s.recvfrom(1024)
print('Received from %s:%s. ' % addr)
# 使用UDP,发送要用sendto,而且还要指明地址
s.sendto(b'hello, %s' % data, addr)
"""
UDP与TCP的端口不冲突,可以各自绑定!
"""
|
import sys
class Contador():
def __init__(self,x=0,y=0):
self.__x=x
self.__y=y
def get_x(self):
return self.__x
def get_y():
return self.__y
def set_incremento(self, incremento_x,incremento_y):
self.incremento_x=get_x()+=1
self.incremento_y=get_y()+=1
return
def set_decrecimiento(self,decrecimiento_x,decrecimiento_y):
sel.drecrecimiento_x=get_x()+=(-1)
self.decrecimiento_y=get_y()+=(-1)
return
print(set_incremento(incremento_x))
print(set_incremento(incremento_y))
print(set_decrecimiento(decrecimiento_y))
print(set_decrecimiento(decrecimiento_x))
|
" Module containing a generator of Fibonacci sequence list."
import numpy as np
def fibo(f_seq):
"""Returns list of FIbonacci sequence elements.
Parameters:
list *f_seq* -- list of Fibonacci sequence elements already computed.
Return:
list of FIbonacci sequence elements """
return np.append(f_seq,f_seq[-1]+f_seq[-2])
|
#列
'''try:
print(a)
except: #通吃,不管你遇到什么问题都会处理
print('你好皮!')
else:
print('damon 你可以啊--这么皮!!')'''
#列2
'''try:
print(a)
finally:
print('damon 你可以啊--这么皮!!') '''''
#列3
'''try:
print(a)
except:
print('皮一下')
finally:
pass
list_1=[1,2,3,4]
for i in range(5):
print(list_1[i]) '''
#列4
'''try:
print(a)
except NameError as e: #except通吃,不管你遇到什么问题都会处
print("你这个捣蛋鬼,我帮你处理的错误是%s"%e)
print('你好皮!')
finally:
print('damon 你可以啊--这么皮!!') '''
#列5
'''try:
print(a)
except:
print('你怎么这么可爱')
finally:
print("你真讨厌") '''
#列6
'''try:
file=open("aa.txt",'r+')
except Exception as e:
print("错误是",e)
finally:
file.close() '''
#列7
'''try:
file=open("test_1.txt",'r+')
except Exception as e:
print("错误是",e)
finally:
file.close()
print(file.closed) '''
#第一种异常
try:
#try下面是监控你觉得可能会有问题的代码,或者是可能会出现一些违规操作的代码
pass
except:
#excapt下面是针对try监控你的代码出现异常的处理
pass
#第二种异常
try: #关键字
#try下面是监控你觉得可能会有问题的代码,或者是可能会出现一些违规操作的代码
pass
except:
#excapt下面是针对try监控你的代码出现异常的处理
pass
finally:
#finally下面是针对不管你有没有发现异常,我都要进行finally下面的代码
pass
#第三种异常
try: #关键字
#try下面是监控你觉得可能会有问题的代码,或者是可能会出现一些违规操作的代码
pass
except:
#excapt下面是针对try监控你的代码出现异常的处理
pass
else:
#如果异常发生就不执行else下面的代码.如果异常发生我就执行else下面的代码
pass
#第四种异常
try:
pass
finally:
pass
#适合各位--》print() 万能的print()
#logging-->日志处理
#debug
'''def add(a,b):
result=a+b
return result
add(4,5) '''
|
def my_function():
my_list = [0, 1, 2, 3, 4, 5]
list_length = len(my_list)
if list_length > 0:
print('list length is greater')
else:
print('list length is lesser')
# try block check whether the statement is executable
try:
list_length1 = len(my_list1)
print(list_length1)
# except block handles the error occurs in statement
except:
print('There is no list in code')
# finally block print the statement whether the statement is true or false
finally:
print('Finally printing list: ', my_list)
print(list_length)
my_function() |
import math
print(" ********************* WELCOME TO PYTHON CALCULATOR ************************************")
print(" ")
print("PlEASE ENTER YOUR SELECTION")
print("** ADDITION --> 1 ** \n** SUBTRACTION --> 2 ** \n** MULTIPLICATION --> 3 ** \n** DIVISION --> 4 ** \n** POWER --> 5 ** \n** ROOT --> 6 ** ")
print(" ")
Select=input("Enter your Selection")
while Select!="Q":
if Select == "1":
print("ADDITION")
first=int(input("Enter the First Number"))
second = int(input("Enter the Second Number"))
print("ADDITION OF ",first ,"+",second,":",first+second)
print(" ")
Select=input("Please Enter your Next SELECTION")
if Select == "2":
print("SUBTRACTION")
first = int(input("Enter the First Number"))
second = int(input("Enter the Second Number"))
print("SUBTRACTION OF ",first ,"-",second,":",first- second)
print(" ")
Select = input("Please Enter your Next SELECTION")
if Select == "3":
print("DIVISION")
first = int(input("Enter the First Number"))
second = int(input("Enter the Second Number"))
print("DIVISION OF ",first ,"/",second,":",first / second)
print(" ")
Select = input("Please Enter your Next SELECTION")
if Select == "4":
print("MULTIPLICATION")
first = int(input("Enter the First Number"))
second = int(input("Enter the Second Number"))
print("MULTIPLICATION OF ",first ,"*",second,":",first * second)
print(" ")
Select = input("Please Enter your Next SELECTION")
if Select == "5":
print("SQAURE")
first = int(input("Enter the First Number"))
second = int(input("Enter the Second Number"))
print(" SQAURE IS ",pow(first,second))
print(" ")
Select = input("Please Enter your Next SELECTION")
if Select == "6":
print("ROOT")
first = int(input("Enter the Number for square root"))
print("SQUARE ROOT OF",first,": ",math.sqrt(first))
print(" ")
Select = input("Please Enter your Next SELECTION")
else:
print("YOU HAVE GIVEN WRONG CHOICE")
print(" !!!!!!! Please Try Again !!!!!!!")
Select = input("Please Enter your Next SELECTION")
|
#Crear menu con 3 opciones
import os
def Numeros():
pos=0
neg=0
cero=0
cantidad=int(input("Ingrese cantidad de números a ingresar: "))
for i in range(cantidad):
n=int(input(str(i+1)+".-Ingresa un número: "))
if (n>0):
pos+=1
elif (n<0):
neg+=1
else:
cero+=1
print("cantidad de números positivos: "+str(pos))
print("cantidad de números negativos: "+str(neg))
print("cantidad de 0: "+str(cero))
pausa=input("Ingrese cualquier tecla para continuar...")
def Personas():
sum=0
cantidad=int(input("Ingrese cantidad de personas a ingresar: "))
for i in range(cantidad):
nom=input(str(i) + ".-Ingresa un nombre: ")
edad=int(input(str(i)+ ".-Ingrese la edad: "))
sum=sum+edad
print("El promedio de las edades es: " + str(sum/cantidad))
pausa=input("Ingrese cualquier tecla para continuar...")
seguir=True
while (seguir):
os.system('cls')
print("1. Numeros")
print("2. Datos Personales")
print("3. Finalizar")
op=int(input("Digite opción 1,2,3: "))
if(op==1):
Numeros() #Invocamos un metodo
if (op==2):
Personas()
if (op==3):
print("Programa Finalizado")
pausa=input("Ingrese cualquier tecla para continuar...")
break |
def get_indices_of_item_weights(weights, length, limit):
"""
YOUR CODE HERE
"""
# initiaize a cache
cache = {}
# will be increment to make representing indexes
index = 0
# store weights as keys and indexes as values in cache
for weight in weights:
cache[weight] = index
index += 1
# traverse and stop at end of input array
for i in range(length):
# key to find solution case
key = limit - weights[i]
# check if a solution is possible
if key in cache:
# return values of solution
return (cache[key], i) |
###START###
##I'm very sorry this code doesn't work, but I gave it my best shot!##
def main():
year_won = {}
number_of_wins = {}
year = int(input("What year do you wanna check? "))
infile = open("worldserieswinners.txt", "r")
team_num_wins(infile, number_of_wins)
assign_years(infile, year_won)
if year == 1904 or year == 1944:
print("Sorry, the World Series wasn't played that year.")
else:
if year in year_won:
print(number_of_wins.popitem(), "won", year_won.pop(year))
def team_num_wins(infile, number_of_wins):
winners_txt = infile.readlines()
for line in winners_txt:
if line in number_of_wins:
number_of_wins[line] += 1
else:
number_of_wins[line] = 1
##This part COMPLETELY stumped me, Dr. B! I found a github article that
##walked through someone's solution to the problem, but I wanted to
##make it work for myself; I'm pretty sure it's wrong, ha! :) ##
def assign_years(infile, year_won):
winner_txt = infile.readline().rstrip("\n")
for line in winner_txt:
for i in range(1903, 2008):
year_won[i] =
main() |
def ArmN(x):
sum=0
t=x
while(t>0):
d=t%10
sum+=d**3
t=t//10
if sum==x:
return 'Armstrong number'
else:
return 'Not A N'
x=int(input())
print(ArmN(x))
|
class hash_map(object):
aMap = []
def __init__(self, table_size):
self.table_size = table_size
for i in range(0, self.table_size):
self.aMap.append([])
def put(self, key,value):
if key is None or value is None :
raise ValueError('Please pass a valid key/value')
hash_location = hash(key) % len(self.aMap)
self.aMap[hash_location].append(value)
def get(self, key):
if key is None :
raise ValueError('Please pass a valid key')
hash_location = hash(key) % len(self.aMap)
return self.aMap[hash_location]
if __name__ == '__main__':
hashmap1 = hash_map(100)
key,value = raw_input('Please enter a key and value... ').split()
hashmap1.put(key, value)
Key = raw_input('Please enter a key whose value is to be checked... ')
print hashmap1.get(Key) |
vs2=list(input())
if len(vs2)%2==0:
vs2[int(len(vs2)/2)] ='*'
vs2[int(len(vs2)/2)-1]='*'
else:
vs2[int(len(vs2)/2)] ='*'
for i in range(0,len(vs2)):
print(vs2[i],end='')
|
h3,k3=map(int,input().split())
ik=h3+k3
if(ik%2==0):
print("even")
else:
print("odd")
|
g1=int(input())
if(g1>1 and g1<10):
print("yes")
else:
print("no")
|
varshaa=int(input())
shav=0
while varshaa>0:
varshaa=varshaa//10
shav=shav+1
print(shav)
|
ab1=int(input())
ba11=0
l=[]
for ab1 in range(1,ab1+1):
l.append(ab1)
for ab1 in range(len(l)):
for ab1 in range(ab1+1,len(l)):
ba11+=1
print(ba11)
|
"""Author: Cole Howard
Email: [email protected]
neuron.py is a basic linear neuron, that can be used in a perceptron
Information on that can be found at:
https://en.wikipedia.org/wiki/Perceptron
It was written as a class specifically for network ()
Usage:
From any python script:
from neuron import Neuron
API:
update_weights, fires are the accessible methods
usage noted in their definitions
"""
from math import e
from numpy import append as app
from numpy import dot
class Neuron:
""" A class model for a single neuron
Parameters
----------
vector_size : int
Length of an input vector
target : int
What the vector will associate with its weights. It will claim this
is the correct answer if it fires
sample_size : int
Total size of sample to be trained on
answer_set: list
The list of correct answers associated with the training set
Attributes
----------
threshold : float
The tipping point at which the neuron fires (speifically in relation
to the dot product of the sample vector and the weight set)
weights : list
The "storage" of the neuron. These are changed with each training
case and then used to determine if new cases will cause the neuron
to fire. The last entry is initialized to 1 as the weight of the
bias
expected : list
Either 0's or 1's based on whether this neuron should for each of the
vectors in the training set
guesses : list
Initialized to 0, and then updated with each training vector that
comes through.
"""
def __init__(self, vector_size, target, sample_size, answer_set):
self.threshold = .5
self.answer_set = answer_set
self.target = target
self.weights = [0 for x in range(vector_size + 1)]
self.weights[-1] = 1 # Bias weight
self.sample_size = sample_size
self.expected = [0 if y != self.target else 1 for y in self.answer_set]
self.guesses = [0 for z in range(self.sample_size)]
def train_pass(self, vector, idx):
""" Passes a vector through the neuron once
Parameters
----------
vector : a list
Training vector
idx : an int
The position of the vector in the sample
Returns
-------
None, always
"""
if self.expected == self.guesses:
return None
else:
error = self.expected[idx] - self.guesses[idx]
if self.fires(vector)[0]:
self.guesses[idx] = 1
else:
self.guesses[idx] = 0
self.update_weights(error, vector)
return None
def _dot_product(self, vector):
""" Returns the dot product of two equal length vectors
Parameters
----------
vector : list
Any sample vector
Returns
-------
float
The sum for all of each element of a vector multiplied by its
corresponding element in a second vector.
"""
if len(vector) < len(self.weights):
vector = app(vector, 1)
return dot(vector, self.weights)
def _sigmoid(self, z):
""" Calculates the output of a logistic function
Parameters
----------
z : float
The dot product of a sample vector and an associated weights
set
Returns
-------
float
It will return something between 0 and 1 inclusive
"""
if -700 < z < 700:
return 1 / (1 + e ** (-z))
elif z < -700:
return 0
else:
return 1
def update_weights(self, error, vector):
""" Updates the weights stored in the receptors
Parameters
----------
error : int
The distance from the expected value of a particular training
case
vector : list
A sample vector
Attributes
----------
l_rate : float
A number between 0 and 1, it will modify the error to control
how much each weight is adjusted. Higher numbers will
train faster (but risk unresolvable oscillations), lower
numbers will train slower but be more stable.
Returns
-------
None
"""
l_rate = .05
for idx, item in enumerate(vector):
self.weights[idx] += (item * l_rate * error)
def fires(self, vector):
""" Takes an input vector and decides if neuron fires or not
Parameters
----------
vector : list
A sample vector
Returns
-------
bool
Did it fire? True(yes) or False(no)
float
The dot product of the vector and weights
"""
dp = self._dot_product(vector)
if self._sigmoid(dp) > self.threshold:
return True, dp
else:
return False, dp
|
import time
import control
import sensor
## DEFAULT SETTINGS ###
TEMPERATURE = 25
HUMIDITY = 0.8
HOURS_LIGHT = 12
MINUTES_BEFORE_CHECK = 1
while True:
temperature = sensor.get_temperature()
humidity = sensor.get_humidity()
print("current temperature % (C)", str(temperature))
print("current humidity %", str(humidity))
# TEMPERATURE CHECK
if temperature < TEMPERATURE:
control.heat()
elif temperature > TEMPERATURE:
control.cool()
# HUMIDITY CHECK
if humidity < HUMIDITY:
control.humidify()
time.sleep(60*MINUTES_BEFORE_CHECK) |
#!/usr/bin/env python
import random
with open('groupchoiser/eleves.txt') as x:
names_list = x.read().split()
# is the name marked
def is_name_marked(student_name):
return student_name[-1:] == "+"
def is_group_marked(group):
for name in group:
if is_name_marked(name):
return True
return False
class Students:
""" The object students manipulates a list of students and helps forming groups of students
being able of creating group taking in consideration marked studens + , or not !
Marked stutents with plus '+' should not be paired with another marked students, unless the maximum
number allowed is different than one.
"""
def __init__(self):
self.members = names_list
self.len = len(names_list)
self.all_groups = []
self.group = {}
# does the group contain a marked student?
def dispatch_students(self, max_number_per_group):
# iterate over the self.names_list
remaining_students = list(self.members)
# shuffle the list to avoid the same results at each run
random.shuffle(remaining_students)
# start a new group
current_group = []
# let<s take turns until no one remains.. someone may not be part of a group and alone but nobody likes him anyways
while len(remaining_students) > 0:
# take the first student from the list
current_student = remaining_students.pop(0)
if is_name_marked(current_student) and is_group_marked(current_group):
# cant do anything : push if back at the end of the list
remaining_students.append(current_student)
else:
if len(current_group) >= max_number_per_group:
# once we reach enought students, we close the group and create a new one
self.all_groups.append(current_group)
current_group = []
# add the student to the current group
current_group.append(current_student)
# end while
self.all_groups.append(current_group)
return self.all_groups
def groups_json(self):
i = 1
for groups in self.all_groups:
self.group['Group#' + str(i)] = groups
i += 1
|
n=input()
if len(n)>7 and len(n)%2!=0:
print(n[(len(n)//2)-1:(len(n)//2)+2])
else:
print("enter a valid odd numbered string") |
word=input()
count=1
length=""
if len(word)>1:
for i in range(1,len(word)):
if word[i-1]==word[i]:
count+=1
else :
length += word[i-1]+" repeats "+str(count)+", "
count=1
length += ("and "+word[i]+" repeats "+str(count))
else:
i=0
length += ("and "+word[i]+" repeats "+str(count))
print (length) |
import letterboxd
from rotten_tomatoes_client import RottenTomatoesClient
import os
import pandas as pd
# create and save database to store multiple user's data
database_name = 'letterboxd'
os.system('mysql -u root -pcodio -e "CREATE DATABASE IF NOT EXISTS '
+ database_name + '; "')
os.system('mysql -u root -pcodio -e "CREATE TABLE IF NOT EXISTS '
+ 'letterboxd.all_users(username VARCHAR(255), average_difference'
+ ' FLOAT(3,2), PRIMARY KEY (username)); "')
letterboxd.save_database(database_name)
# get the username and letterboxd ratings from their ratings.csv
lbxd_ratings = 'ratings1.csv'
username = letterboxd.user_input()
# check if the user is returning
response = input('Are providing new data? [Y/N]: ').lower()
filename = username + ".csv"
if response == 'n':
ratings_df = letterboxd.returning_user(username, database_name)
else:
# create dataframe containing user movie ratings and the RT score
ratings_df = letterboxd.user_ratings_to_df(lbxd_ratings)
ratings_df = letterboxd.user_and_critic_df(ratings_df)
# outputs users results
letterboxd.user_output(ratings_df)
# get the average difference and put the user's info into the database
letterboxd.user_data_to_database(database_name, username, ratings_df)
# provide user with visualization of movie taste
letterboxd.plot_movie_ratings(username, ratings_df)
|
from support import get_input_file
def main():
lines = get_input_file.ReadLines(True)
##### PART 1 #####
print("\nDay04 Part 1:\n")
res = validate_numbers(lines, 25, False)
print("The first number to fail the encryption scheme is " + str(res))
##### PART 2 #####
print("\nDay04 Part 2:\n")
res = find_contiguous_set(lines, res)
print("The index of the set is [" + str(res[0]) + ", " + str(res[1]) + "]")
val = find_largest_in_set(lines, 1, res[0], res[1])[0] + find_smallest_in_set(lines, 1, res[0], res[1])[0]
print("The sum of the values at that index is " + str(val))
def find_largest_in_set(numbers, count=1, lower_bound=0, upper_bound= -1):
if upper_bound < 0:
upper_bound = len(numbers) -1
res = []
for i in range(lower_bound, upper_bound + 1):
if len(res) < count:
res.append(numbers[i])
else:
m_val = min(res)
if numbers[i] > m_val:
res.remove(m_val)
res.append(numbers[i])
return res
def find_smallest_in_set(numbers, count=1, lower_bound=0, upper_bound= -1):
if upper_bound < 0:
upper_bound = len(numbers) -1
res = []
for i in range(lower_bound, upper_bound + 1):
if len(res) < count:
res.append(numbers[i])
else:
m_val = min(res)
if numbers[i] < m_val:
res.remove(m_val)
res.append(numbers[i])
return res
def find_contiguous_set(numbers, target_sum):
lower_bound = 0
upper_bound = 1
cur_sum = get_sum_in_subset(numbers, lower_bound, upper_bound)
while(cur_sum != target_sum):
if cur_sum > target_sum:
lower_bound = lower_bound + 1
else:
upper_bound = upper_bound + 1
if lower_bound >= upper_bound or upper_bound > len(numbers):
print("Find Contiguous Set failed")
return -1
cur_sum = get_sum_in_subset(numbers, lower_bound, upper_bound)
return [lower_bound, upper_bound]
def get_sum_in_subset(numbers, lower, upper):
sum_val = 0
for i in range(lower, upper + 1):
sum_val = sum_val + numbers[i]
return sum_val
def validate_numbers(lines, depth, debug = False):
numbers = []
for line in lines:
if debug:
print("Testing for Number: ")
print(line)
if len(numbers) < depth:
numbers.append(line)
else:
if( not validate_sum_exists(numbers, line, debug)):
return line
else:
numbers.pop(0)
numbers.append(line)
return -1
def validate_sum_exists(numbers, num, debug = False):
for t_num in numbers:
for t_num2 in numbers:
if debug: print("Testing " + str(t_num) + " : " + str(t_num2) + " for " + str(num))
if t_num + t_num2 == num and t_num != t_num2:
return True
return False
if __name__ == "__main__":
main()
|
def binarySearch(list,f):
start = 0
end = len(list)-1
while(start<=end):
mid = (start + (end-start) // 2)
if list[mid] is f:
return f
elif list[mid]> f:
end = mid-1
elif list[mid]< f:
start = mid+1
list = [1,2,3,4,5,6 ,7,8,9]
f=int(input("Find this number :"))
r = binarySearch(list,f)
if r is -1:
print("Not found")
else:
print(r) |
def subsetsUtil(list,subsets,index):
print(subsets)
for i in range(index,len(list)):
subsets.append(list[i])
subsetsUtil(list,subsets,i+1)
subsets.pop(-1)
# print("check")
#print(subsets)
# print("Done")
# else:
# print(subsets)
return
def subset(list):
# global res
subsets = []
index = 0
subsetsUtil(list,subsets,index)
s = input()
list = [s[i] for i in range(len(s))]
subset(list)
|
def fact(n):
if n <=1:
return 1
else:
return n*fact(n-1)
if __name__ == '__main__':
n = int(input())
r = fact(n)
print(r) |
a = [2,3,4,5,6,7]
val = 34
pos = 0
temp = 0
for i in range(pos,len(a)):
if i>= pos:
temp = int(a[i])
a[i]=val
val=temp
a.append(temp)
print(a) |
#Programme to take two input numbers from user and print addend of the inputs
print("Watch me amaze and stupify by adding two numbers.")
num1=int(input('Hey... enter your first number...'))
num2=int(input('...alright now your second...'))
num3=str(num1-num2)
print("By my deductive reasoning, your number is - " +num3+"?")
#above line got me thinkings, what is preffered way to create the simple str for the print statement
#% formatting is an old alternative to the above, but it's clunkier.
#str.format() was a pretty good alternative, assigning variables, but seemed a bit clunky still (lot of extra typing vs '+')
#f-strings are a recent python 3.6 feature but very nice, as you can see, really simplifies the str
print(f"By my deductive reasoning, your number is - {num1-num2}?")
|
###Initialising dict and list and choice
#some_dict = {"StudentName":"Keith", "Subjects": ["Web App Development", "Programming and Scripting", "Computer Architecture"]}
list_of_dicts = []
choice = ''
#function to prompt user for what they would like to do
def prompt():
#First I'm just using simple print, then store user input in user_in
print("What would you like to do?\n (a) \n (v) \n (q)\n")
user_in=input("Type a or v or q: ")
print(f"You chose {user_in}")
return user_in
def showSubjects(subjects):
print("\tName \tGrade")
for subject in subjects:
print(f"\t{subject['name']} \t{subject['grade']}")
#simple function that just shows dictionary of students
def view(students):
for student in students:
print("student name")
print(student['StudentName'])
showSubjects(student['Subjects'])
#function to add a new student
def add():
new_student = {}
new_student["StudentName"]=str(input("Enter a student name: "))
new_student["Subjects"]=subjects()
return new_student
#function to exit loop
def quit():
return 0
#function to add subjects per user
def subjects():
subject_list = []
new_subject = str(input("Enter your subjects (blank to stop)"))
while(new_subject != ''):
subject = {}
subject["name"] = new_subject
subject["grade"] = int(input('Enter a grade:'))
subject_list.append(subject)
new_subject = str(input("Enter your subjects (blank to stop)"))
print(subject_list)
return subject_list
choice = prompt()
while choice.lower() != 'q':
#print(list_of_dicts)
if choice.lower()=="a":
list_of_dicts.append(add())
if choice.lower()=="v":
view(list_of_dicts)
choice = prompt()
view(list_of_dicts)
'''
user_choice = prompt()
#I don't care if user types in a or A, so casting str to all lowercase
if(user_choice.lower()=="a"):
print("A")
elif(user_choice.lower()=="v"):
print(f"{some_dict}")
elif(user_choice.lower()=="q"):
print("Q")
''' |
#!python
def merge(items1, items2):
"""Merge given lists of items, each assumed to already be in sorted order,
and return a new list containing all items in sorted order.
TODO: Running time: ??? Why and under what conditions?
TODO: Memory usage: ??? Why and under what conditions?"""
# TODO: Repeat until one list is empty
# TODO: Find minimum item in both lists and append it to new list
# TODO: Append remaining items in non-empty list to new list
def merge_sort(items):
"""Sort given items by splitting list into two approximately equal halves,
sorting each recursively, and merging results into a list in sorted order.
TODO: Running time: ??? Why and under what conditions?
TODO: Memory usage: ??? Why and under what conditions?"""
# TODO: Check if list is so small it's already sorted (base case)
# TODO: Split items list into approximately equal halves
# TODO: Sort each half by recursively calling merge sort
# TODO: Merge sorted halves into one list in sorted order
if len(items) > 1:
mid = len(items)//2
first_half = items[:mid]
second_half = items[mid:]
# Sorting the first half
merge_sort(first_half)
# Sorting the first half
merge_sort(second_half)
x = y = z = 0
# Copies the date to temp arrays first_half[] and second_half[]
while x < len(first_half) and y < len(second_half):
if first_half[x] < second_half[y]:
items[z] = first_half[x]
x += 1
else:
items[z] = second_half[y]
z += 1
# Checks to see if any elements are left out.
while x < len(first_half):
items[z] = second_half(x)
x += 1
z += 1
while y < len(second_half):
items[z] = second_half[y]
y += 1
z += 1
# Prints the list of items
def printList(items):
for x in range(len(items)):
print(items[x], end=" ")
print()
if __name__ == '__main__':
items = [100, 5, 1, 20, 30, 40, 80, 100, 30, 40]
print("The Given array is", end="\n")
print(items)
merge_sort(items)
print("the Sorted array is: ", end="\n")
print(items)
# def partition(items, low, high):
# """Return index `p` after in-place partitioning given items in range
# `[low...high]` by choosing a pivot (TODO: document your method here) from
# that range, moving pivot into index `p`, items less than pivot into range
# `[low...p-1]`, and items greater than pivot into range `[p+1...high]`.
# TODO: Running time: ??? Why and under what conditions?
# TODO: Memory usage: ??? Why and under what conditions?"""
# # TODO: Choose a pivot any way and document your method in docstring above
# # TODO: Loop through all items in range [low...high]
# # TODO: Move items less than pivot into front of range [low...p-1]
# # TODO: Move items greater than pivot into back of range [p+1...high]
# # TODO: Move pivot item into final position [p] and return index p
# def quick_sort(items, low=None, high=None):
# """Sort given items in place by partitioning items in range `[low...high]`
# around a pivot item and recursively sorting each remaining sublist range.
# TODO: Best case running time: ??? Why and under what conditions?
# TODO: Worst case running time: ??? Why and under what conditions?
# TODO: Memory usage: ??? Why and under what conditions?"""
# # TODO: Check if high and low range bounds have default values (not given)
# # TODO: Check if list or range is so small it's already sorted (base case)
# # TODO: Partition items in-place around a pivot and get index of pivot
# # TODO: Sort each sublist range by recursively calling quick sort
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.