text
stringlengths 37
1.41M
|
---|
city_name = "Istanbul, Turkey"
pop_1927 = 691000
pop_2017 = 15029231
pop_change = (pop_2017 - pop_1927) / pop_1927
percentage_gr = pop_change * 100
annual_gr = percentage_gr / (2017 - 1927)
print(annual_gr)
def population_growth(year_one, year_two, population_one, population_two):
growth_rate = (((population_two - population_one)/population_one)*100)/(year_two - year_one)
return growth_rate
set_one = population_growth(1927, 2017, pop_1927, pop_2017)
print(set_one)
pop_1950 = 983000
pop_2000 = 8831800
set_two = population_growth(1950, 2000, pop_1950, pop_2000)
print(set_two)
print(city_name + " had an annual population growth between 1927-2017 of " + str(set_one) + '%')
print(city_name + " had an annual population growth between 1950-2000 of " + str(set_two) + '%')
|
class Circle:
pi = 3.14
def area(self, radius):
return Circle.pi * radius ** 2
circle = Circle()
pizza_area = circle.area(12 / 2)
teaching_table_area = circle.area(36 / 2)
round_room_area = circle.area(11460 / 2)
print(pizza_area)
print(teaching_table_area)
print(round_room_area)
# Constructors
class Circle:
pi = 3.14
# Add constructor here:
def __init__(self, diameter):
print("New circle with diameter: {diameter}".format(diameter=diameter))
teaching_table = Circle(36)
# Instance Variables
class Store:
pass
alternative_rocks = Store()
isabelles_ices = Store()
alternative_rocks.store_name = "Alternative Rocks"
isabelles_ices.store_name = "Isabelle's Ices"
# Attribute Functions
can_we_count_it = [{'s': False}, "sassafrass", 18, ["a", "c", "s", "d", "s"]]
for i in can_we_count_it:
if hasattr(i, "count"):
print(str(type(i)) + " has the count attribute!")
else:
print(str(type(i)) + " does not have the count attribute :(")
# Self
class Circle:
pi = 3.14
def __init__(self, diameter):
print("Creating circle with diameter {d}".format(d=diameter))
self.radius = diameter / 2
def circumference(self):
return 2 * self.pi * self.radius
medium_pizza = Circle(12)
teaching_table = Circle(36)
round_room = Circle(11460)
print(medium_pizza.circumference())
print(teaching_table.circumference())
print(round_room.circumference())
# String Representation
# __repr__ is a method we can use to tell Python what we want the string representation of the class to be.
# __repr__ can only have one parameter, self, and must return a string.
class Circle:
pi = 3.14
def __init__(self, diameter):
self.radius = diameter / 2
def area(self):
return self.pi * self.radius ** 2
def circumference(self):
return self.pi * 2 * self.radius
def __repr__(self):
return "Circle with radius {radius}".format(radius=self.radius)
medium_pizza = Circle(12)
teaching_table = Circle(36)
round_room = Circle(11460)
print(medium_pizza)
print(teaching_table)
print(round_room)
|
balances = {"checking": 0, "savings": 0}
def make_deposit(account_type, amount, balances):
print("Time to open your account")
account_type = input("Savings or Checkings?: ")
print("Perfect!, time to make a deposit")
amount = input("How much would you like to deposit?: $")
deposit_status = ""
if amount > 0:
if account_type == "savings":
balances["savings"] += amount
deposit_status = "successful"
elif account_type == "checking":
balances["checking"] += amount
deposit_status = "successful"
else:
deposit_status = acc_error
else:
deposit_status = "Unsuccessful, please enter an amount greater than 0"
deposit_statement = "Deposit of "+ str(amount) + " dollars to your " + account_type + " account was " + deposit_status + "."
make_deposit("checking", 200, balances)
# make_deposit(account_type, amount, balances)
print(balances)
|
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
from pandas_datareader.data import DataReader
# Group listings by Sector and Exchange
by_sector_exchange = listings.groupby(['Sector', 'Exchange'])
# Calculate the median market cap
mcap_by_sector_exchange = by_sector_exchange.market_cap_m.median()
# Display the head of the result
print(mcap_by_sector_exchange.head())
# Unstack mcap_by_sector_exchange
mcap_unstacked = mcap_by_sector_exchange.unstack()
# Plot as a bar chart
mcap_unstacked.plot(kind='bar', title='Median Market Capitalization by Exchange')
# Set the x label
plt.xlabel('USD mn')
# Show the plot
plt.show()
# Create market_cap_m
listings['market_cap_m'] = listings['Market Capitalization'].div(1e6)
# Group listing by both Sector and Exchange
by_sector_exchange = listings.groupby(['Sector', 'Exchange'])
# Subset market_cap_m of by_sector_exchange
bse_mcm = by_sector_exchange['market_cap_m']
# Calculate mean, median, and std in summary
summary = bse_mcm.agg({'Average': 'mean', 'Median': 'median', 'Standard Deviation': 'std'})
# Print the summary
print(summary)
|
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
from pandas_datareader.data import DataReader
# Select IPOs after 2000
listings = listings[listings['IPO Year'] > 2000]
# Convert IPO Year to integer
listings['IPO Year'] = listings['IPO Year'].astype(int)
# Create a countplot
sns.countplot(x='IPO Year', hue='Exchange', data=listings)
# Rotate xticks and show result
plt.xticks(rotation=45)
# Show the plot
plt.show()
# Inspect the data
income_trend.info()
# Create barplot
sns.barplot(x='Year', y='Income per Capita', data=income_trend)
# Rotate xticks
plt.xticks(rotation=45)
# Show the plot
plt.show()
# Close the plot
plt.close()
# Create second barplot
sns.barplot(x='Year', y='Income per Capita', data=income_trend, estimator=np.median)
# Rotate xticks
plt.xticks(rotation=45)
# Show the plot
plt.show()
# Import the seaborn library as sns
import seaborn as sns
# Exclude IPOs before 2000 and from the 'amex'
listings = listings[(listings['IPO Year'] > 2000) & (listings.Exchange != 'amex')]
# Convert IPO Year to integer
listings['IPO Year'] = listings['IPO Year'].astype(int)
# Create market_cap_m
listings['market_cap_m'] = listings['Market Capitalization'].div(1e6)
# Exclude outliers
listings = listings[listings.market_cap_m < listings.market_cap_m.quantile(.95)]
# Create the pointplot
sns.pointplot(x='IPO Year', y='market_cap_m', hue='Exchange', data=listings)
# Rotate
plt.xticks(rotation=45)
# Show the plot
plt.show()
|
def word_flipper(our_string):
"""
Flip the individual words in a sentence
Args:
our_string(string): Strings to have individual words flip
Returns:
string: String with words flipped
"""
# Method 1 starts************************************
words = our_string.split(" ")
reverse_words = map(lambda x: x[::-1], words)
return " ".join(reverse_words)
# Method 1 ends**************************************
# Method 2 starts************************************
words = our_string.split(" ")
reverse_words = []
for word in words:
reverse_words.append(word[::-1])
return " ".join(reverse_words)
# Method 2 ends**************************************
# Method 3 starts************************************
words = our_string.split(" ")
return " ".join(word[::-1] for word in words)
# Method 3 ends**************************************
# print(word_flipper('This is an example'))
print ("Pass" if ('retaw' == word_flipper('water')) else "Fail")
print ("Pass" if ('sihT si na elpmaxe' == word_flipper('This is an example')) else "Fail")
print ("Pass" if ('sihT si eno llams pets rof ...' == word_flipper('This is one small step for ...')) else "Fail")
# Hamming Distance
# In information theory, the Hamming distance between two strings of equal length is the number of positions at which the corresponding symbols are different. Calculate the Hamming distace for the following test cases.
# Code
def hamming_distance(str1, str2):
"""
Calculate the hamming distance of the two strings
Args:
str1(string),str2(string): Strings to be used for finding the hamming distance
Returns:
int: Hamming Distance
"""
# Method 1 starts*********************************
if len(str1) != len(str2):
return None
hamming_distance = 0
for i, char in enumerate(str1):
if str2[i] != char:
hamming_distance += 1
return hamming_distance
# Method 1 ends***********************************
# Method 2 starts*********************************
hamming_distance = 0
if len(str1) == len(str2):
for i in range(len(str1)):
if str1[i] != str2[i]:
hamming_distance += 1
return hamming_distance
return None
# Method 2 ends***********************************
# Test Cases
print ("Pass" if (10 == hamming_distance('ACTTGACCGGG','GATCCGGTACA')) else "Fail")
print ("Pass" if (1 == hamming_distance('shove','stove')) else "Fail")
print ("Pass" if (None == hamming_distance('Slot machines', 'Cash lost in me')) else "Fail")
print ("Pass" if (9 == hamming_distance('A gentleman','Elegant men')) else "Fail")
print ("Pass" if (2 == hamming_distance('0101010100011101','0101010100010001')) else "Fail")
|
# use f in order to interpolate variables into a string
first_name = "ada"
last_name = "lovelace"
full_name = f"{first_name} {last_name}"
print(full_name)
# use the title method to capitalize first letters
print(f"Hello {full_name.title()}")
# .strip() to strip whitespace from a string
einstein = "Albert Einstein"
quote = "A person who never made a mistake never tried anything new."
print(f"{einstein} once said '{quote}'")
world_age = 5_781
print(world_age)
# A variable that doesnt change is declared in capital
DONT_CHANGE = 783259
# def eight():
# print(5+3)
# print(10-2)
# print(2*4)
# print(40/5)
# eight()
# import this
# an array in JS is called a list in Python
|
groups = open("input").read().split("\n\n")
count1, count2 = (0,0)
for group in groups:
questions = set([person for person in group.replace("\n","")])
count1 += len(questions)
for group in groups:
list_questions = [set(person) for person in group.split("\n")]
count2 += len(set.intersection(*list_questions))
print("First puzzle:", count1)
print("Second puzzle:", count2)
|
def sort(nums):
for i in range(len(nums)-1,0,-1):
for j in range(i):
if nums[j] > nums[j + 1]:
temp = nums[j]
nums[j] = nums[j + 1]
nums[j + 1] = temp
nums = [12, 2, 89, 105, 63, 4, 57, 99];
sort(nums)
print(nums)
|
class Animal(object):
def __init__(self,sound,name,age,favourite_color):
self.sound = sound
self.name = name
self.age = age
self.favourite_color = favourite_color
def eat(self,food):
print("Yummy!!" + self.name + "is eating" + food)
def description(self):
print(self.name + " is " + str(self.age) + " years old and loves the color" + self.favourite_color)
def make_sound(self,x):
print((self.sound + " ")*x )
class Person(object):
def __init__(self,name,age,city,gender, favourite_food):
self.name = name
self.age = age
self.city = city
self.gender = gender
self.favourite_food = favourite_food
def eat_breakfast(self,food):
if (food == "none"):
food = self.favourite_food
print("yum " + self.name + " is eating " + food)
def play_game(self, game):
print("This is so fun! " + self.name + " is playing " + game)
class Song(object):
def __init__(self, lyrics):
self.lyrics = lyrics
def sing_me_a_song(self):
for i in self.lyrics:
print(i)
flower_song = Song(["Roses are red, ","violets are blue, ","I wrote this poem just for you"])
flower_song.sing_me_a_song()
#####################################################################
# problem 1
#dog = Animal("bark","bim",6,"brown")
#dog.eat("meat")
#dog.description()
#dog.make_sound(4)
#####################################################################
#problem 2
#i = Person("Ilan",15,"Beit Shemesh","Male","meat")
#i.eat_breakfast("none")
#i.play_game("soccer")
#####################################################################
#problem 3
#flower_song = Song(["Roses are red, ","violets are blue, ","I wrote this poem just for you"])
#flower_song.sing_me_a_song()
|
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import math
import operator
eps = np.finfo(float).eps
########################################################
# Meas Squared Errror
########################################################
def rmse_score(y_true, y_pred):
"""Return the Mean Squared error by using the True pridiction made using the formula listed below"""
""" rmse score = sqrt((sum[i=0 to n](y_true - y_pred)) / len(y_true)) """
return np.sqrt((np.subtract(y_pred, y_true) ** 2).sum()/len(y_true))
def train_test_split(x, y, test_size = 0.10, random_state = None):
""" partioning the data into train and test sets """
x_test = x.sample(frac = test_size, random_state = random_state)
y_test = y[x_test.index]
x_train = x.drop(x_test.index)
y_train = y.drop(y_test.index)
return x_train, x_test, y_train, y_test
class DecisionTreeRegressor:
def __init__(self, max_depth = None, min_sample_leaf = 3):
self.depth = 0 #Depth of the tree
self.max_depth = max_depth #Maximum depth of the tree
self.min_sample_leaf = min_sample_leaf #Minimum number of samples for each node
self.coefficient_of_variation = 10 #Stopping Criterion
self.features = list
self.X_train = np.array
self.y_train = np.array
self.num_feats = int
self.train_size = int
def fit(self, X, y):
self.X_train = X
self.y_train = y
self.features = list(X.columns)
self.train_size = X.shape[0]
self.num_feats = X.shape[1]
df = X.copy()
df['target'] = y.copy()
#Builds Decision Tree
self.tree = self._build_tree(df)
print("\nDecision Tree(depth = {}) : \n {}".format(self.depth, self.tree))
def _build_tree(self, df, tree = None):
"""
Args:
df: current number of rows available for splitting(decision making)
"""
#Get feature with minimum score
feature, cutoff = self._find_best_split(df)
if cutoff is None:
return tree
#Initialization of tree
if tree is None:
tree = {}
tree[feature] = {}
#Left Child
new_df = self._split_rows(df, feature, cutoff, operator.le)
target_coef_of_var = self._coef_ov(new_df['target'])
self.depth += 1
if(target_coef_of_var < self.coefficient_of_variation or len(new_df) <= self.min_sample_leaf): #pure group
tree[feature]['<=' + str(cutoff)] = new_df['target'].mean()
else:
if self.max_depth is not None and self.depth >= self.max_depth:
tree[feature]['<=' + str(cutoff)] = new_df['target'].mean()
else:
tree[feature]['<=' + str(cutoff)] = self._build_tree(new_df)
#Right Child
new_df = self._split_rows(df, feature, cutoff, operator.gt)
target_coef_of_var = self._coef_ov(new_df['target'])
if(target_coef_of_var < self.coefficient_of_variation or len(new_df) <= self.min_sample_leaf): #pure group
tree[feature]['>' + str(cutoff)] = new_df['target'].mean()
else:
if self.max_depth is not None and self.depth >= self.max_depth:
tree[feature]['>' + str(cutoff)] = new_df['target'].mean()
else:
tree[feature]['>' + str(cutoff)] = self._build_tree(new_df)
return tree
def _coef_ov(self, y):
""" calculates coefficient of variation:
COV = (Mean of y / Standard Deviation of y) * 100
"""
if(y.std() == 0):
return 0
coef_of_var = (y.mean()/y.std()) * 100
return coef_of_var
def _split_rows(self, df, feature, feat_val, operation ):
""" split rows based on given criterion """
return df[operation(df[feature], feat_val)].reset_index(drop = True)
def _find_best_split(self, df):
"""
Finds the column to split on first.
"""
best_feature = str
cutoff = None
best_score = float('inf')
for feature in list(df.columns[:-1]):
score, threshold = self._find_feature_split(feature, df)
if score < best_score:
best_feature = feature
best_score = score
cutoff = threshold
return best_feature, cutoff
def _find_feature_split(self, feature, df):
best_score = float('inf')
cutoff = float
for val in df[feature]:
left_child = df[feature][df[feature] <= val]
right_child = df[feature][df[feature] > val]
if(len(left_child) > 0 and len(right_child) > 0):
score = self._find_score(df, left_child, right_child)
if score < best_score:
best_score = score
cutoff = val
return best_score, cutoff
def _find_score(self, df, lhs, rhs):
y = df['target']
lhs_std = y.iloc[lhs.index].std()
rhs_std = y.iloc[rhs.index].std()
if(np.isnan(lhs_std)):
lhs_std = 0
if(np.isnan(rhs_std)):
rhs_std = 0
# print('lhs_std \n')
# print(lhs_std)
# print('lhs \n')
# print(lhs)
return lhs_std * lhs.sum() + rhs_std * rhs.sum()
def _predict_target(self, feature_lookup, x, tree):
for node in tree.keys():
val = x[node]
if type(val) == str:
tree = tree[node][val]
else:
cutoff = str(list(tree[node].keys())[0]).split('<=')[1]
if(val <= float(cutoff)): #Left Child
tree = tree[node]['<='+cutoff]
else: #Right Child
tree = tree[node]['>'+cutoff]
prediction = str
if type(tree) is dict:
prediction = self._predict_target(feature_lookup, x, tree)
else:
predicton = tree
return predicton
return prediction
def predict(self, X):
results = []
feature_lookup = {key: i for i, key in enumerate(list(X.columns))}
for index in range(len(X)):
results.append(self._predict_target(feature_lookup, X.iloc[index], self.tree))
return np.array(results)
########################################################
# Decision Tree for Regression. Perform with and without early stop.
########################################################
def DTReg(PDData, MaxDepth):
data = PDData
#print(df)
#Split Features and target
X, y = data.drop([data.columns[0], data.columns[-1]], axis = 1), data[data.columns[-1]]
#Split data into Training and Testing Sets
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.25, random_state = 0)
dt_reg = DecisionTreeRegressor()
dt_reg.fit(X, y)
print("\nTrain RMSE : {}".format(rmse_score(y_train, dt_reg.predict(X_train))))
print("\nTest RMSE: {}".format(rmse_score(y_test, dt_reg.predict(X_test))))
dt_reg = DecisionTreeRegressor(max_depth = MaxDepth)
dt_reg.fit(X, y)
print("\nTrain RMSE : {}".format(rmse_score(y_train, dt_reg.predict(X_train))))
print("\nTest RMSE: {}".format(rmse_score(y_test, dt_reg.predict(X_test))))
|
#!/usr/bin/env python
""" Assignment 1, Exercise 3, INF1340, Fall, 2015. Troubleshooting Car Issues.
This module contains one function diagnose_car(). It is an expert system to
interactive diagnose car issues.
"""
__author__ = 'Susan Sim'
__email__ = "[email protected]"
__copyright__ = "2015 Susan Sim"
__license__ = "MIT License"
"""
"""
# Interactively queries the user with yes/no questions to identify a possible issue with a car.
# Inputs: As is but not nested - same indentation all the way through
# Expected Outputs: To follow the decision logic of the question tree
# Errors: Did not proceed according to logic. fixed by nesting properly
"""
"""
def diagnose_car():
silent = raw_input("Is the car silent when you turn the key? ")
#this begins the line of questions on the left side of the question tree
if silent == 'Y':
corroded = raw_input("Are the battery terminals corroded?")
if corroded == 'Y':
print "Clean terminals and try starting again."
elif corroded == 'N':
print "Replace cables and try again."
elif silent == 'N':
#this begins the line of questions on the right side of the question tree
clicking = raw_input("Does the car make a clicking noise?")
if clicking == 'Y':
print "Replace the battery."
elif clicking == 'N':
crank = raw_input("Does the car crank up but fails to start?")
if crank == 'Y':
print "Check spark plug connections."
elif crank == 'N':
start_and_die = raw_input("Does the engine start and then die?")
if start_and_die == 'Y':
fuel_injection = raw_input("Does your car have fuel injection?")
if fuel_injection == 'N':
print "Check to ensure the choke is opening and closing."
elif fuel_injection == 'Y':
print "Get it in for service."
elif start_and_die == 'N':
print "Engine is not getting enough fuel. Clean fuel pump."
diagnose_car()
|
import datetime
"""
DEFINE LEAP YEAR
The year can be evenly divided by 4;
If the year can be evenly divided by 100, it is NOT a leap year, unless;
The year is also evenly divisible by 400. Then it is a leap year.
"""
def is_leap_year(year):
year = int(year)
is_leap = False
if year % 4 == 0:
if year % 100:
if year % 400:
is_leap = True
else:
is_leap = True
return is_leap
# Define months
MONTHS = {
'1': 31,
'3': 31,
'4': 30,
'5': 31,
'6': 30,
'7': 31,
'8': 31,
'9': 30,
'10': 31,
'11': 30,
'12': 31,
}
def get_days_in_month(month, year):
"""
given a month and year, find the days in the given month
accounting for leap year
:param month:
:param year:
:return: the number of days in the month
"""
if str(month) == '2':
if is_leap_year(year):
return 29
else:
return 28
return MONTHS[str(month)]
def calc_act(year, month, day, sched_hour, sched_min, delay):
"""
from the database parameters, find the delay
:param year:
:param month:
:param day:
:param sched_hour:
:param sched_min:
:param delay:
:return:
"""
days_in_month = get_days_in_month(month, year)
import datetime
time1 = datetime.datetime(year, month, day, sched_hour, sched_min)
time1 += datetime.timedelta(minutes=delay)
return time1.month, time1.day, time1.hour, time1.minute
def calc_window(year, month, day, window_size):
"""
:param year:
:param month:
:param day:
:return:
"""
time = datetime.datetime(year, month, day)
t_delta = datetime.timedelta(days=window_size)
back = time - t_delta
forward = time + t_delta
return back.month, back.day, forward.month, forward.day
|
#2.Write program to implement Selection sort.
no=[5,6,1,2,3]
l=len(no)
for i in range(l-1):
for j in range(i+1,l):
if no[i]>no[j]:
no[i],no[j]=no[j],no[i]
print(no)
|
#6.Write a python program to generate Fibonacci Numbers upto 100 using generator.
def fibo():
a=0
b=1
while True:
if a>100:
break
yield a
a,b=b,a+b
for i in fibo():
print(i)
|
import numpy as np
import random
import matplotlib.pyplot as plt
import os
'''
ConnectX game.
Author: Max Croci
Date: 21.02.2019
'''
class Board:
variant = 0
n_rows = 0
n_cols = 0
positions = {} #Dictionary of symbols (values) at positions (keys)
available_moves = []#List of available moves
visited_states = [] #List of visited states
filled_positions =[]#List of positions filled from chosen moves
chosen_moves = [] #List of moves that have been made
def __init__(self,variant):
self.positions = {}
self.visited_states = []
self.filled_positions = []
self.chosen_moves = []
if variant == "3":
self.n_rows = 4
self.n_cols = 4
self.variant = variant
elif variant == "4":
self.n_rows = 6
self.n_cols = 7
self.variant = variant
self.available_moves = [i + 1 for i in range(self.n_cols)]
for i in range(self.n_rows*self.n_cols):
self.positions[i+1] = "_"
self.visited_states.append("_"*self.n_rows*self.n_cols)
def print_board(self):
for i in range(self.n_rows):
row = ""
for j in range(self.n_cols):
row += self.positions[1+self.n_cols*i+j]
print(row)
def move_to_position(self,move):
cur_state = self.visited_states[-1]
for i in range(self.n_rows-1,-1,-1):
if cur_state[move+i*self.n_cols-1] == "_":
position = move+i*self.n_cols
self.filled_positions.append(position)
self.chosen_moves.append(move)
return position
def update(self,move,symbol):
position = self.move_to_position(move)
self.positions[position] = symbol
if position <= self.n_cols:
self.available_moves.remove(move)
state = ""
for i in range(self.n_rows*self.n_cols):
state += self.positions[1+i]
self.visited_states.append(state)
def get_next_possible_states(self, symbol):
cur_state = self.visited_states[-1]
moves = self.available_moves
next_possible_states = {} #Dict keyed by moves, values are states
for move in moves:
for i in range(self.n_rows-1,-1,-1):
if move not in next_possible_states:
if cur_state[move+i*self.n_cols-1] == "_":
new_state = cur_state[:move+i*self.n_cols-1]\
+ symbol\
+ cur_state[move+i*self.n_cols:]
next_possible_states[move] = new_state
return next_possible_states
def check_victory(self, symbol):
last_filled_pos = self.filled_positions[-1] #Only need to check for win around last position
last_move = self.chosen_moves[-1]
last_move_row = int(np.floor(1+(last_filled_pos-1)/self.n_cols))
last_move_col = (last_filled_pos-1)%self.n_cols + 1
if self.variant == "3":
if last_filled_pos <= 8: #Check vertical if in top two rows
if self.positions[last_filled_pos] == self.positions[last_filled_pos+self.n_cols]\
and self.positions[last_filled_pos] == self.positions[last_filled_pos+self.n_cols*2]:
#print("Game is won vertically!")
return True
for i in range (1,self.n_cols-1): #check horizontal
if self.positions[i+(last_move_row-1)*self.n_cols] != "_"\
and self.positions[i+(last_move_row-1)*self.n_cols] == self.positions[i+1+(last_move_row-1)*self.n_cols]\
and self.positions[i+(last_move_row-1)*self.n_cols] == self.positions[i+2+(last_move_row-1)*self.n_cols]:
#print("Win horizontally!")
return True
#Check diagonals
itmp = [1, 2, 5, 6]
istarts = [i for i in itmp if i in self.filled_positions]
for i in istarts:
if self.positions[i] == self.positions[i+self.n_cols+1]\
and self.positions[i] == self.positions[i+self.n_rows*2+2]:
#print("Win -ve diag")
return True
itmp = [3, 4, 7, 8]
istarts = [i for i in itmp if i in self.filled_positions]
for i in istarts:
if self.positions[i] == self.positions[i+self.n_cols-1]\
and self.positions[i] == self.positions[i+self.n_rows*2-2]:
#print("Win +ve diag")
return True
return False
elif self.variant == "4":
if last_filled_pos <= 21: #Check vertical if in top three rows
if self.positions[last_filled_pos] == self.positions[last_filled_pos+self.n_cols]\
and self.positions[last_filled_pos] == self.positions[last_filled_pos+self.n_cols*2]\
and self.positions[last_filled_pos] == self.positions[last_filled_pos+self.n_cols*3]:
#print("Game is won vertically!")
return True
for i in range (1,self.n_cols-2): #check horizontal
if self.positions[i+(last_move_row-1)*self.n_cols] != "_"\
and self.positions[i+(last_move_row-1)*self.n_cols] == self.positions[i+1+(last_move_row-1)*self.n_cols]\
and self.positions[i+(last_move_row-1)*self.n_cols] == self.positions[i+2+(last_move_row-1)*self.n_cols]\
and self.positions[i+(last_move_row-1)*self.n_cols] == self.positions[i+3+(last_move_row-1)*self.n_cols]:
#print("Win horizontally!")
return True
#Check diagonals
itmp = [1, 2, 3, 4, 8, 9, 10, 11, 15, 16, 17, 18]
istarts = [i for i in itmp if i in self.filled_positions]
for i in istarts:
if self.positions[i] == self.positions[i+8]\
and self.positions[i] == self.positions[i+16]\
and self.positions[i] == self.positions[i+24]:
#print("Win -ve diag")
return True
itmp = [4, 5, 6, 7, 11, 12, 13, 14, 18, 19, 20, 21]
istarts = [i for i in itmp if i in self.filled_positions]
for i in istarts:
if self.positions[i] == self.positions[i+6]\
and self.positions[i] == self.positions[i+12]\
and self.positions[i] == self.positions[i+18]:
#print("Win +ve diag")
return True
return False
else:
print("Warning: unrecognised variant!")
return False
class Bot:
symbol = "" # "X" or "O"
win = 0 # win = 1 if bot wins
V = {} # Estimated value of states (keys)
num_wins = 0# Track number of bot wins
tau = 1 #"Heat" controls exploration v exploitation
training = True
def __init__(self,symbol,V,num_wins,tau,training):
self.symbol = symbol
self.win = -1
self.num_wins = num_wins
self.V = V
self.tau = tau
self.training = training
def get_move(self, board):
next_possible_states = board.get_next_possible_states(self.symbol)
candidate_moves = []
candidate_V = []
candidate_probabilities = []
for poss_move, poss_state in next_possible_states.items():
if poss_state not in self.V.keys():
self.V[poss_state] = 0
candidate_moves.append(poss_move)
candidate_V.append(self.V[poss_state])
if self.training:
candidate_V[:] = [x/self.tau for x in candidate_V]
candidate_probabilities = list(np.exp(candidate_V)/sum(np.exp(candidate_V)))
move = int(np.random.choice(candidate_moves,1,candidate_probabilities))
else:
max_V = max(candidate_V)
possible_moves = [candidate_moves[i] for i,j in enumerate(candidate_V) if j == max_V]
move = np.random.choice(possible_moves)
return move
def update_V(self,board,REWARD,LEARN_RATE):
final_state = board.visited_states[-1]
self.V[final_state] = REWARD*self.win
for state in board.visited_states:
if state not in self.V:
self.V[state] = 0
n_states_visited = len(board.visited_states)
for i in range(n_states_visited-1):
state = board.visited_states[n_states_visited -i -2]
next_state = board.visited_states[n_states_visited -i -1]
self.V[state] = self.V[state] + LEARN_RATE*(self.V[next_state] - self.V[state])
#Mirror states - make use of symmetry
mirror_visited_states = []
for state in board.visited_states:
mirror_state = state[board.n_cols-1::-1]
for i in range(1,board.n_rows,1):
mirror_row = state[(i+1)*board.n_cols-1:i*board.n_cols-1:-1]
mirror_state = mirror_state + mirror_row
self.V[mirror_state] = self.V[state]
def main():
print("Hello, welcome to connectX!")
valid_variant = False
while not valid_variant:
print("Which variant would you like to play? Type '3' for Connect3 or '4' for Connect4:")
variant = input()
if variant is "3":
valid_variant = True
elif variant is "4":
valid_variant = True
else:
print("I'm sorry, " + variant + " isn't a valid option, please try again.")
res_dir = "resultsConnect" + variant +os.sep
path = os.getcwd() + os.sep
res_path = path + res_dir
if not os.path.exists(res_path):
os.mkdir(res_path)
quit = False
while not quit:
print("Would you like to train, test or play against a bot? Type 'r' to train, 'e' to test,'p' to play or 'q' to quit:")
ans = input()
if ans is "r":
train_bots(variant,res_dir)
print('\n')
elif ans is "e":
test_bots(variant,res_dir)
print('\n')
elif ans is "p":
play_bot(variant,res_dir)
print('\n')
elif ans is "q":
quit = True
print("Goodbye!")
else:
print("I'm sorry, " + ans + " isn't a valid option, please try again.")
def train_bots(variant,res_dir):
##Train the bots over many trials##
print("Please enter the number of trials (games) to train the bots over (10k trials takes approx 20s): ")
MAX_NUM_TRIALS = input()
while MAX_NUM_TRIALS.isdigit() == False:
print("Error, please try again:")
MAX_NUM_TRIALS = input()
MAX_NUM_TRIALS = int(MAX_NUM_TRIALS)
tau = 20
for n_trial in range(1,MAX_NUM_TRIALS+1,1):
#print("#"*15)
if n_trial%1000 == 0:
print("Trial: " + str(n_trial) + " of " + str(MAX_NUM_TRIALS))
if n_trial%5000 == 0:
tau = tau/2
if n_trial == 1:
bot1 = Bot("X",{},0,tau,True)
bot2 = Bot("O",{},0,tau,True)
else:
bot1 = Bot("X",bot1.V,bot1.num_wins,tau,True) #Load key bot variables from previous trial
bot2 = Bot("O",bot2.V,bot2.num_wins,tau,True) #Load key bot variables from previous trial
bots = {}
bots[1] = bot1
bots[2] = bot2
board = Board(variant)
##Run the game##
MAX_NUM_TURNS = board.n_rows*board.n_cols
REWARD = 100
LEARN_RATE = 0.1
turn = 1
victory = False
while turn <= MAX_NUM_TURNS and not victory:
bot = bots[2-(turn%2)]
move = bot.get_move(board)
board.update(move,bot.symbol)
#board.print_board()
victory = board.check_victory(bot.symbol)
if victory:
bot.win = 1
bot.num_wins = bot.num_wins + 1
#print("Bot " + bot.symbol + " wins!")
turn = turn + 1
#print("#"*15)
##Update bots
for botnum,bot in bots.items():
if victory and bot.win == 0:
bot.win = -1
bot.update_V(board,REWARD,LEARN_RATE)
##Analyse training results##
print("Training complete!")
print("X won " + str(bot1.num_wins) + " games and analysed " + str(len(bot1.V)) + " positions.")
print("O won " + str(bot2.num_wins) + " games and analysed " + str(len(bot2.V)) + " positions.")
save_results(res_dir,bot1,bot2,MAX_NUM_TRIALS,"trials")
def test_bots(variant,res_dir):
##Load V from a file saved through training process##
print("The following saved bots exist: ")
num_bots = 0
for f in os.listdir(res_dir):
if f[0] == "V":
num_bots = num_bots + 1
print("#" + str(num_bots) + ": " + f)
if num_bots == 0:
print("No saved bots found! Please train a bot before testing it.")
return -1
print("Type a number eg '1' to choose the bot:")
bot_chosen = int(input())
num_bots = 0
for f in os.listdir(res_dir):
if f[0] == "V":
num_bots = num_bots + 1
if bot_chosen == num_bots:
[Vx, Vo] = read_V_file(res_dir,f)
##Test the bots against each other aggressively##
print("Please enter the number of tests: ")
MAX_NUM_TESTS = input()
while MAX_NUM_TESTS.isdigit() == False:
print("Error, please try again:")
MAX_NUM_TESTS = input()
MAX_NUM_TESTS = int(MAX_NUM_TESTS)
for n_trial in range(1,MAX_NUM_TESTS+1,1):
#print("#"*15)
if n_trial%1000 == 0:
print("Test: " + str(n_trial) + " of " + str(MAX_NUM_TESTS))
if n_trial == 1:
bot1 = Bot("X",Vx,0,0,False)
bot2 = Bot("O",Vo,0,0,False)
else:
bot1 = Bot("X",bot1.V,bot1.num_wins,0,False) #Load key bot variables from previous trial
bot2 = Bot("O",bot2.V,bot2.num_wins,0,False) #Load key bot variables from previous trial
bots = {}
bots[1] = bot1
bots[2] = bot2
board = Board(variant)
##Run the game##
MAX_NUM_TURNS = board.n_cols*board.n_rows
REWARD = 100
LEARN_RATE = 0.1
turn = 1
victory = False
while turn <= MAX_NUM_TURNS and not victory:
bot = bots[2-(turn%2)]
move = bot.get_move(board)
board.update(move,bot.symbol)
#board.print_board()
victory = board.check_victory(bot.symbol)
if victory:
bot.win = 1
bot.num_wins = bot.num_wins + 1
#print("Bot " + bot.symbol + " wins!")
turn = turn + 1
#print("#"*15)
##Update bots
for botnum,bot in bots.items():
if victory and bot.win == 0:
bot.win = -1
bot.update_V(board,REWARD,LEARN_RATE)
##Analyse testing results##
print("Testing complete!")
print("X won " + str(bot1.num_wins) + " games and analysed " + str(len(bot1.V)) + " positions.")
print("O won " + str(bot2.num_wins) + " games and analysed " + str(len(bot2.V)) + " positions.")
save_results(res_dir,bot1,bot2,MAX_NUM_TESTS,"tests")
def play_bot(variant,res_dir):
##Load V from a file saved through training process##
print("The following saved bots exist: ")
num_bots = 0
for f in os.listdir(res_dir):
if f[0] == "V":
num_bots = num_bots + 1
print("#" + str(num_bots) + ": " + f)
print("Type a number eg '1' to choose the bot:")
bot_chosen = int(input())
num_bots = 0
for f in os.listdir(res_dir):
if f[0] == "V":
num_bots = num_bots + 1
if bot_chosen == num_bots:
[Vx, Vo] = read_V_file(res_dir,f)
play_game = True
while play_game:
board = Board(variant)
print("Play as player '1' or '2'?")
valid_answer = False
while not valid_answer:
answer = input()
if answer == "1" or answer == "2":
player = int(answer)
valid_answer = True
else:
print("Error, please enter '1' or '2'")
if player == 1:
player_symbol = "X"
bot = Bot("O",Vo,0,0,False)
else:
bot = Bot("X",Vx,0,0,False)
player_symbol = "O"
##Run the game##
MAX_NUM_TURNS = board.n_cols*board.n_rows
turn = 1
victory = False
board.print_board()
while turn <= MAX_NUM_TURNS and not victory:
cur_player = (turn-1)%2 + 1
if cur_player == player:
print("Please make a move. Available moves:")
print(board.available_moves)
move = int(input())
while move not in board.available_moves:
print("Error: move unavailable. Available moves:")
print(board.available_moves)
move = int(input())
board.update(move,player_symbol)
else:
n_states = board.get_next_possible_states(bot.symbol)
move = bot.get_move(board)
board.update(move,bot.symbol)
print("#"*15)
board.print_board()
victory = board.check_victory(bot.symbol)
if (victory):
if cur_player == player:
print("Game over: you win!")
else:
print("Game over: you lose!")
turn = turn + 1
print("Would you like to play again? (y/n)")
valid_answer = False
while not valid_answer:
answer = input()
if answer == "y":
play_game = True
valid_answer = True
elif answer == "n":
play_game = False
valid_answer = True
else:
print("Error, please enter 'y' or 'n':")
def read_V_file(res_dir,filename):
Vx = {}
Vo = {}
f = open(res_dir + filename,'r')
num_lines = 0
for line in f:
num_lines = num_lines + 1
if num_lines%1000 == 0:
print("Loaded " + str(num_lines) + " states...")
state, value = line.rstrip('\n').split('\t')
Vx[state] = float(value)
Vo[state] = -float(value)
V = [Vx, Vo]
return V
def save_results(res_dir,bot1,bot2,MAX_NUM,case):
filename = res_dir + "results_" + str(MAX_NUM) + "_" + case + ".txt"
f = open(filename,"w")
state_msg = "X analysed " + str(len(bot1.V)) + " states, O analysed " + str(len(bot2.V)) + ".\n"
for state, value in bot1.V.items():
if state not in bot2.V:
bot2.V[state] = 0
for state, value in bot2.V.items():
if state not in bot1.V:
bot1.V[state] = 0
if case == "trials":
f.write("Results of training with " + str(MAX_NUM) + " trials.\n")
else:
f.write("Results of testing with " + str(MAX_NUM) + " tests.\n")
res_msg = "X won " + str(bot1.num_wins) + " games, O won " + str(bot2.num_wins) + ".\n"
f.write(res_msg)
f.write(state_msg)
f.write("#"*len(state_msg) + "\n")
f.write("State values V(s) estimated by X and O:\n")
for state, value in bot1.V.items():
f.write("-"*len(state_msg) + "\n")
f.write(state[0:4] + " "*4 + "V(s) for X: " + str(round(value,3)) + "\n")
f.write(state[4:8] + " "*4 + "V(s) for O: " + str(round(bot2.V[state],3)) +"\n")
f.write(state[8:12] + "\n")
f.write(state[12:16] + "\n")
f.close()
filename = res_dir + "V_" + str(MAX_NUM) + "_" + case + ".txt"
f = open(filename,"w")
for state, value in bot1.V.items():
f.write(state + "\t" + str(value) + "\n")
f.close()
if __name__ == "__main__":
main()
|
def read(filename):
with open(filename, "r") as f:
data = f.read().split("\n\n")
return data
def count(data):
count_1, count_2 = 0, 0
for item in data:
count_1 += len(set(item.replace("\n", "")))
current = [set(i) for i in item.split()]
count_2 += len(current[0].intersection(*current[1:]))
return count_1, count_2
data = read("input6.txt")
c1, c2 = count(data)
print("count_1:", c1, "count_2:", c2)
|
#danilo Patrucco
#inf 103
#c to f table
#set variables
celsius = 0
#set max temp as final value
maxtemp = 21
#test = 1
#while celsius is different than maxtemp then loop
#while test == 1:
while celsius != maxtemp:
#compute the temperature
fahrenheit = format((9/5)*celsius+32,'.2f')
print (celsius,'\t',fahrenheit)
celsius = celsius + 1
#test = int(input('test Value'))
#if test != 1:
#celsius = 0
#print (celsius)
|
#inf 103
#danilo patrucco
# Math Quiz
import random
def main():
in1 = random.randint(1,300)
in2 = random.randint(1,300)
intot = in1 + in2
print (in1,"+",in2)
inanswer = int ( input ("insert result of sum of the values displayed above \t"))
compare(intot,inanswer)
def compare(v1,v2):
if v1 == v2 :
print ("Good answer!")
else :
print ("Wrong Answer!")
main()
|
#INF103
#Danilo Patrucco
#read, write, append
'''
test = open ('data_sample.txt','r')
file_content = str(test.readline())
test.close()
print = (file_content)
'''
inFile = open ('data_sample.txt','r')
firstLine = inFile.readline()
fLineStripped = firstLine.strip('\n') # stirp remove leading an trailing edges
inFile.close()
print (fLineStripped)
inFile = open ('write_sample.txt','a')
#write overwrite the file completely
#append it does append
test1 = input('give me a number:')
inFile.write(str(test1)+ '\n')
#cannot use comma in write, only the concatenation
inFile.close()
|
#import os and csv
import os
import csv
#join path
budget_data = os.path.join("Resources", "budget_data.csv")
#open and read csv
with open(budget_data, 'r') as csvfile:
csvreader = csv.reader(csvfile, delimiter = ',')
header= next(csvreader)
#make list to find net profit and loss
profit = []
month =[]
#read file and add to list
for rows in csvreader:
profit.append(int(rows[1]))
month.append(rows[0])
#make profit change list
profit_change =[]
#add profit/loss change to profit change list
for x in range(1, len(profit)):
profit_change.append((int(profit[x])- int(profit[x-1])))
#formula for avg change
avg_change = sum(profit_change)/ len(profit_change)
#num of months length
month_num = len(month)
#greatest increase in profit
great_increase = max(profit_change)
#greatest decrease in profit
great_decrease = min(profit_change)
#print the final info
print("Financial Analysis")
print("-------------------")
print("Total Months: " + str(month_num))
print("Total: " + "$" + str(sum(profit)))
print("Average change: " + "$" + str(avg_change))
print("Greatest Increase in Profits: " + str(month[profit_change.index(max(profit_change))+1])) + " "+ "$" + str((great_increase))
print("Greatest Decrease in Profits: " + str(month[profit_change.index(min(profit_change))+1])) + " "+ "$" + str((great_decrease))
#write a text file containing printed information
file = open("Analysis/bank_analysis.txt","w")
file.write("Financial Analysis" + "\n")
file.write("------------------" + "\n")
file.write("Total months: " + str(month_num) + "\n"
file.write("Average change: " + "$" + str(avg_change) + "\n")
file.write("Greatest Increase in Profits: " + str(month[profit_change.index(max(profit_change))+1])) + " "+ "$" + str(great_increase) + "\n")
file.write("Greatest Increase in Profits: " + str(month[profit_change.index(min(profit_change))+1])) + " "+ "$" + str((great_decrease)) + "\n")
file.close()
|
anoNascimento = int(input("Informe o seu ano de nascimento: "))
idade = 2019 - anoNascimento
if idade >= 16:
print("Você possue idade para votar!")
if idade >= 18:
print("Você possue idade para tirar a CNH!")
|
cotacaoDolar = float(input("Informe a cotação atual do dólar: "))
valor = float(input("Informe ó valor em reais: "))
valorConvertido = valor/cotacaoDolar
print("O valor em dólar é: $", valorConvertido)
|
from node import Node
class Input(Node):
def __init__(self):
Node.__init__(self)
def forward(self, value=None):
# Overwrite value if one is passed
if value is not None:
self.value = value
def backward(self):
self.gradients = {self: 0}
for neuron in self.outbound_nodes:
grad_cost = neuron.gradients[self]
self.gradients[self] += grad_cost
|
// Time Complexity : O(V+E)
// Space Complexity : O(1)
// Did this code successfully run on Leetcode : Yes
// Any problem you faced while coding this : No
// Your code here along with comments explaining your approach
class Solution:
def isSymmetric(self, root: TreeNode) -> bool:
return self.isMirror(root,root)
def isMirror(self,roota,rootb):
if roota==None and rootb==None: #if both same, return true
return True
if roota==None or rootb==None: #if one of them is None, false
return False
#compare between subtreeA left, subtreeB right and vice versa.
return roota.val==rootb.val and self.isMirror(roota.left,rootb.right) and self.isMirror(rootb.left,roota.right)
|
from bs4 import BeautifulSoup
from urllib.request import urlopen
import csv
import pandas as pd
import numpy as np
from selenium import webdriver
from selenium.webdriver.support.ui import Select
from selenium.webdriver.common.keys import Keys
from io import BytesIO, StringIO
import boto3
import selenium
import time
from selenium.webdriver import Firefox
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.firefox.options import Options
from selenium.webdriver.support import expected_conditions as expected
from selenium.webdriver.support.wait import WebDriverWait
def get_alt(village, location, browser, state_dict, lat, lon):
'''
The function takes in the name of the village and it's location along with
the coordinates and uses that information to return the elevation of the
coordinates/location
village(str): String specifying the name of the village for which the
latitude and longitude are returned
location(str): String specifying the name of the location for which the
latitude and longitude are returned
browser(webdriver): Webdriver object that will be used to make get requests
and for obtaining the page source
state_dict(dict): Dictionary mapping the location for each village to the
state. The village name and state will then be used to
search for latitude and longitude
lat(float): The latitude for the village in degrees
lon(float): The longitude for the village in degrees
'''
#Making a get request to website from which elevation data can be acquired
browser.get("https://www.whatismyelevation.com")
#Locating element using which location can be entered
browser.find_element_by_id("change-location").click()
time.sleep(2)
#Entering location/coordinates to search for the elevation
search = browser.find_element_by_id("address")
search.send_keys('{}, {}'.format(lat, lon))
#Making sure the changes were registered
search.send_keys(Keys.ENTER)
search.send_keys(Keys.ENTER)
search.send_keys(Keys.ENTER)
time.sleep(3)
text = browser.page_source
#coord = browser.current_url.split('@')[1].split(',')
soup = BeautifulSoup(text, "lxml")
#Parsing through the page source to find the elevation for the location
elevation = soup.find('div', {'id':'elevation'})
altitude = elevation.find('span', {'class': "value"})
#Converting to float only if there is elevation data present for this
#location
if len(altitude.decode().split('>')[1].split('<')[0].replace(',', '')) > 0:
alt = float(altitude.decode().split('>')[1].split('<')[0].replace(',', ''))
else:
alt = altitude.decode().split('>')[1].split('<')[0].replace(',', '')
return location, village, alt
if __name__ == '__main__':
df = pd.read_csv('complete_vill_loc.csv')
#Reading in the village and location names
df.drop(columns='Unnamed: 0', inplace=True)
location_groups = df.groupby(by='Location')
village_dict = {}
#Creating dictionary that has village names as keys and locations as values
for loc, group in location_groups:
for vill in set(group['Village'].values):
village_dict[vill] = loc
states = ['KARNATAKA', 'ANDHRA PRADESH', 'ANDHRA PRADESH', 'MAHARASHTRA', 'ANDHRA PRADESH', 'ANDHRA PRADESH',
'TAMILNADU', 'TELANGANA', 'ANDHRA PRADESH', 'ANDHRA PRADESH', 'ANDHRA PRADESH',
'TELANGANA', 'TELANGANA', 'ANDHRA PRADESH']
#Creating dictionary that has locations as keys and states as values
state_dict = dict(zip(df['Location'].unique(), states))
#Initializing headless Selenium webdriver and boto3 client to interact
#with AWS S3 bucket
options = Options()
options.add_argument('-headless')
browser = Firefox(executable_path='geckodriver', firefox_options=options)
#browser = Firefox()
s3 = boto3.client('s3')
#Writing the elevation data for each village to csv file in AWS S3 bucket
with StringIO() as f:
wr = csv.writer(f)
wr.writerow(['Location', 'Village', 'Elevation'])
for village, location in village_dict.items():
lat = df[df['Village'] == village]['Latitude'].values[0]
lon = df[df['Village'] == village]['Longitude'].values[0]
print (lat, lon)
data = get_alt(village, location, browser, state_dict, lat, lon)
print (data)
wr.writerow(data)
time.sleep(2)
s3.put_object(Bucket='capstone-web-scrape',
Key='new_village_altitude_data.csv',
Body=f.getvalue())
''' with open("village_altitude_data.csv", "w") as f:
wr = csv.writer(f)
wr.writerow(['State', 'Location', 'Altitude'])
for location, state in zip(places, states):
data = get_alt(location, state, browser)
wr.writerow(data)
time.sleep(2)'''
|
c = float(input("Digita la temperatura in °C: "))
f = ((9 * c) /5) + 32
print("-" * 80)
print("La temperatura di {}° C equivale a {}° F".format(c, f))
print("-" * 80)
|
name = str(input("COGNOME / NOME: ").strip())
print("Il tuo COGNOME/NOME contiene Rossi: {}".format("rossi" in name.lower()))
|
from random import randint
from time import sleep
pc = randint(0, 5)
print("-=-"*20)
print("Sto pensando in un numero da 0 a 5...")
print("-=-"*20)
sleep(3)
user = int(input("In quale numero ho pensato, prova a indovinarlo: "))
print("-=-"*20)
if user == pc:
print("Hai vinto, complimenti !!!")
else:
print("Hai perso, ho pensato al numero {} ritenta." .format(pc))
print("-=-"*20)
|
"""Calcolo della velocità in km/h e m/s"""
# dati
dist = float(input("Per quanti km hai corso? "))
min = int(input("In quanti minuti? "))
# elaborazione
m = dist * 1000 # da km a metri
s = min * 60 # da minuti a secondi
v = m / s
# colors
colors = {"clear": "\33[m",
"start": "\33[1;30;31m"}
# output
print("{}".format(colors["start"]))
print("=" * 75)
print("Hai corso {} km in {} minuti. La tua velocià media è di {} m/s." .format(round(dist, 1), min, round(v, 1)))
print("=" * 75)
print("{}".format(colors["start"]))
|
n = int(input("Digita un numero: "))
if n%2 == 0:
print("Il numero {} è un numero PARI !!!" .format(n))
else:
print("Il numero {} è un numero DISPARI !!!" .format(n))
|
num = int(input("Digita un numero da 0 a 9999: "))
#n = str(num)
#print("-" * 80)
#print("Unità: {}".format(n[3]))
#print("Decina: {}".format(n[2]))
#print("Centinaia: {}".format(n[1]))
#print("Migliaia: {}".format(n[0]))
#print("-" * 80)
u = num // 1 % 10
d = num // 10 % 10
c = num // 100 % 10
m = num // 1000 % 10
print("-" * 80)
print("Unità: {}".format(u))
print("Decina: {}".format(d))
print("Centinaia: {}".format(c))
print("Migliaia: {}".format(m))
print("-" * 80)
|
global1 = 34
def cambiar_global(var1):
'''Cambiar una variable global
Esta función debe asignarle a la variable global `global1` el valor que se
le pasa como único argumento posicional.
'''
global global1
global1 = var1
# print(var1)
return global1
pass
#cambiar_global(5)
def anio_bisiesto(anio):
'''Responder si el entero pasado como argumento es un año bisiesto
Para determinar si un año es bisiesto, se deben tener en cuenta las
siguientes condiciones:
- Si el año es divisible por 4 es bisiesto, a menos que:
- Si el año es divisible por 100 no es bisiesto a menos que:
- Si el año es divisible por 400 es bisiesto.
Retorna True o False
'''
if anio%4 == 0:
if anio%100 == 0:
if anio%400 == 0:
return True
else:
return False
else:
return True
else:
return False
pass
def contar_valles(lista):
'''Contar el número de valles
Esta función debe recibir como argumento una lista de -1's, 0's y 1's, y lo
que representan son las subidas y las bajadas en una ruta de caminata. -1
representa un paso hacia abajo, el 0 representa un paso hacia adelante y el
1 representa un paso hacia arriba, entonces por ejemplo, para la lista
[-1,1,0,1,1,-1,0,0,1,-1,1,1,-1,-1] representa la siguiente ruta:
/\
/\__/\/ \
_/
\/
El objetivo de esta función es devolver el número de valles que estén
representados en la lista, que para el ejemplo que se acaba de mostrar es
de 3 valles.
'''
cont = 0
temp = False
cont2 = 0
cont3 = 0
longitud = len(lista)
for i in lista:
cont3 += 1
if i == -1:
cont2=cont3
temp = False
while temp == False:
if cont2 < longitud:
if lista[cont2]==1:
cont += 1
temp = True
elif lista[cont2]==0:
cont2 += 1
temp = False
else:
temp = True
else:
temp = True
print(cont)
return cont
pass
#contar_valles([-1,1,0,1,1,-1,0,0,1,-1,1,1,-1,-1])
def saltando_rocas(listarocas):
'''Mínimo número de saltos en las rocas
Esta función hace parte de un juego en el que el jugador debe cruzar un río
saltando de roca en roca hasta llegar al otro lado. Hay dos tipo de rocas,
secas y húmedas, y el jugador debe evitar saltar encima de las húmedas para
no resbalarse y caer. Además el jugador puede saltar 1 o 2 rocas, siempre y
cuando no caiga en una húmeda.
Esta función debe recibir como argumento una lista de ceros y unos. Los ceros
representan las rocas secas y los unos las húmedas.
El objetivo es devolver el número mínimo de saltos que debe realizar el
jugador para ganar la partida
'''
#saltando_rocas = []
#ll = [1,1,0,0]
saltos =0
cont = 0; #=c
cont1 = 0 #i = 0;
longitud = len(listarocas) #l = len(ll)
while cont1 < longitud-1:
if cont1+2 < longitud and listarocas[cont1+2] == 0:
cont += 1
cont1 += 2
else:
cont += 1
cont1 += 1
saltos = cont
# print(saltos)
return(saltos)
saltando_rocas([1,1,0,0])
def pares_medias(listapares):
'''Contar pares de medias
Esta función debe recibir como argumento una lista de enteros. Cada elemento
de esta lista representa el color de una media, y por lo tanto si hay dos
elementos que tienen el mismo entero, esas dos medias tienen el mismo color.
El objetivo de esta función es devolver un diccionario cuyas keys son cada
uno de los colores que se encuentren en la lista, y los valores son la
cantidad de pares que se han encontrado para cada color.
'''
pares= {}
for i in listapares:
if int(listapares.count(i)/2)!=0:
pares[i]= int(listapares.count(i)/2)
print(pares)
return pares
pass
#pares_medias([1,1,2,2,3,1])
# Crear una clase llamada `ListaComa` que reciba en su constructor un iterable
# con el valor inicial para una lista que se guardará en un atributo llamado
# `lista`. Implementar el método __str__ para que devuelva un string con todos
# los elementos del atributo `lista` unidos a través de comas. Ejemplo:
# si `lista` es [1,2,3,4], __str__ debe devolver '1,2,3,4'
class ListaComa:
def __init__(self, lista=[]):
self.lista = lista
def __str__(self):
cadena=""
for i in self.lista:
if cadena == "":
cadena = str(i)
else:
cadena = cadena + "," + str(i)
return cadena
lis = ListaComa([1,2,3])
#print(lis)
# Crear una clase llamada `Persona` que reciba en su constructor como 1er
# argumento un iterable con el valor inicial para una lista que se guardará en
# un atributo llamado `nombres` y como 2do argumento un iterable con el valor
# inicial para una lista que se guardará en un atributo llamado `apellidos`.
# Antes de guardar estos atributos se debe verificar que todos los elementos
# de estas dos listas deben ser de tipo str y procesar todos los elementos de
# cada una de las dos listas para que su primera letra sea mayúscula y las demás
# minúsculas.
#
# Implementar el método `nombre_completo` para que devuelva un string con todos
# los elementos de `nombres` concatenados con espacio, y esto a su vez
# concatenado con todos los elementos de `appelidos` concatenados con espacio.
# Ejemplo:
# si `nombres` es ['Juan', 'David'] y `apellidos` es ['Torres', 'Salazar'],
# el método `nombre completo` debe devolver 'Juan David Torres Salazar'
class Persona:
def __init__(self, nombres=[], apellidos=[]):
self.nombres = nombres
self.apellidos = apellidos
def nombre_completo(self):
cadena1=""
cadena2=""
cadena3=""
for i in self.nombres:
if cadena1 == "":
cadena1 = str(i).capitalize()
else:
cadena1 = cadena1 + " " + str(i).capitalize()
for j in self.apellidos:
if cadena2 == "":
cadena2 = str(j).capitalize()
else:
cadena2 = cadena2 + " " + str(j).capitalize()
cadena3 = cadena1 + " " + cadena2
return cadena3
nom = Persona(["fabian", "emilio"], ["solano", "aragon"])
#print(nom.nombre_completo())
# Crear una clase llamada `Persona1` que herede de la clase `Persona`, y que en su
# constructor reciba además de los atributos del padre, una variable tipo
# `datetime` como 3er argumento para guardar en atributo `fecha_nacimiento`.
#
# Implementar el método `edad` para que devuelva un `int` que represente la edad
# de la persona y que se calcule restando los años entre la fecha actual y
# el atributo `fecha_nacimiento`.
# Ejemplo:
# si `fecha_nacimiento` es 1985-10-21 y la fecha actual es 2020-10-20, el método
# `edad` debe devover 35.
import datetime
class Persona1(Persona):
def __init__(self, nombres, apellidos, fecha_nacimiento):
super().__init__(nombres,apellidos)
self.fecha_nacimiento = fecha_nacimiento
def edad(self):
#fechaactual = datetime.datetime.now()
#fecha_nacimiento = datetime.datetime.strptime("1985-10-21", "%Y-%m-%d")
edad1 = datetime.datetime.now().year - self.fecha_nacimiento.year
edad1 -= ((datetime.datetime.now().month, datetime.datetime.now().day) < (self.fecha_nacimiento.month, self.fecha_nacimiento.day))
return(edad1)
fecha = datetime.datetime.strptime("1985-10-21", "%Y-%m-%d")
edd = Persona1(["fabian", "emilio"], ["solano", "aragon"], fecha)
#print(edd.edad())
|
x=int(input("Введите число: "))
def chetn(x):
if x%2==0:
return("Число четное")
else:
return("Число нечетное")
print(chetn(x))
|
import random
x = random.randint(1,4)
value = input("Я загадал число от 1 до 4. Ты думаешь, что это число: ")
if value:
y = float(value)
if x==y:
print("Ты победил!!")
elif x<y:
print("Нет, мое число меньше...Повторите ее раз!")
else:
print("Нет, мое число больше...Повторите ее раз!")
else:
print("Нужно ввести число!")
|
x=input("Введите время звонка в минутах:")
y=input("Введите код города: ")
if x:
vrem=float(x)
if y:
kod_gor=int(y)
if kod_gor==343: print("Стоимость звонка в городе Екатеринбург:", 15*vrem)
elif kod_gor==381: print("Стоимость звонка в городе Омск:", 18*vrem)
elif kod_gor==473: print("Стоимость звонка в городе Воронеж:", 13*vrem)
elif kod_gor==485: print("Стоимость звонка в городе Ярославль:", 11*vrem)
else: print("Город неопределен")
else:
print("Вы не ввели код города!!!")
else:
print("Вы не ввели время звонка!!!")
|
'''This simple program models using OOP the proces of calculating
the cost of a telephone call.
'''
# Needed for computation of call duration, and to determine whether call
# is on- or off-peak.
import datetime
class Call:
'''Model a call with clas params as below:
:param MINIMUM_COST_NEAR : The applicable minimum cost for a short distance call
:type MINIMUM_COST_NEAR : float, constant
:param MINIMUM_COST_FAR : The applicable minimum cost for a long distance call
:type MINIMUM_COST_FAR : float, constant
:param PER_SECOND_COST_NEAR : The applicable cost per second of a short distance call
:type PER-SECOND_COST_NEAR : float, constant
:param PER_SECOND_COST_FAR : The applicable cost per second of a long distance call
:type PER-SECOND_COST_FAR : float, constant
:param OFF_PEAK_START : Time when off-peak starts
:type OFF_PEAK_START : datetime.time object
:param OFF_PEAK_END : Time when off-peak ends
:type OFF_PEAK_END : datetime.time object
:param DISTANCE_DELIMITER : The preset for boundary value for short distances
:type DISTANCE_DELIMITER : int, constant
:param VAT : The preset for boundary value for short distances
:type VAT : float, constant
'''
# All money is in Ksh.
MINIMUM_COST_NEAR = 10.00
MINIMUM_COST_FAR = 20.00
PER_SECOND_COST_NEAR = 0.50
PER_SECOND_COST_FAR = 0.75
OFF_PEAK_START = datetime.time(19, 0, 0) # 19:00:00
OFF_PEAK_END = datetime.time(6, 59, 59) # 06:59:59
OFF_PEAK_DISCOUNT_NEAR = 0.40
OFF_PEAK_DISCOUNT_FAR = 0.50
DISTANCE_DELIMITER = 50 # km
VAT = 0.14 # Charged on final cost
def __init__(self, call_start=None, call_end=None, long_distant=None, share_call=None):
'''Return an instance of a Call object with instance variables as below
:param call_start : time when call was initiated. Format h:m:s
:type call_start : datetime.time object
:param call_end : time when call was terminated. Format h:m:s
:type call_end : date.time object
:param long_distant : whether call distance exceeds DISTANCE_DELIMITER
:type long_distant : boolean
:param share_call : whether call was a share-call
:type share_call : boolean
'''
self.call_start = call_start
self.call_end = call_end
self.long_distant = long_distant
self.share_call = share_call
def collect_call_time(self):
'''Ask for user-input for call_start and call_end
'''
# Determine call_start and call_end
print("=="*70)
print("\n\n\t\t\tWELCOME TO THIS PROGRAM. IT CALCULATES THE COST OF A TELEPHONE CALL, GIVEN SOME INFO\n\n")
print("=="*70)
call_start = input(
"\n Call started at: Use this format - h:m:s [e.g. 10:00:00] \n\n >>")
call_end = input(
"\n Call finished at: Use this format - h:m:s [e.g. 10:00:00] \n\n >>")
# Convert to objects, and save as instance variables
self.call_start = self.convert_time_to_object(call_start)
self.call_end = self.convert_time_to_object(call_end)
return (self.call_start, self.call_end)
def convert_time_to_object(self, time_input):
'''Global method used to convert input time into a time object
'''
# Time collected into a list of the hours, mins, and secs
time_as_list = time_input.split(':')
# Extract hours (h), minutes (m), seconds (s) from time_as_list and use to make time object
h = int(time_as_list[0])
m = int(time_as_list[1])
s = int(time_as_list[2])
self.time_object = datetime.time(h, m, s)
return self.time_object
def calculate_call_duration(self, call_start, call_end):
'''Calculate length of call in seconds'''
starting_time_in_secs = call_start.hour * 3600 + \
call_start.minute * 60 + call_start.second
ending_time_in_secs = call_end.hour * 3600 + \
call_end.minute * 60 + call_end.second
self.call_duration = ending_time_in_secs - starting_time_in_secs
return self.call_duration
def determine_if_off_peak(self, call_start):
'''Return bool marking call as off-peak or not'''
if call_start >= Call.OFF_PEAK_START:
self.is_off_peak = True
else:
self.is_off_peak = False
return self.is_off_peak
def determine_if_long_distant(self):
'''Return bool indicating whether call is long distant or not'''
call_distance = input(
"\n How far off is this call made? Enter an estimate in km:\n\n >>")
if int(call_distance) >= Call.DISTANCE_DELIMITER:
self.long_distant = True
elif int(call_distance) < Call.DISTANCE_DELIMITER:
self.long_distant = False
return self.long_distant
def determine_if_share_call(self):
'''Return bool marking call as share_call or not'''
is_share_call = input(
"\n Is this a share-call? Enter 'y' for yes, 'n' for no\n\n >>").lower()
if is_share_call == 'y':
self.is_share_call = True
elif is_share_call == 'n':
self.is_share_call = False
return self.is_share_call
def calculate_cost(self):
'''Collect all params, call appropriate method for cost calculation'''
call_start_time, call_end_time = self.collect_call_time()
call_duration = self.calculate_call_duration(call_start_time, call_end_time)
is_off_peak = self.determine_if_off_peak(call_start_time)
is_long_distant = self.determine_if_long_distant()
# Call appropriate cost calculation method
if is_long_distant:
pretax_costs = self.calculate_basic_cost_long_distant(call_duration, is_off_peak)
else:
pretax_costs = self.calculate_basic_cost_short_distant(call_duration, is_off_peak)
# Apply tax
vat = self.calculate_vat(pretax_costs)
# Collect all user-defined call params in a dict
all_call_params = {
"Call Start Time": call_start_time,
"Call End Time": call_end_time,
"Call Duration in Seconds": call_duration,
"Call Off-Peak": is_off_peak,
"Call Long Distant": is_long_distant,
}
# Display everything
self.presentation(all_call_params, pretax_costs, vat)
return pretax_costs
def calculate_basic_cost_long_distant(self, call_duration, is_off_peak):
'''Calculate the basic_call_cost, without VAT or discount'''
basic_cost = Call.MINIMUM_COST_FAR + (Call.PER_SECOND_COST_FAR * call_duration)
discount = 0.00 # Default value of discouunt
if is_off_peak:
discount = Call.OFF_PEAK_DISCOUNT_FAR * basic_cost
discounted_cost = basic_cost - discount
pretax_costs = {
"Basic Cost": basic_cost,
"Discount": discount,
"Discounted Cost": discounted_cost
}
return pretax_costs
def calculate_basic_cost_short_distant(self, call_duration, is_off_peak):
'''Calculate the basic_call_cost, without VAT'''
basic_cost = Call.MINIMUM_COST_NEAR + (Call.PER_SECOND_COST_NEAR * call_duration)
discount = 0.00 # Default value of discouunt
if is_off_peak:
discount = Call.OFF_PEAK_DISCOUNT_NEAR * basic_cost
discounted_cost = basic_cost - discount
pretax_costs = {
"Basic Cost": basic_cost,
"Discount": discount,
"Discounted Cost": discounted_cost
}
return pretax_costs
def calculate_vat(self, pretax_costs):
vat = pretax_costs["Discounted Cost"] * 0.14
return vat
def presentation(self, all_call_params, pretax_costs, vat):
'''Display e'erthing to user'''
print("\n\n")
print("=="*70)
print("\n\nYOUR CALL'S PARAMETERS\n")
for key, value in all_call_params.items():
print(" %s : %s\n" % (key, value))
print("=="*70)
print("\n\nYOUR CALL'S COSTS\n")
for key, value in pretax_costs.items():
print(" %s : Ksh. %s\n\n" % (key, round(value, 2)))
print("=="*70)
print("\n Value Added Tax : Ksh. %s\n" % round(vat, 2))
print("--"*70)
print("\n FINAL COST : Ksh. %s" % round((pretax_costs["Discounted Cost"] + vat), 2))
print("=="*70)
lo_call = Call()
lo_call.calculate_cost()
|
# -*- coding: utf-8 -*-
"""
Created on Wed Jun 19 10:11:08 2019
@author: Hashim
"""
import itertools
fl = lambda ll: [item for sublist in list2d for item in sublist]
fl(list2d)
'''
# goal is to write a program inputting two lists where the 2nd list element is an exponent to the first list element
power = lambda x,y : print(list(a**b for a,b in zip(x,y)))
# why does this work?
power({0:1,1:2,2:3},(2,3,0))
list2d.reverse()
# how to reverse lists recursively?
# inplace operation : doesn't return anything, changes the input data directly
fl = lambda l: print([sublist for sublist in list2d[::-1] for item in sublist[::-1]])
fl(list2d)
try_one = lambda list2d: list(reversed(sublist)for sublist in reversed(list2d))
try_two = lambda l : [list(reversed(el)) if isinstance(el,list) else el for el in reversed(l)]
co = lambda l: [i+1 if isinstance(i,int) else list(map(lambda j: j+1,i))for i in l]
bo = co(list2d)
list3d = [list2d,bo]
# use remove for removing element from list, but pop to remove an element at a specific index
a = [1,2,3]
lambda l : l.pop(0)
a = [1,2,3]
lambda l : l.remove(0)
# what's the difference ?
a.sorted()
print(a)
# sorted actually returns a list, but reversed returns a lambda expression
# verify:
reversed(a)
'''
|
import string
from words import choose_word
from images import IMAGES
import random
'''
Important instruction
* function and variable name snake_case -> is_prime
* contant variable upper case PI
'''
def is_word_guessed(secret_word, letters_guessed):
'''
secret_word: word guess by the user
letters_guessed: list hold all the word guess by the user
returns:
return True (if user guess the world correctly )
return False (wrong selection)
'''
print(secret_word,letters_guessed)
if(len(secret_word)==len(letters_guessed)):
return True
return False
# if you want to test this function please call function -> get_guessed_word("kindness", [k, n, d])
def get_guessed_word(secret_word, letters_guessed):
'''
secret_word: word guess by the user
letters_guessed: list hold all the word guess by the user
returns:
return string which contain all the right guessed characters
Example :-
if secret_word -> "kindness" and letters_guessed = [k, n, s]
return "k_n_n_ss"
'''
index = 0
guessed_word = ""
while (index < len(secret_word)):
if secret_word[index] in letters_guessed:
guessed_word += secret_word[index]
else:
guessed_word += "_"
index += 1
return guessed_word
def get_available_letters(letters_guessed):
'''
letters_guessed: list contains all guessed characters
returns:
it return string which contains all characters except guessed letters
Example :-
letters_guessed = ['e', 'a'] then
return sting is -> `bcdfghijklmnopqrstuvwxyz`
'''
all_chars_atoz=string.ascii_lowercase
str1=""
let_guessedString=str1.join(letters_guessed)
letters_left = [i for i in all_chars_atoz+let_guessedString if i not in all_chars_atoz or i not in let_guessedString]
str2=""
string_Letters_left=str2.join(letters_left)
return string_Letters_left
def showMan(rem):
print(IMAGES[rem])
def isValid(letter):
if(len(letter)==1 and letter.islower()):
return True
return False
def hangman(secret_word):
'''
secret_word (string) : secret word to guessed by the user.
Steps to start Hangman:
* In the beginning of the game user will know about the total characters in the secret_word
* In each round user will guess one character
* After each character give feedback to the user
* right or wrong
* Display partial word guessed by the user and use underscore in place of not guess word
'''
print("Welcome to the game, Hangman!")
print("I am thinking of a word that is {} letters long.".format(
str(len(secret_word))), end='\n\n')
letters_guessed = []
t=1
remaining_lives=8
c=0
hint_used=False
while(t==1):
print("{} lives left".format(remaining_lives))
if(remaining_lives>0):
available_letters = get_available_letters(letters_guessed)
print("Available letters: {} ".format(available_letters))
guess = input("Please guess a letter: ")
letter = guess.lower()
if(letter!="hint" and not isValid(letter)):
print("Invalid input..Enter again")
continue
if(letter=="hint"):
if hint_used==False:
hint_used=True
lst=[]
print("hint worked")
print(available_letters)
for i in secret_word:
lst.append(i)
print(letters_guessed)
# secret_word-letters_guessed
li_dif = [i for i in lst + letters_guessed if i not in lst or i not in letters_guessed]
letter=random.choice(li_dif)
else:
print("Sorry buddy you have used your hint")
continue
if letter in secret_word:
c+=1
letters_guessed.append(letter)
print("Good guess: {} ".format(
get_guessed_word(secret_word, letters_guessed)))
if is_word_guessed(secret_word, letters_guessed) == True:
t=0
print(" * * Congratulations, you won! * * ", end='\n\n')
else:
remaining_lives-=1
# 7->0
showMan(8-(remaining_lives+1))
print("Oops! That letter is not in my word: {} ".format(
get_guessed_word(secret_word, letters_guessed)))
else:
t=0
print("Game Over!!!!You ran out of lives")
# Load the list of words into the variable wordlist
# So that it can be accessed from anywhere in the program
secret_word = choose_word()
hangman(secret_word)
|
print('Welcome')
#print('08-15-2021')
h = float(input("What is your hight?"))
w = float(input('What is your weight?'))
imc = round(w/(h*h),1)
meta = round(float(25*h*h),1)
print('IMC')
print(imc)
if imc > 25.0:
print('Over weight')
print('Your target is: ')
print(f"{meta}Kg")
else:
print('You got it!')
print(' ')
print('End the program!')
|
"""
Observer pattern implementation.
Any observable object shall inherit from Observable, and an observer from
Observer.
"""
from abc import ABC, abstractmethod
class Observer(ABC):
"""
Observer class needs to be added in Observable container of Observers.
Implement update() to define what happens on Observable notifications.
"""
@abstractmethod
def update(self, data: any) -> None:
"""
namedtuple from collections python module is recommended for passing
data to observers.
:param data: any, use namedtuple! or whatever you want.
"""
pass
class Observable(ABC):
"""
Observable keeps a list of Observers, and it notifies them when method
notify() is called. Use the different methods to deal with Observers.
"""
@abstractmethod
def add_observer(self, observer: Observer) -> None:
pass
@abstractmethod
def remove_observer(self, observer: Observer) -> None:
pass
@abstractmethod
def notify_observers(self) -> None:
"""
Method to invoke for observers notification.
"""
pass
|
#need a list
weight_list= []
#enter weights/print list
for i in range(4):
val = float(input("Enter weight " + str(i+1) + ": "))
weight_list.append(val)
print("Weights:", weight_list)
#calculate total/average and print
total = 0.0
for i in range(len(weight_list)):
total = total + weight_list[i]
average = total / len(weight_list);
print("Average weight:", average)
#find da maximum and print
maximum = weight_list[0]
for i in range(len(weight_list)):
if weight_list[i] > maximum:
maximum = weight_list[i]
print("Max Weight:", maximum)
#pick a number and convert
index = int(input("Enter a list index location (1 - 4): "))
if index < 1 or index > 4:
print("Invalid index!")
else:
print("Weight in pounds:", weight_list[index-1])
print("Weight in kilograms:", (weight_list[index-1]/2.2))
#sort light to heavy
for i in range(len(weight_list)):
minPos = i
for j in range(i + 1, len(weight_list)):
if weight_list[j] < weight_list[minPos]:
minPos = j
if i != minPos:
x = weight_list[i]
weight_list[i] = weight_list[minPos]
weight_list[minPos] = x
print("Sorted list:", weight_list)
|
arrow_base_height = int(input('Enter arrow base height:\n'))
arrow_base_width = int(input('Enter arrow base width:\n'))
arrow_head_width = int(input('Enter arrow head width:\n'))
while arrow_head_width <= arrow_base_width:
arrow_head_width = int(input("Enter arrow head width:"))
print
for i in range(arrow_base_height):
for j in range(arrow_base_width):
print ("*", end=''),
print
for i in range(arrow_head_width):
for j in range(arrow_head_width - i):
print ("*", end=''),
print
|
import collections
def equalizeArray(arr):
arrCount = collections.Counter(arr)
return len(arr)-arrCount.most_common(1)[0][1]
if __name__ == '__main__':
n = int(input())
arr = list(map(int, input().rstrip().split()))
result = equalizeArray(arr)
print(str(result))
|
import random
import data
import distance
import prototype
class clustering:
def __init__(self, data, clusters, centroids, distance=distance.euclidean):
self.data = data
self.clusters = clusters
self.centroids = centroids
self.distance = distance
def source_data_summary(self):
"""
Produces a summary in the form min-->max (avg) for each attribute of the source data
"""
attributes = range(len(self.data[0]))
attr_ranges = [(min([obj[i] for obj in self.data]), max([obj[i] for obj in self.data]))
for i in attributes]
attr_averages = [sum([obj[i] for obj in self.data])/len(self.data) for i in attributes]
attr_strings = []
for i in attributes:
attr_strings.append("%.3f-->%.3f (%.3f)" % \
(attr_ranges[i][0],attr_ranges[i][1], attr_averages[i]))
return "[%s]" % ', '.join(attr_strings)
def describe(self):
sse_values = []
for j in range(i):
sse_values.append(self.cluster_sse(j))
print "%d {size: %d, sse: %f, centroid:[%s]}" % \
(j,
len(self.clusters[j]),
sse_values[j],
', '.join(['{:.5}'.format(attr_val) for attr_val in self.centroids[j]]))
total_sse = sum(sse_values)
print "total sse: %f" % total_sse
print "\n"
def cluster_sse(self, index):
return sum([pow(self.distance(self.data[object_num], self.centroids[index]), 2)
for object_num in self.clusters[index]])
def total_sse(self):
return sum([self.cluster_sse(i) for i in range(len(self.clusters))])
@staticmethod
def kmeans(data, k=4, distance=distance.euclidean, prototype=prototype.rand):
"""
A static factory method providing a kmeans clustering of the source data.
"""
result_clustering = clustering(data, clusters=[], centroids=prototype(data, k))
attributes = range(len(data[0]))
clusters_last = None
for t in range(1, 101):
result_clustering.clusters = [[] for i in range(k)]
#assign each object to the closest centroid
for object_num in range(len(data)):
obj = data[object_num]
assigned_cluster_num = random.choice(range(k))
for cluster_num in range(k):
d = distance(result_clustering.centroids[cluster_num], obj)
if d < distance(result_clustering.centroids[assigned_cluster_num], obj):
assigned_cluster_num = cluster_num
result_clustering.clusters[assigned_cluster_num].append(object_num)
#terminate the loop if the centroids list hasn't changed
if result_clustering.clusters == clusters_last: break
clusters_last = result_clustering.clusters
#recompute the centroid of each cluster
for i in range(k):
attr_averages = [0.0] * len(attributes)
if len(result_clustering.clusters[i]) > 0:
for object_num in result_clustering.clusters[i]:
for attr_num in attributes:
attr_averages[attr_num] += data[object_num][attr_num]
for attr_num in attributes:
attr_averages[attr_num] /= len(result_clustering.clusters[i])
result_clustering.centroids[i] = attr_averages
print "kmeans finished after %d iterations" % t
return result_clustering
iris_data, iris_keys = data.iris()
summary_stats = None
#for euclidean
optimal_clustering = 0
minimal_sse = 9999
all_clusterings = []
for t in range(20):
i = 3
new_clustering = clustering.kmeans(iris_data, k=i, distance=distance.euclidean, prototype=prototype.avg)
if summary_stats == None:
summary_stats = new_clustering.source_data_summary()
print "iris statistics:"
print summary_stats
print "kmeans result clusters based on euclidean distance for k = %d (trial %d):" % (i, t)
new_clustering.describe()
current_sse = new_clustering.total_sse()
if(current_sse < minimal_sse):
optimal_clustering = t
minimal_sse = current_sse
all_clusterings.append(new_clustering)
print "optimal clustering:"
all_clusterings[optimal_clustering].describe()
|
from collections import deque
class LRU_Cache(object):
def __init__(self, capacity):
# Initialize class variables
self.size = capacity # cache size = queue size
self.hash = {}
self.q = deque()
def get(self, key):
# Retrieve item from provided key. Return -1 if nonexistent.
if key in self.hash:
self.reorder_key(key)
print(self.hash[key])
return self.hash[key]
else:
print(-1)
return -1
def set(self, key, value):
# Set the value if the key is not present in the cache.
if key not in self.hash:
self.check_size()
self.hash[key] = value
self.q.append(key)
else:
self.reorder_key(key)
def check_size(self):
if len(self.q) == self.size:
del self.hash[self.q.popleft()]
def reorder_key(self, key):
print('queue before reorder: ', self.q)
self.q.remove(key) # remove first occurence from queue
self.q.append(key) # append referenced key to the end of the queue
print('queue after reorder: ', self.q)
our_cache = LRU_Cache(5)
our_cache.set(1, 'abba')
our_cache.set(2, 'baab')
our_cache.set(5, 'cappa')
our_cache.set(9, 'yippie')
our_cache.set(5, 'cappa')
our_cache.get(1) # returns abba
our_cache.get(2) # returns baab
our_cache.get(3) # return -1
|
'''Slice'''
a = [1,12,23,34,45,56, 3, 5, 36, 75, 81, 2]
b = [2, 4, 6, 7, 8, 57 ,89, 9]
'''Print out the 2nd to the 5th elements of list "a"'''
print(a[1:5])
'''Create a list that contains the 4th to the 8th element of "a" and the 1st to the 3rd element of "b"'''
c = a[3:8] + b[0:3]
print(c)
'''Append "a" with the 3rd to the 5th elements of "c"'''
a += c[2:5]
print(a)
'''Create a list that contains the 1st to the 3rd element of "a", the 4th to the 5th element of "b", and the 6th to the 7th element of "c"'''
d = a[0:3] + b[3:5] + c[5:7]
print(d)
'''Append "c" with the last 4 elements of "d"'''
c += d[len(d) - 4:len(d)]
print(c)
'''Set list "a" to the first 3 values of d'''
a = d[0:3]
print(a)
|
class Solution:
#O(NlogN) time(sort)
#First sort the input array by two attributes:
#(1) height, with reverse order(higher people in front)
#(2) k, with normal order
#Then we insert the sorted array into another array with the rule given.
def reconstructQueue(self, people):
"""
:type people: List[List[int]]
:rtype: List[List[int]]
"""
people=sorted(people, key=lambda p:(-p[0], p[1]))
r=[]
for p in people:
r.insert(p[1], p)
return r
|
# 循环语句
# py中所有的计数都是从0开始的
# for i in range(10):
# print(i)
lists = [9, 8, 6, 7, 15, 3, 5, 6, 3, 4, 6, 3]
a = 0
for i in lists:
if i == 6:
del lists[a]
a = a + 1
print(lists)
# count = 10
#
# while count < 0:
# count = count - 1
# print(count)
# 打印:0123456789
# 打印:0 2 4 6 8 10
# a = 0
# while a <= 10:
# print(a)
# a = a + 2
|
"""This is the simple implementation of a batch gradient descent algorithm.
Partially inspired by https://gist.github.com/marcelcaraciolo/1321575
Written by Sarunas Girdenas, [email protected], July, 2014"""
import numpy as np
import matplotlib.pyplot as plt
# Import some data
Data = np.genfromtxt('some_data_file.txt',usecols=(0,1),delimiter=',',dtype=None)
# Name the first and second variables
Stock_Pr = Data[0:len(Data),0]
Index_Pr = Data[0:len(Data),1]
# clear redundand Data
del Data
# Let's do gradient descent now
g = Stock_Pr.size # size of the sample
theta = np.zeros([2,1]) # container for theta
theta[0,0] = 5
theta[1,0] = 3 # initial guesses for theta
alpha = 0.01 # learning rate (step of algorithm)
# set the hypothesis, in our case it is:
# y = theta_0 + theta_1*X
# Index_pr = alpha + beta*Stock_Pr
X = np.array([Stock_Pr])
y = np.array([Index_Pr])
# Add column of 1 to X or an intercept
X = np.concatenate((np.ones([g,1]),X.T),axis=1)
# Define cost function
def cost_f(X,y,theta):
training = y.shape[1]
pred = X.dot(theta).flatten()
sq_err = (pred - y) ** 2
J = (1.0 / (2*training)) * sq_err.sum()
return J
m = g # sample size
max_iter = 10000 # No of maximum iterations
no_iter = 0 # initialize
Er = 0.00000001 # tolerance for error
theta_0 = np.zeros([max_iter,1]) # empty array to store theta_0
theta_1 = np.zeros([max_iter,1]) # empty array to store theta_1
J_loss_hist = np.zeros([max_iter,1]) # empty array to store loss function values
J_loss_new = 0 # initialize loss function value
J_loss = cost_f(X,y,theta) # initial loss
# Gradient Descent Algorithm
while J_loss - J_loss_new > Er:
no_iter = no_iter + 1
J_loss_hist [no_iter,0] = cost_f(X,y,theta)
J_loss = cost_f(X,y,theta)
predictions = X.dot(theta).flatten()
err_x1 = (predictions - y) * X[:,0]
err_x2 = (predictions - y) * X[:,1]
theta[0][0] = theta[0][0] - alpha * (1.0/m) * err_x1.sum()
theta[1][0] = theta[1][0] - alpha * (1.0/m) * err_x2.sum()
J_loss_new = cost_f(X,y,theta)
theta_0[no_iter][0] = theta[0][0]
theta_1[no_iter][0] = theta[1][0]
# Compare gradient descent results with OLS
X2 = np.concatenate((np.ones([g,1]),np.array([Stock_Pr]).T),axis=1)
beta2 = (np.linalg.inv(X2.T.dot(X2))).dot(X2.T).dot(y.T)
print 'Algorithm Converged in', no_iter, 'Iterations!'
print 'Values from Gradient Descent'
print theta
print '================'
print 'Values from OLS'
print beta2
# Do the scatter plot for the raw data
plt.scatter(Stock_Pr,Index_Pr)
plt.xlabel('Stock Price')
plt.ylabel('Index Price')
plt.title('Scatter Plot of Raw Data')
plt.show()
# Construct the array of predicted values
X3 = np.zeros([g,2])
X3[:,0] = np.ones([g])
X3[:,1] = np.asarray(range(1,Stock_Pr.size+1))
Y_pred = X3.dot(theta)
# Plot the fitted line on the data
plt.scatter(Stock_Pr,Index_Pr)
plt.plot(Y_pred,'r')
plt.xlabel('Stock Price')
plt.ylabel('Index Price')
plt.title('Scatter Plot of Variables and Fitted Line')
plt.show()
|
import random
# input
print("Let's play rock, paper, scissors!")
user_choice = input("What do you choose - rock, paper, or scissors?\n")
computer_choice = random.choice(["scissors", "rock", "paper"])
result = ""
# process
if computer_choice == user_choice:
result = "It's a tie game!"
elif user_choice == "rock" and computer_choice == "scissors":
result = "YOU WIN!"
elif user_choice == "paper" and computer_choice == "rock":
result = "YOU WIN!"
elif user_choice == "scissors" and computer_choice == "paper":
result = "YOU WIN!"
else:
result = "YOU LOSE :("
# output
print("You chose: " + user_choice)
print("The computer chose: " + computer_choice)
print(result)
|
# Initialize for all GPAs
overall_count = 0
overall_points = 0
overall_gpa = 0
grade= ""
active = True
grades = {"A+": 4.2,
"A": 4.0,
"A-": 3.9,
"B+": 3.7,
"B": 3.2,
"B-": 3.0,
"C+": 2.8,
"C": 2.2,
"C-": 2.0,
"D+": 1.8,
"D": 1.2,
"F": 0
}
# Get the first input into variable grade
print("This program takes your entered grades and calculates your GPA for you.")
grade_prompt = "Enter your letter grade for a course: \n"
# def gradeInit():
# grade = input("Enter your letter grade for a course: \n")
# grade = user_grade.replace(" ", "")
# grade = grade.lower()
while active:
grade = input(grade_prompt)
one_points = 0
one_count = 0
if grade == "quit":
active = False
else:
if grade in grades:
while grade != "":
if grade not in grades:
print("Sorry the grade you entered is not valid.")
elif grade in grades:
one_count += 1
one_points += grades[grade]
grade = input(grade_prompt)
overall_points += one_points
overall_count += one_count
overall_gpa = overall_points / overall_count
print("GPA is ", ("%.2f" % overall_gpa))
|
import csv
from utils import *
def nameyear(pm):
return pm["County"] + pm["Year"]
def newCounty(pm, withYear):
newCounty = {}
#set county name
newCounty["Name"] = pm["County"]
#set establishment and changeover numbers
newCounty["EstNum"] = 0
newCounty["ChangeNum"] = 0
if isChangeover(pm):
newCounty["ChangeNum"] = 1
else:
newCounty["EstNum"] = 1
#set year
if withYear == 1:
newCounty["Year"] = pm["Year"]
else:
newCounty["Year"] = "-"
return newCounty
def increment(Counties, pm):
for County in Counties:
if (pm["County"] == County["Name"]) and (County["Year"] in [pm["Year"],"-"]):
if isChangeover(pm):
County["ChangeNum"] = County["ChangeNum"] + 1
else:
County["EstNum"] = County["EstNum"] + 1
return Counties
print(__name__)
if __name__== "__main__":
PM = getLinesCSV("data/postmasters.csv")
Counties = []
CountyNames = set()
CountyNameYears = set()
#cycle through postmasters
for pm in PM:
#if county has not been encountered, create two new entries: one for the postmaster's year and one for all years
if pm["County"] not in CountyNames:
Counties.append(newCounty(pm, 1))
Counties.append(newCounty(pm, 0))
#add to set so that, on later iterations, we know the counties have already been seen
CountyNames.add(pm["County"])
CountyNameYears.add(nameyear(pm))
#if the county does not have an entry for the postmaster's year, create one
elif nameyear(pm) not in CountyNameYears:
#increment the total for the county
Counties = increment(Counties,pm)
Counties.append(newCounty(pm,1))
#add to set
CountyNameYears.add(nameyear(pm))
#if both entries exist, increment
else:
Counties = increment(Counties,pm)
writeCSV(Counties, "data/counties.csv")
|
import random
# greeting = '안녕하세요.'
# for i in range(5):
# print(greeting)
# n = 0
# while n < 5:
# print(greeting)
# n += 1
# tiny_dust = 130
# if tiny_dust >= 150:
# print("매우나쁨")
# elif tiny_dust > 80, 150 <= tiny_dust:
# print("나쁨")
# elif tiny_dust > 30, 80 <= tiny_dust:
# print("보통")
# else:
# print("정상")
numbers = random.sample(range(1,46), 6)
print(numbers)
|
import nmap
print("*.*.*.*.*.*.*.*.*.*.*.*.*..*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*")
print("<*W*E*L*L*C*O*M*E**T*O**N*A*M*P**S*C*A*N*N*E*R**I*N**P*Y*T*H*O*N*3*_*>")
print("*.*.*.*.*.*.*.*.*.*.*.*.*..*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*")
scanner = nmap.PortScanner()
ip_addr = input("< Enter The IP Address You Want TO Scan >: ")
print("This is the IP you Want to Scan:", ip_addr)
type(ip_addr)
resp = input("""\nPlease enter the type of scan you want to run
1)SYN ACK Scan
2)UDP Scan
3)Comprehensive Scan
4)Regular Scan
5)OS Detection
6)Multiple IP inputs
7)Ping Scan
8)Full Scan\n""")
print("You have selected option: ", resp)
if resp == '1':
print("Nmap Version: ", scanner.nmap_version())
scanner.scan(ip_addr,'1-65535', '-v -sS')
print(scanner.scaninfo())
print("Ip Status: ", scanner[ip_addr].state())
print("protocols:",scanner[ip_addr].all_protocols())
print("Open Ports: ", scanner[ip_addr]['tcp'].keys())
elif resp == '2':
print("Nmap Version: ", scanner.nmap_version())
scanner.scan(ip_addr, '1-65535', '-v -sU')
print(scanner.scaninfo())
print("Ip Status: ", scanner[ip_addr].state())
print("protocols:",scanner[ip_addr].all_protocols())
print("Open Ports: ", scanner[ip_addr]['udp'].keys())
elif resp == '3':
print("Nmap Version: ", scanner.nmap_version())
scanner.scan(ip_addr, '1-65535', '-v -sS -sV -sC -A -O')
print(scanner.scaninfo())
print("Ip Status: ", scanner[ip_addr].state())
print(scanner[ip_addr].all_protocols())
print("Open Ports: ", scanner[ip_addr]['tcp'].keys())
elif resp == '4':
print("Nmap Version: ", scanner.nmap_version())
scanner.scan(ip_addr)
print(scanner.scaninfo())
print("Ip Status: ", scanner[ip_addr].state())
print("protocols:",scanner[ip_addr].all_protocols())
print(scanner[ip_addr].all_protocols())
print("Open Ports: ", scanner[ip_addr]['tcp'].keys())
elif resp == '5':
print(scanner.scan[ip_addr], arguments="-O"),+['scan'][ip_addr],['osmatch']
elif resp == '6':
ip_addr = input()
print("Nmap Version: ", scanner.nmap_version())
scanner.scan(ip_addr,'1-65535', '-v -sS')
print(scanner.scaninfo())
print("Ip Status: ", scanner[ip_addr].state())
print("protocols:",scanner[ip_addr].all_protocols())
print("Open Ports: ", scanner[ip_addr]['tcp'].keys())
elif resp == '7':
scanner.scan(hosts=ip_addr, arguments='-n -sP -PE -PA')
hosts_list = [(x, scanner[x]['status']['state']) for x in scanner.all_hosts()]
for host, status in hosts_list:
print('{0}:{1}'.format(host, status))
elif resp == '8':
print("Nmap Version: ", scanner.nmap_version())
scanner.scan(ip_addr, '1-65535', '-vvv -sV -sC -A -T4')
print(scanner.scaninfo())
print("Ip Status: ", scanner[ip_addr].state())
print("protocols:",scanner[ip_addr].all_protocols())
print(scanner[ip_addr].all_protocols())
print("Open Ports: ", scanner[ip_addr]['tcp'].keys())
|
import pandas as pd
class OpenFiles:
'this class has opens and closes the file to process using pandas library, it has the openfile method which accepts arguments, accepts either(txt,csv,tsv)'
def __init__(self,file_type):
self.file_type = file_type
def open_files(self):
file_extention = self.file_type.split('.')[-1].lower()
pd.set_option('display.max_rows',None,'display.max_columns',None)
try:
if file_extention == 'csv':
yield pd.read_csv(f'./files/{self.file_type}')
elif file_extention == 'tsv':
yield pd.read_csv(f'./files/{self.file_type}', sep='\t')
else:
yield pd.read_csv('./files/error_mesages.txt')
except:
return 'invalid file format'
class OpenCloseFiles:
'this class uses the opens files via context manager, accepts either(txt,csv,tsv)'
def __init__(self,file_type):
self.file_type = file_type
def open_files(self):
file_extention = self.file_type.split('.')[-1].lower()
try:
if file_extention == 'txt' or 'csv' or 'tsv':
with open(f'./files/{self.file_type}','r') as open_file:return open_file.readlines()
except:
with open('./files/error_mesages.txt','r') as read_error:return read_error.readlines()
|
import csv
with open ("oui.csv") as input_csv:
entries = csv.reader(input_csv, delimiter =',')
output_txt = open("oui.txt", "w")
#Create the starting part of the file
output_txt.write("OUI/MA-L\nOrganization\ncompany_id\nOrganization\n\nAddress\n\n")
first = True
for row in entries:
if first:
first = False
continue
#Extract the relevant entries required from each row
mac = row[1]
vendor = row[2]
address = row[3]
#Recreate the text file based on the inputs
output_txt.write(mac[0:2]+"-"+mac[2:4]+"-"+mac[4:6]+" (hex) "+vendor+"\n")
output_txt.write(mac+" (base 16) "+vendor+"\n")
output_txt.write(" "+address+"\n")
output_txt.write(" "+address+"\n")
output_txt.write(" "+address+"\n")
output_txt.write("\n")
output_txt.close()
|
class Employee:
def __init__(self,name,yearsOfExperience,pastEmployers):
self.name = name
self.yearsOfExperience = yearsOfExperience
self.pastEmployers = pastEmployers
def pastEmployers(self):
return(self,pastEmployers)
def yearsOfExperience(self,y):
self,yearsOfExperience = y
def needsPromotion(self):
if(self.yearsOfExperience > 5):
return(True)
else:
return(False)
def main():
employee1 = Employee(name = 'John' ,yearsOfExperience = 6,pastEmployers = [])
employee2 = Employee(name = "joe",yearsOfExperience = 8,pastEmployers = "cook")
print(employee1.needsPromotion())
if __name__ == "__main__":
main()
|
def main():
mylist = ['Tuesday','Wednesday','Friday']
print(mylist)
replacement_day = input("Enter the day: ")
mylist[0] = replacement_day
print(mylist)
remove_day = int(input("Enter the index of the day: "))
del mylist[remove_day]
print(mylist)
if __name__ == "__main__":
main()
|
s = input("Enter a string:")
t = ""
for i in s:
if i == " ":
t = t + '_'
else:
t = t+i
print(t)
|
text1 = str(input("Enter your first name:"))
if "Moaksh" in text1:
print("Moaksh Kakkar the great!!")
else:
text2 = str(input("Enter yout second name:"))
space = " "
print(text1 + space + text2)
|
num1 = int(input("Enter 1st number : "))
num2 = int(input("Enter 2nd number : "))
min = num1
if num2 < num1:
min = num2
for i in range(1, min + 1):
if((num1 % i) == 0 and (num2 % i) == 0):
hcf = i
print("HCF of", num1, "and", num2, ":", hcf)
|
str = "Hello, World!"
#str[start: stop:step]
# slicing str
print("Basic slicing")
print("1", str[1:])
print("2", str[:5])
print("3", str[6:10])
print("4", str[-12:-6])
# step string slicing
print("Step string slicing")
print("1", str[:12:2])
# reverse slicing
print("Reverse slicing")
print("1", str[::-1])
|
ask = ("avashah")
odd = 1
empty = ""
for x in ask:
odd = odd + 1
if odd%2 ==0:
empty = empty + ((x.upper()))
else:
empty = empty + ((x.lower()))
print(empty)
ask = ("avashah")
odd = 1
anotherempty = ""
for t in ask:
odd = odd + 1
if odd%2 ==0:
t = t.upper()
if t =="A" or t == "E" or t == "I" or t == "U" or t == "O":
anotherempty = anotherempty + ("*")
else:
anotherempty = anotherempty + t
else:
anotherempty = anotherempty + (t.lower())
print("asterik: " + anotherempty)
thisway = 0
thatway = 0
ask = ("avashah()(((")
for y in ask:
if "(" in y:
thisway = thisway + 1
elif ")" in y:
thatway = thatway + 1
if thisway == thatway:
print("Balanced? True.")
else:
print("Balanced? False.")
|
"""
Project: Coffee Machine in Python
Stage #5: On a coffee loop
Description
But just one action isn’t interesting.
Let's improve the program so it can do multiple actions, one after another.
The program should repeatedly ask what the user wants to do.
If the user types "buy", "fill" or "take", then just do what the program did in the previous step.
However, if the user wants to switch off the coffee machine, he should type "exit".
Then the program should terminate.
Also, when the user types "remaining", the program should output all the resources that the coffee machine has.
Also, do not forget that you can be out of resources for making coffee.
If the coffee machine doesn’t have enough resources to make coffee,
the program should output a message that says it can't make a cup of coffee.
And the last improvement to the program at this step—if the user types "buy" to buy a cup of coffee and then changes his mind,
he should be able to type "back" to return into the main cycle.
Output example
Your coffee machine should have the the same initial resources as in the example
(400 ml of water, 540 ml of milk, 120 g of coffee beans, 9 disposable cups, $550 in cash.
Write action (buy, fill, take, remaining, exit): remaining
The coffee machine has:
400 of water
540 of milk
120 of coffee beans
9 of disposable cups
$550 of money
Write action (buy, fill, take, remaining, exit): buy
What do you want to buy? 1 - espresso, 2 - latte, 3 - cappuccino, back - to main menu: 2
I have enough resources, making you a coffee!
Write action (buy, fill, take, remaining, exit): remaining
The coffee machine has:
50 of water
465 of milk
100 of coffee beans
8 of disposable cups
$557 of money
Write action (buy, fill, take, remaining, exit): buy
What do you want to buy? 1 - espresso, 2 - latte, 3 - cappuccino, back - to main menu: 2
Sorry, not enough water!
Write action (buy, fill, take, remaining, exit): fill
Write how many ml of water do you want to add: 1000
Write how many ml of milk do you want to add: 0
Write how many grams of coffee beans do you want to add: 0
Write how many disposable cups of coffee do you want to add: 0
Write action (buy, fill, take, remaining, exit): remaining
The coffee machine has:
1050 of water
465 of milk
100 of coffee beans
8 of disposable cups
$557 of money
Write action (buy, fill, take, remaining, exit): buy
What do you want to buy? 1 - espresso, 2 - latte, 3 - cappuccino, back - to main menu: 2
I have enough resources, making you a coffee!
Write action (buy, fill, take, remaining, exit): remaining
The coffee machine has:
700 of water
390 of milk
80 of coffee beans
7 of disposable cups
$564 of money
Write action (buy, fill, take, remaining, exit): take
I gave you $564
Write action (buy, fill, take, remaining, exit): remaining
The coffee machine has:
700 of water
390 of milk
80 of coffee beans
7 of disposable cups
0 of money
Write action (buy, fill, take, remaining, exit): exit
"""
class CoffeeMachine:
state_output_template = \
'\n' \
'The coffee machine has:\n' \
'{} of water\n' \
'{} of milk\n' \
'{} of coffee beans\n' \
'{} of disposable cups\n' \
'${} of money'
coffee_mapping = {
1: (250, 0, 16, 1, 4),
2: (350, 75, 20, 1, 7),
3: (200, 100, 12, 1, 6),
}
def __init__(self):
self.water = 400
self.milk = 540
self.coffee_beans = 120
self.disposable_cups = 9
self.money = 550
def make_coffee(self, coffee_number):
ingredients = self.coffee_mapping[coffee_number]
success_flag = True
if self.water < ingredients[0]:
success_flag = False
print('Sorry, not enough water!')
if self.milk < ingredients[1]:
success_flag = False
print('Sorry, not enough milk!')
if self.coffee_beans < ingredients[2]:
success_flag = False
print('Sorry, not enough coffee beans!')
if self.disposable_cups < ingredients[3]:
success_flag = False
print('Sorry, not enough disposable cups!')
if success_flag:
self.water -= ingredients[0]
self.milk -= ingredients[1]
self.coffee_beans -= ingredients[2]
self.disposable_cups -= ingredients[3]
self.money += ingredients[4]
return success_flag
def print_state(self):
print(self.state_output_template.format(
self.water, self.milk, self.coffee_beans, self.disposable_cups, self.money,
))
if __name__ == '__main__':
coffee_machine = CoffeeMachine()
while True:
action = input('Write action (buy, fill, take, remaining, exit):').strip()
if action == 'remaining':
coffee_machine.print_state()
elif action == 'exit':
break
elif action == 'take':
print(f'I gave you ${coffee_machine.money}')
coffee_machine.money = 0
elif action == 'fill':
print()
coffee_machine.water += int(input('Write how many ml of water do you want to add:'))
coffee_machine.milk += int(input('Write how many ml of milk do you want to add:'))
coffee_machine.coffee_beans += int(input('Write how many grams of coffee beans do you want to add:'))
coffee_machine.disposable_cups += int(input('Write how many disposable cups of coffee do you want to add:'))
elif action == 'buy':
coffee_number = input('What do you want to buy? 1 - espresso, 2 - latte, 3 - cappuccino, back - to main menu:')
if coffee_number == 'back':
continue
if coffee_machine.make_coffee(int(coffee_number)):
print('I have enough resources, making you a coffee!')
print()
|
"""
Project: Smart Calculator (Python)
Stage #3: Count them all
Description
At this stage, the program should read an unlimited sequence of numbers from the standard input and calculate their sum.
Also, add a /help command to print some information about the program.
Input/Output example
The example below shows input and the corresponding output. Your program should work in the same way.
4 5 -2 3
10
4 7
11
6
6
/help
The program calculates the sum of numbers
/exit
Bye!
"""
if __name__ == '__main__':
while True:
input_line = input().strip()
if input_line == '':
continue
if input_line == '/help':
print('The program calculates the sum of numbers')
if input_line == '/exit':
print('Bye!')
break
arguments = map(int, input_line.split())
print(sum(arguments))
|
"""
Project: Hangman
Stage #6: Victory!
Add the victory condition
The recent version of the game is not as fun until we don't handle the player's victory.
A player wins when all the letters are guessed and there are still some tries left
(except the player uses his last try and actually guesses the word, he's lucky then!).
Notice that, in the previous stage, the user has only 8 attempts to guess letters.
The number of attempts was decreasing despite the fact that the user guessed one of the hidden letters in the word!
It needs to be changed - now the number of attempts should decrease only if there are no words to uncover.
And yes, if the word to guess is -a-a at the moment and the user printed a you should count this as a fail
and reduce the number of attempts by 1 (later we'll fix it in favor of the user).
Print No such letter in the word if the word guessed by the program doesn't contain this letter.
Print No improvements if the guessed word contains this letter but the user tried this letter before.
Input and output example
H A N G M A N
----------
Input a letter: a
-a-a------
Input a letter: i
-a-a---i--
Input a letter: o
No such letter in the word
-a-a---i--
Input a letter: o
No such letter in the word
-a-a---i--
Input a letter: p
-a-a---ip-
Input a letter: p
No improvements
-a-a---ip-
Input a letter: h
No such letter in the word
-a-a---ip-
Input a letter: k
No such letter in the word
You are hanged!
H A N G M A N
----
Input a letter: j
j---
Input a letter: i
No such letter in the word
j---
Input a letter: g
No such letter in the word
j---
Input a letter: a
ja-a
Input a letter: v
java
You guessed the word!
You survived!
"""
import random
from collections import defaultdict
n_attempts = 8
game_dictionary = ['python', 'java', 'kotlin', 'javascript']
correct_word = random.choice(game_dictionary)
current_word = ['-'] * len(correct_word)
entered_letters = set()
letter_positions = defaultdict(list)
for idx, _letter in enumerate(correct_word):
letter_positions[_letter].append(idx)
print('H A N G M A N')
while n_attempts > 0:
print('\n', ''.join(current_word), sep='')
letter = input('Input a letter:').strip()
assert len(letter) == 1
if letter in letter_positions:
if letter in entered_letters:
print('No improvements')
n_attempts -= 1
continue
entered_letters.add(letter)
for idx in letter_positions[letter]:
current_word[idx] = letter
if ''.join(current_word) == correct_word:
print()
print(correct_word)
print('You guessed the word!\nYou survived!')
break
else:
print('No such letter in the word')
n_attempts -= 1
else:
print('You are hanged!')
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Nov 25 23:23:12 2017
@author: akhiltayal
"""
# Multiple Linear Regression
# Importing Libraries
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
def importData(filename):
data = pd.read_csv(filename, header=None, dtype=float)
X = data.iloc[:, :-1].values
y = data.iloc[:, -1].values
return [X, y]
# Feature Scaling for better convergence of the Gradient Descent
# X = (X - mean)/std
def featureScaling(X):
mu = X.mean(0)
sigma = X.std(0)
X_norm = (X - mu)/sigma
return [X_norm, mu, sigma]
# Cost Functoin J(theta) = (1/2*m) * sum(h(x) - y)^2
# h(x) = theta[0] + theta[1] * x (Prediction)
def computeCost(X, y, theta):
m = len(X)
prediction = (theta * X).sum(1)
sqrError = (prediction - y) ** 2
J = (sqrError)/(2*m)
return J
# Gradient Descent theta[j] = theta[j] - derivative(J(theta))
# theta[j] = theta[j] - (sum(h(theta) - y) * x[j] ) * (alpha/m)
# x[0] = 1
def gradientDescent(X, y, theta, alpha, num_iter):
m = len(X)
for i in range(0, num_iter):
prediction = (theta * X).sum(1)
theta_temp = []
for j in range(0, len(theta)):
t = theta[j] - (((prediction - y) * X[:, j]).sum())*(alpha/m)
theta_temp.append(t)
theta = theta_temp
return theta
# Graphical Visualisation of the learning algorithm
def visualisingData(X, y, theta):
y_pred = (theta * X).sum(1)
fig = plt.figure()
axes = fig.add_subplot(111, projection='3d')
axes.scatter(X[:, 1], X[:, 2], y)
axes.plot(X[:, 1], X[:, 2], y_pred)
plt.show()
# Main Function
if __name__ == "__main__":
[X, y] = importData('ex1data2.csv')
[X, mu, sigma] = featureScaling(X)
[y, mu_y, sigma_y] = featureScaling(y)
# Adding vector of 1's for X[0]
one_array = np.array([1]*len(X))
X = np.column_stack((one_array, X))
theta = np.array([0] * X.shape[1], dtype = float)
theta = gradientDescent(X, y, theta, alpha= 0.01, num_iter = 1500)
visualisingData(X, y, theta)
|
users=[
{
"id":0,"name":"Hero"},{
"id":1,"name":"Dunn"
},{
"id":2,"name":"Sue"
},{
"id":3,"name":"Chi"
},{
"id":4,"name":"Clive"
},
{
"id":5,"name":"Devin"
},
{
"id":6,"name":"Klein"
},
]
#now wants to map them to the friendship pairs
friendsip_pairs=[(0,1),(0,2),(3,4)]
#using a dict
friendshisp = {user["id"]: [] for user in users}
#and now looping over the friendhsip pairs to populate it
for i,j in friendsip_pairs:
friendshisp[i].append(j)#adding j as a friend of user i
friendshisp[j].append(i)# adding i as a friend of user j
#to get the total number of conenctions by summing up the length of all the friends lists
def numberOfFriends(user):
user_id = user["id"]
friend_ids = friendshisp[user_id]
return len(friend_ids)
##total connections
total_connections = sum(numberOfFriends(user) for user in users)
print(total_connections)
#now dividing by the number of users
num_users= len(users)
avgCOnnections = total_connections/ num_users
#it is also easy to find the most connected people:- they are people who have the largetst
#number of freinds
#creating a list:- (usr_id,numberofFreinds)
num_friends_by_id = [(user["id"] , numberOfFriends(user)) for user in users]
#sort the list by num_freinds ,largest to smallest
num_friends_by_id.sort(
key=lambda id_and_friends:id_and_frineds[1],
reverse=True)
|
# 单行注释1
print("abc") # 单行注释2
'''
多行注释
'''
"""
多行注释
"""
if True:
print("true")
else:
print("false")
if True:
print("Answer")
print("True")
else:
print("Answer")
# print ("False") # 缩进不一致,会导致运行错误
# 变量声明,前面不能有空格
word = '字符串'
sentence = "这是一个句子。"
paragraph = """这是一个段落,
可以由多行组成"""
#a = b = c = 1
a, b, c = 1, 2, "runoob"
print(a,b,c)
print(type(a), type(b), type(c)) #type 获取变量类型
if isinstance(a,int):
print("a是整数")
strvalue = '123456789'
print(strvalue) # 输出字符串
print(strvalue[0:-1]) # 输出第一个到倒数第二个的所有字符
print(strvalue[0]) # 输出字符串第一个字符
print(strvalue[2:5]) # 输出从第三个开始到第五个的字符
print(strvalue[2:]) # 输出从第三个开始后的所有字符
print(strvalue[1:5:2]) # 输出从第二个开始到第五个且每隔一个的字符(步长为2)
print(strvalue * 2) # 输出字符串两次
print(strvalue + '你好') # 连接字符串
# 加减乘除运算
a = 1
b = 2
print(a+b)
print(a/b)
print(a-b)
print(a*b)
# 一行多条语句
print("一行多条语句")
print("一行多条语句")
# 字符串拼接
result = 1
# print("输出"+1) python中盖写法会报错,字符串无法直接拼接int类型
if result == 1:
print("输出" + str(1))
elif result == 2:
print("输出"+str(2))
else:
print("输出"+str(2))
#引入sys模块
import sys
#引入sys模块的部分成员,多个用逗号隔开
from sys import argv,path
for i in sys.argv: #循环
print(i)
print(issubclass(bool, int) ); #python中 bool为int类型的子类
print(True==1);print(False==0) # 即True = 1 ,false = 0
print(True+False) # 同理 TRUE和FALSE是可以做数学运算的
var1 = 1
var2 = 2
del var1 # 删除了var1这个变量,print(var1)时则报错
#del var1,var2 #已经删除的变量无法重复删除
#List 操作
a = [1, 2, 3, 4, 5, 6,"aaa"]
a[0] = 9 #針對單個指定元素賦值
print(a)
a[2:5] = [13, 14, 15] #針對
print(a)
a[2:5] = []
print(a)
#Tuple 操作
tup = ( 'abcd', 786 , 2.23, 'runoob', 70.2 )
# tup[0] = 1 tuple的元素無法操作,此處運行會報錯
#string這種操作也會報錯
#Python中 string list tuple都屬於序列,操作方式類似
#由此可看出 string是一種特殊存在的元組
#Set操作 Python中Set表示為集合
sites = {'Google', 'Taobao', 'Runoob', 'Facebook', 'Zhihu', 'Baidu','Google'}
print(sites) #輸出時,會自動刪除重複的對象
# 成员测试,判斷是否存在
if 'Runoob' in sites :
print('Runoob 在集合中')
else :
print('Runoob 不在集合中')
# set可以进行集合运算,交集、並集、差集
a = set('abracadabra')
b = set('alacazam')
print(a)
print(a - b) # a 和 b 的差集
print(a | b) # a 和 b 的并集
print(a & b) # a 和 b 的交集
print(a ^ b) # a 和 b 中不同时存在的元素
#Dictionary key value,
dict = {}
dict['one'] = "1 - 菜鸟教程"
dict[2] = "2 - 菜鸟工具"
print(dict)
tinydict = {'name': 'runoob','code':1, 'site': 'www.runoob.com'} #結構
print(tinydict.keys()) #輸出所有key
print(tinydict.values()) #輸出所有value
|
def mergeSort(a):
n=len(a)
if n<=1:
return a
L=mergeSort(a[:round(n/2)])
R=mergeSort(a[round(n/2):])
return merge(L,R)
def merge(L,R):
i=0
j=0
newA=[]
while i<len(L) and j< len(R):
if L[i]<R[j]:
newA.append(R[j])
j+=1
else:
newA.append(L[i])
i+=1
while i <len(L):
newA.append(L[i])
i+=1
while j< len(R):
newA.append(R[j])
j += 1
return newA
array=[15,32,1,42,21]
b=mergeSort(array)
print(b)
|
"""
Algorithms for finding shortest distance between set of points
"""
import math
def e_distance(point1, point2):
"""Calculates the euclidian distance betweeb two points"""
return math.sqrt((point1[0] - point2[0]) ** 2 +
(point1[1] - point2[1]) ** 2)
def brute_force(points_list):
"""Takes list of tuples of format (x, y),
returns a tuple of format (distance, (x1, y1), (x2, y2))
takes O(N^2)"""
min_dist = (float("inf"), (None, None), (None, None))
for point1 in points_list:
for point2 in points_list:
new_dist = (e_distance(point1, point2), point1, point2)
if new_dist[0] < min_dist[0] and point1 is not point2:
min_dist = new_dist
return min_dist
def divide_and_conquer(points_list):
"""
Takes list of tuples of format (x, y) sorted in x ASC,
returns a tuple of format (distance, (x1, y1), (x2, y2))
takes O(N^2)"""
# step 0
num_points = len(points_list)
if num_points <= 3:
return brute_force(points_list)
mid_index = num_points // 2
left_result = divide_and_conquer(points_list[:mid_index])
right_results = divide_and_conquer(points_list[mid_index:])
result = min(left_result, (right_results[0],
(right_results[1][0] +
mid_index, right_results[1][1]),
(right_results[2][0] +
mid_index, right_results[2][1])))
mid_strip_disrt = (points_list[mid_index - 1][0] +
points_list[mid_index][0]) / 2
result = min(result, colsest_pair_middle(points_list,
mid_strip_disrt,
result[0]))
return result
def colsest_pair_middle(points_list, mid, half_width):
"""Finds cloasest pairs in middle"""
# take only points in middle strip
# sort in Y ASC
middle_points = [point for point in points_list
if abs(point[0] - mid) < half_width]
middle_points.sort(key=lambda x: x[1])
size = len(middle_points)
result = (float("inf"), (None, None), (None, None))
for point1_idx in range(size - 1):
for point2_idx in range(point1_idx + 1,
min(point1_idx + 4, size)):
dist = e_distance(middle_points[point1_idx],
middle_points[point2_idx])
result = min(result, (dist,
middle_points[point1_idx],
middle_points[point2_idx]))
return result
|
def union(set1, set2):
"""
Returns the union of two sets.
Arguments:
set1 -- The first set of the union.
set2 -- The second set of the union.
Returns:
A new set containing all the elements of set1 and set2.
"""
res = set1.copy()
for item in set2:
res.add(item)
return res
print union(set(), set())
def intersection(set1, set2):
"""
Returns the intersection of two sets.
Arguments:
set1 -- The first set of the intersection.
set2 -- The second set of the intersection.
Returns:
A new set containing only the elements common to set1 and set2.
"""
res = set()
for item in set1:
if item in set2:
res.add(item)
return res
print intersection(set([1,2,3]), set([2,3,4]))
print intersection(set([1,2]), set([3,4]))
print intersection(set(), set([3]))
def make_dict(keys, default_value):
"""
Creates a new dictionary with the specified keys and default value.
Arguments:
keys -- A list of keys to be included in the returned dictionary.
default_value -- The initial mapping value for each key.
Returns:
A dictionary where every key is mapped to the given default_value.
"""
res ={}
for key in keys:
res[key] = default_value
return res
print make_dict(["a","b","c"], "z")
print make_dict([], [])
def ensure_key_value_pair(pairs, key, expected_value):
"""
Checks to ensure that the mapping of key in pairs matches the given expected value.
If the state of pairs is such that the given key is already mapped to the given expected value
this function in no way modifies the dictionary and returns the given dictionary.
If the state of pairs is such that the given key does not map to the given expected value
(or no such key is contained in pairs) then update (or add) the mapping of key to
the given expected value and return the given dictionary.
Arguments:
pairs -- A dictionary to check for the expected mapping.
key -- The key of the expected mapping.
expected_value -- The the value of the expected mapping.
Returns:
The given dictionary.
"""
if pairs.has_key(key):
if pairs[key] != expected_value:
pairs[key] = expected_value
else:
pairs[key] = expected_value
return pairs
pairs = { 1:"a", 2:"b" }
print ensure_key_value_pair(pairs, 1, "a")
print ensure_key_value_pair(pairs, 2, "z")
print ensure_key_value_pair(pairs, 3, "x")
|
"""
Simple graph distionary representation and calculation
"""
import random
import dpa_trial
import upa_trial
EX_GRAPH0 = {0: set([1, 2]), 1: set([]), 2: set([])}
EX_GRAPH1 = {0: set([1, 4, 5]), 1: set([2, 6]), 2: set([3]),
3: set([0]), 4: set([1]), 5: set([2]), 6: set([])}
EX_GRAPH2 = {0: set([1, 4, 5]), 1: set([2, 6]), 2: set([3, 7]),
3: set([7]), 4: set([1]), 5: set([2]), 6: set([]),
7: set([3]), 8: set([1, 2]), 9: set([0, 3, 4, 5, 6, 7])}
def make_complete_graph(num_nodes):
"""
Makes a dictionary representation of a full
graph with num_nodes nodes
returns dictionary representation
"""
res = {}
if num_nodes > 0:
set_all_nodes = set(range(num_nodes))
for node in range(num_nodes):
ajasent_nodes = set_all_nodes.copy()
ajasent_nodes.remove(node)
res[node] = ajasent_nodes
return res
def compute_in_degrees(digraph):
"""
Computes in-degree of grapgh nodes
digraph is directional graph represented as dict
returns new dictionary with keys as nodes
and values as in-degree
"""
def make_dict(keys, default_value):
"""
Creates a new dictionary with the specified keys and default value.
Arguments:
keys -- A list of keys to be included in the returned dictionary.
default_value -- The initial mapping value for each key.
Returns:
A dictionary where every key is mapped to the given default_value.
"""
res = {}
for key in keys:
res[key] = default_value
return res
res = make_dict(digraph.keys(), 0)
for node_out in digraph:
for node_in in digraph[node_out]:
res[node_in] += 1
return res
def compute_in_degrees_old(digraph):
"""
Computes in-degree of grapgh nodes
digraph is directional graph represented as dict
returns new dictionary with keys as nodes
and values as in-degree
"""
res = {}
if digraph:
for node_in in digraph:
in_degree = 0
for node in digraph:
if node_in in digraph[node]:
in_degree += 1
res[node_in] = in_degree
return res
def in_degree_distribution(digraph):
"""
Computes in-degree distribution of a graph
returns dicitonary where keys are in-degrees
and values are number of occurences
"""
in_degree = compute_in_degrees(digraph)
res = {}
for node in in_degree:
if in_degree[node] not in res:
res[in_degree[node]] = 1
else:
res[in_degree[node]] += 1
return res
def compute_out_degree(digraph):
"""Compute out degree of graph"""
res = {}
for node in digraph:
res[node] = len(digraph[node])
return res
def out_degree_distribution(digraph):
"""Computes out degree distribution of graph"""
out_degree = compute_out_degree(digraph)
res = {}
for node in out_degree:
if out_degree[node] not in res:
res[out_degree[node]] = 1
else:
res[out_degree[node]] += 1
return res
def node_count(graph):
"""
Returns the number of nodes in a graph.
Arguments:
graph -- The given graph.
Returns:
The number of nodes in the given graph.
"""
return len(graph.keys())
print node_count(EX_GRAPH0)
print node_count(EX_GRAPH1)
print node_count(EX_GRAPH2)
print node_count({})
print "----------------"
def edge_count(graph):
"""
Returns the number of edges in a graph.
Arguments:
graph -- The given graph.
Returns:
The number of edges in the given graph.
"""
res = 0
for edges in graph.values():
res += len(edges)
return res / 2
graph1 = {"0": set(["1", "2"]),
"1": set(["0", "2"]),
"2": set(["1", "0"])}
print edge_count(graph1)
print edge_count(EX_GRAPH0)
print edge_count(EX_GRAPH1)
print edge_count(EX_GRAPH2)
print edge_count({})
def make_graph1(num_nodes):
"""
#V = {0, 1, 2, 3, 4, 5} where an edge exists
from n to n+1 (for n = 0...4).
Also include the edge (5,0)
"""
res = {}
for node in range(num_nodes + 1):
res[node] = set([num for num in range(node, num_nodes + 1)
if num != node])
res[num_nodes] = set([0])
return res
def make_graph2(num_nodes):
"""
#V = {0, 1, 2, 3, 4, 5} where an edge exists
from n to n+1 (for n = 0...4).
Also include the edge (5,0)
"""
res = {}
for node in range(num_nodes + 1):
res[node] = set([(node + 1) % (num_nodes + 1)])
return res
print make_graph1(5)
print make_graph2(5)
def is_undirected_graph_valid(graph):
"""
Tests whether the given graph is logically valid.
Asserts for every unordered pair of distinct nodes {n1, n2} that
if n2 appears in n1's adjacency set then n1 also appears in
n2's adjacency set. Also asserts that no node appears in
its own adjacency set and that every value that appears in
an adjacency set is a node in the graph.
Arguments:
graph -- The graph in dictionary form to test.
Returns:
True if the graph is logically valid. False otherwise.
"""
for node in graph:
for edge in graph[node]:
if (edge not in graph) or (edge == node) or (node not in graph[edge]):
return False
return True
graph1 = {"0": set(["1", "2"]),
"1": set(["0", "2"]),
"2": set(["1", "0"])}
print is_undirected_graph_valid(graph1)
graph2 = {"0": set(["1", "2"]),
"1": set(["0", "2"]),
"2": set(["1"])}
print is_undirected_graph_valid(graph2)
graph3 = make_complete_graph(100)
print is_undirected_graph_valid(graph3)
graph4 = {"0": set(["1", "2"]),
"1": set(["0", "2"]),
"2": set(["1", "3"])}
print is_undirected_graph_valid(graph4)
graph5 = {"0": set(["0"])}
def find_popular_nodes(graph):
avg_degree = (edge_count(graph) * 2) / node_count(graph)
count = 0
res = set([])
for node in graph:
if len(graph[node]) > avg_degree:
res.add(node)
count += 1
return count, res
import urllib2
CITATION_URL = "http://storage.googleapis.com/codeskulptor-alg/random10000.txt"
def load_graph(graph_url):
"""
Function that loads a graph given the URL
for a text representation of the graph
Returns a dictionary that models a graph
"""
graph_file = urllib2.urlopen(graph_url)
graph_text = graph_file.read()
graph_lines = graph_text.split('\n')
graph_lines = graph_lines[: -1]
print "Loaded graph with", len(graph_lines), "nodes"
answer_graph = {}
for line in graph_lines:
neighbors = line.split(' ')
node = int(neighbors[0])
answer_graph[node] = set([])
for neighbor in neighbors[1: -1]:
answer_graph[node].add(int(neighbor))
return answer_graph
def make_random_graph(num_nodes, probablitiy):
res = {}
for node in range(num_nodes):
res[node] = set([])
for node_from in range(num_nodes):
for node_to in range(num_nodes):
prob1 = random.random()
if probablitiy < prob1:
res[node_from].add(node_to)
prob2 = random.random()
if probablitiy < prob2:
res[node_to].add(node_from)
return res
rnd_graph = make_random_graph(1000, 0.9)
print in_degree_distribution(rnd_graph)
def make_dpa_graph(num_nodes, avg_degree):
"""
Creates a graph with num_nodes amout of nodes
and average in degree of avg_degree.
Prefers popular nodes
"""
full_graph = make_complete_graph(avg_degree)
trial = dpa_trial.DPATrial(avg_degree)
for node in range(avg_degree, num_nodes):
full_graph[node] = trial.run_trial(avg_degree)
return full_graph
def make_random_graph_undir(num_nodes, probablitiy):
res = {}
for node in range(num_nodes):
res[node] = set([])
nodes_to = range(num_nodes)
for node_from in range(num_nodes):
for node_to in nodes_to:
prob1 = random.random()
if probablitiy > prob1 and node_from != node_to:
res[node_from].add(node_to)
res[node_to].add(node_from)
nodes_to.remove(node_from)
return res
def make_upa_graph(num_nodes, avg_degree):
"""
Creates a graph with num_nodes amout of nodes
and average in degree of avg_degree.
Prefers popular nodes
"""
full_graph = make_complete_graph(avg_degree)
trial = upa_trial.UPATrial(avg_degree)
for node in range(avg_degree, num_nodes):
neighbors = trial.run_trial(avg_degree)
full_graph[node] = neighbors
for neighbour in neighbors:
full_graph[neighbour].add(node)
return full_graph
|
# -*- coding: utf-8 -*-
import command
class NothingToUndoException(Exception):
def __init__(self):
super(NothingToUndoException, self).__init__("There is command to undo.")
class NothingToRedoException(Exception):
def __init__(self):
super(NothingToRedoException, self).__init__("There is nothing to redo.")
class EmptyHistoryException(Exception):
def __init__(self):
super(EmptyHistoryException, self).__init__("There is no items in this history.")
class History(object):
"""
History objects are design to keep track of executed commands in order to undo or redo them.
"""
def append(self, e):
"""
Push an element in the history, being the first command to undo if the user request so and execute it.
:param e: the command
:type e: command.CommandInstance
"""
raise NotImplementedError()
def back(self):
"""
Move the internal cursor backward, executing an undo on the previously selected command. If no more commands
exists, meaning you reached the oldest command, method raise an exception.
:raises NothingToUndoException, EmptyHistoryException
"""
raise NotImplementedError()
def forth(self):
"""
Move forward in history, moving the cursor first and executing a redo then. Fail if no commands
can be redo.
:raises EmptyHistoryException, NothingToRedoException
"""
raise NotImplementedError()
def item(self):
"""
Get the current selected command.
:raise EmptyHistoryException
:return: the selected command or None if not command is selected
:rtype: None|command.CommandInstance
"""
raise NotImplementedError()
def can_undo(self):
"""
Say if a command can be undone.
:return: True if it can, else False
:rtype: bool
"""
raise NotImplementedError()
def can_redo(self):
"""
Say if a command can be redo.
:return: True if it is possible, else False
:rtype: bool
"""
raise NotImplementedError()
def clear(self):
"""
Clear this history, removing all stored commands.
"""
raise NotImplementedError()
def __len__(self):
"""
Return the number of commands stored in this history.
:return: history's lenght
:rtype: int
"""
raise NotImplementedError()
class BoundedHistory(History):
"""
BoundedHistory is an History with a capacity. Once this capacity is reached, oldest elements are removed.
"""
def __init__(self, capacity):
"""
Create a new BoundedHistory with the provided capacity.
:param capacity: history's capacity
"""
self._capacity = capacity
@property
def capacity(self):
"""
Get this history's capacity.
:return: history's capacity
:rtype: int
"""
return self._capacity
class DoubleStackHistory(History):
"""
An implementation of History using stacks. The first one is used as the primary stack. When new elements are added
to the history, they are pushed to the primary stack. When a call is made to back, top element is retrieved and
pushed on the second stack. While the user is keeping calling back, elements are added to the second stack. If a
call to add is made, second stack is cleared. Calls to forth pop elements of the second one and push them on the
primary one.
"""
def __init__(self):
"""
Create a new DoubleStackHistory without any command.
"""
self._primary = []
self._secondary = []
def append(self, e):
# Clear secondary
self._secondary.clear()
# Append element to the primary stack and execute command
self._primary.append(e)
e.command.execute(*e.args, **e.kwargs)
def back(self):
if len(self._primary) == 0:
if len(self._secondary) == 0:
raise EmptyHistoryException()
raise NothingToUndoException()
# Add last element to the secondary stack
self._secondary.append(self._primary[-1])
# Pop and undo command
c = self._primary.pop()
c.command.undo(*c.args, **c.kwargs)
def forth(self):
if len(self._secondary) == 0:
if len(self._primary) == 0:
raise EmptyHistoryException()
raise NothingToRedoException()
# Add last element to primary stack
self._primary.append(self._secondary[-1])
# Pop element and execute redo
c = self._secondary.pop()
c.command.redo(*c.args, **c.kwargs)
def item(self):
if len(self._primary) == 0 and len(self._secondary) == 0:
raise EmptyHistoryException()
return self._primary[-1] if len(self._primary) > 0 else None
def can_undo(self):
return len(self._primary) > 0
def can_redo(self):
return len(self._secondary) > 0
def clear(self):
self._primary.clear()
self._secondary.clear()
def __len__(self):
return len(self._primary) + len(self._secondary)
|
sifre1 = input("Lütfen yeni şifrenizi giriniz:")
sifre2 = input("Lütfen şifrenizi tekrar giriniz:")
if(sifre1 == sifre2):
if(len(sifre1) < 4):
print("Şifreniz 4 karakterden daha büyük olmalıdır")
else:
print("Şifreniz değiştirildi.")
else:
print("Şifreleriniz uyuşmamaktadır.")
|
int_codes = []
relative_base = 0
def get_int_code(position: int) -> int:
global int_codes
if position >= len(int_codes):
for num in range(len(int_codes), position + 2):
int_codes.append(0)
return int_codes[position]
def set_int_code(position: int, value: int):
global int_codes
if position >= len(int_codes):
for num in range(len(int_codes), position + 2):
int_codes.append(0)
int_codes[position] = value
def get_value(pos: int, mode: int) -> int:
if mode == 0:
return int(get_int_code(pos))
elif mode == 1:
return int(pos)
elif mode == 2:
return int(get_int_code(pos + relative_base))
def get_modes(opcode: int) -> tuple:
code = str(opcode)
first_mode = 0
second_mode = 0
third_mode = 0
length = len(str(code))
if length == 5:
third_mode = code[0]
second_mode = code[1]
first_mode = code[2]
elif length == 4:
second_mode = code[0]
first_mode = code[1]
elif length == 3:
first_mode = code[0]
code = int(code) % 100
return int(code), int(first_mode), int(second_mode), int(third_mode)
def compute(codes: list, inputs: list = []) -> list:
print(len(codes))
global int_codes
global relative_base
int_codes = codes
input_values = inputs.copy()
pointer = 0
output = []
while pointer < len(int_codes):
code = get_int_code(pointer)
modes = get_modes(code)
first_mode = modes[1]
second_mode = modes[2]
third_mode = modes[3]
code = modes[0]
# Code 1: Add
if code == 1:
operand1pos = get_int_code(1 + pointer)
operand2pos = get_int_code(2 + pointer)
target = get_int_code(3 + pointer)
set_int_code(get_value(target, third_mode),
get_value(operand1pos, first_mode) + get_value(operand2pos, second_mode))
pointer += 4
# Code 2: Multiply
elif code == 2:
operand1pos = get_int_code(1 + pointer)
operand2pos = get_int_code(2 + pointer)
target = get_int_code(3 + pointer)
set_int_code(get_value(target, third_mode),
get_value(operand1pos, first_mode) * get_value(operand2pos, second_mode))
pointer += 4
# Code 3: Input
elif code == 3:
target = get_int_code(pointer + 1)
if len(input_values) == 0:
set_int_code(get_value(target, first_mode), input("Enter value for opcode 3: "))
else:
set_int_code(get_value(target, first_mode), input_values.pop(0))
pointer += 2
# Code 4: Output
elif code == 4:
target = get_int_code(pointer + 1)
print(get_value(target, first_mode))
output.append(get_value(target, first_mode))
pointer += 2
# Code 5: Conditional Jump
elif code == 5:
if get_value(get_int_code(1 + pointer), first_mode) != 0:
pointer = get_value(get_int_code(pointer + 2), second_mode)
else:
pointer += 3
# Code 6: Conditional Jump
elif code == 6:
if get_value(get_int_code(1 + pointer), first_mode) == 0:
pointer = get_value(get_int_code(pointer + 2), second_mode)
else:
pointer += 3
# Code 7: Greater-Than
elif code == 7:
operand1pos = get_int_code(1 + pointer)
operand2pos = get_int_code(2 + pointer)
target = get_int_code(3 + pointer)
if get_value(operand1pos, first_mode) < get_value(operand2pos, second_mode):
set_int_code(get_value(target, third_mode), 1)
else:
set_int_code(get_value(target, third_mode), 0)
pointer += 4
# Code 8: Compare two positions for equality
elif code == 8:
operand1pos = get_int_code(1 + pointer)
operand2pos = get_int_code(2 + pointer)
target = get_int_code(3 + pointer)
if get_value(operand1pos, first_mode) == get_value(operand2pos, second_mode):
set_int_code(get_value(target, third_mode), 1)
else:
set_int_code(get_value(target, third_mode), 0)
pointer += 4
# Code 9: Modify relative base
elif code == 9:
parameter = get_value(pointer + 1, first_mode)
relative_base += parameter
pointer += 2
# Code 99: Shut down
elif code == 99:
break
return output
|
from collections import deque
class TransitionMemory():
def __init__(self, num_steps):
self.t_deque = deque(maxlen=num_steps)
# this function formats all transitions in memory, returns the list of them, and resets self.t_deque to an empty deque, resetting the instance to its starting state
def flush(self):
# formatting all transitions
transition_list = []
for i in range(len(self.t_deque)):
formatted_transition = self.format(i, num_steps_till_complete=len(self.t_deque)-i-1)
transition_list.append(formatted_transition)
# empties the t_deque
self.t_deque = deque(maxlen=self.t_deque.maxlen)
return transition_list
# this function "formats" a transition and is the core method of this class. formatting means two things:
# append the next state of all the following transfers to its next state
# set the last element to an integer rather than a boolean, which represents the number of transitions from this transition until the env terminates, which is useful in bootstrapping during Q learning
# the parameters are:
# transition_index is the index of the transition in self.t_deque because it makes the logic of the function simpler
# num_steps_till_complete is the number of transitions from this transition until the env terminates
def format(self, transition_index, num_steps_till_complete=-1):
# referencing self in parameters of a function is not allowed in python, so I've settled on this hack:
if (num_steps_till_complete == -1):
num_steps_till_complete = self.t_deque.maxlen
# the targetted transition in the deque
transition = self.t_deque[transition_index]
# gotta make a new tuple with a list containing the next state of transition that states following that state will be appended to
# the last element, which used to be a boolean that indicates weather or not the transition was terminal, will be set to an interger representing a lower bound for the number of transitions until the terminal state.
formatted_transition = transition[:3] + ([transition[3]], num_steps_till_complete)
for i in range(1, len(self.t_deque)):
# this line means that i will wrap around the deque
i = (i + transition_index) % len(self.t_deque)
t = self.t_deque[i]
formatted_transition[3].append(t[3])
return formatted_transition
# this function accepts a transition and returns a list
# that list either contains nothing, a single transition, or all transitions in memory
def new_transition(self, new_transition):
# appending the new transition onto the deque
self.t_deque.append(new_transition)
if (len(self.t_deque) == self.t_deque.maxlen):
if new_transition[4]:
# if the transition is terminal, flush memory
return self.flush()
# if we've got enough transitions in memory, return the extended form of the earliest transition
return [self.format(0)]
else:
# if we don't have enough transitions in memory, return an empty list
return []
def make_transition(terminal = False):
# this is a testing function, so we can import in it even though it may be called multiple times
import numpy as np
import random
old_observation = np.random.uniform(size=4)
action = random.choice([0.0, 1.0])
reward = random.uniform(0, 1)
observation = np.random.uniform(size=4)
done = terminal
return (old_observation, action, reward, observation, done)
def test_transition_memory():
tm = TransitionMemory(5)
print(tm.new_transition(make_transition()))
print(tm.new_transition(make_transition()))
print(tm.new_transition(make_transition()))
print(tm.new_transition(make_transition()))
print('------------------------------')
# upon the fifth new transition, tm should contain enough tansistions to give an output
print(tm.new_transition(make_transition())[0][3])
print(tm.new_transition(make_transition())[0][3])
print(tm.new_transition(make_transition())[0][3])
print(tm.new_transition(make_transition())[0][3])
print(tm.new_transition(make_transition())[0][3])
print('------------------------------')
# we now give tm a terminal transition to see how it reacts
final_transition = make_transition(terminal=True)
flush = tm.new_transition(final_transition)
print(len(flush))
print('***')
print(flush[0][3])
print('***')
print(flush[1][3])
print('***')
print(flush[2][3])
print('***')
print(flush[3][3])
print('***')
print(flush[4][3])
def permute_generator(tuple_of_lists):
first_list = tuple_of_lists[0]
last_lists = tuple_of_lists[1:]
if (len(last_lists) != 0):
child_generator = permute_generator(last_lists)
for child in child_generator:
for element in first_list:
yield (element, *child)
else:
for element in first_list:
yield (element, )
def test_permute_generator():
tol = ([1,2,3,4], ['a,', ' b'], ['one', 'two', 'three'])
gen = permute_generator(tol)
for g in gen:
print(g)
if (__name__ == '__main__'):
# test_transition_memory()
test_permute_generator()
|
"""
Desafio 015 - Aluguel de carros
Faça um algoritmo que : Pergunte a quantidade de Km percorridos
e quantidade de dias alugado, Calcule o valor a pagar
Diaria R$60 Km rodado R$0.15
Passos
1- Verificar quantidade de Km percorrido
2- Verificar quantidade de Dias alugado
3 - Calcular valor a ser pago
4 - Exibir total
"""
kmPercorrido = float(input("Digite a kilometragem percorrida: "))
diasAlugado = float(input("Digite a quantidade de dias que foi alugado:"))
valorTotal = (kmPercorrido*60.00)+(diasAlugado*0.15)
print("O valor total a ser pago é de R${:.2f}".format(valorTotal))
|
#Dissecando uma váriavel : Fazer um programa que leia algo -
# pelo teclado e mostre na tela o seu:
#Tipo primitivo e todas informações possíveis
a = input('Digite algo: ')
print(" o tipo primitivo desse valor é" , type(a))
print('Só tem espaços?', a.isspace())
print('is numeric?', a.isnumeric())
print('é alfabetico?', a.isalpha())
print('é alfanumeric?', a.isalnum())
print('esta maisculo?', a.isupper())
print('esta minusculo?', a.islower())
print('esta capitalizada?', a.istitle())
|
import csv
import os
# Adopted from course materials
electioncsv = os.path.join("Resources", "election_data.csv")
# Declare and initialize variables and lists
totalvotes = 0
candidates = []
candidatesvotes = []
Khanvotes = 0
Khanpercent = 0
Correyvotes = 0
Correypercent = 0
Livotes = 0
Lipercent = 0
OTooleyvotes = 0
Otooleypercent = 0
Winner = []
# Open and read csv
with open(electioncsv, 'r') as csvfile:
csvreader = csv.reader(csvfile, delimiter=",")
# skip header
header = next(csvreader)
for row in csvreader:
totalvotes += 1
# Append unique list. Syntax from geeksforgeeks.org
if row[2] not in candidates:
candidates.append(row[2])
# Total votes for each candidate
if row[2] == "Khan":
Khanvotes += 1
elif row[2] == "Correy":
Correyvotes += 1
elif row[2] == "Li":
Livotes += 1
elif row[2] == "O'Tooley":
OTooleyvotes += 1
# for row in csvreader:
# for counter in candidates:
# if row[2] == candidates[counter]:
# candidatesvotes[counter] += 1
# Calculate candidate percentage votes
Khanpercent = "{:.3%}".format(Khanvotes/totalvotes)
Correypercent = "{:.3%}".format(Correyvotes/totalvotes)
Lipercent = "{:.3%}".format(Livotes/totalvotes)
Otooleypercent = "{:.3%}".format(OTooleyvotes/totalvotes)
# for counter in candidatesvotes:
# print(candidatesvotes[counter])
print("Election Results")
print("-----------------------------")
print("Total Votes :", totalvotes)
print("-----------------------------")
print(f'{candidates[0]}' ":", " ", Khanpercent, " ", Khanvotes)
print(f'{candidates[1]}' ":", " ", Correypercent, " ", Correyvotes)
print(f'{candidates[2]}' ":", " ", Lipercent, " ", Livotes)
print(f'{candidates[3]}' ":", " ", Otooleypercent, " ", OTooleyvotes)
print("-----------------------------")
if Khanpercent > Correypercent and Khanpercent > Lipercent and Khanpercent > Otooleypercent:
print(f'Winner : {candidates[0]}')
Winner = candidates[0]
elif Correypercent > Khanpercent and Correypercent > Lipercent and Correypercent > Otooleypercent:
print(f'Winner : {candidates[1]}')
Winner = candidates[1]
elif Lipercent > Khanpercent and Lipercent > Correypercent and Lipercent > Otooleypercent:
print(f'Winner : {candidates[2]}')
Winner = candidates[2]
elif Otooleypercent > Khanpercent and Otooleypercent > Correypercent and Otooleypercent > Lipercent:
print(f'Winner : {candidates[3]}')
Winner = candidates[3]
print("-----------------------------")
# Adopted from class material
# Specify the file to write to
outputpath = os.path.join("analysis", "results.csv")
# Open the file using "write" mode. Specify the variable to hold the contents
with open(outputpath, 'w', newline='') as csvfile:
# Initialize csv.writer
csvwriter = csv.writer(csvfile, delimiter=',')
# Write the first row (column headers)
csvwriter.writerow(["Election Results"])
csvwriter.writerow(["-----------------------------"])
csvwriter.writerow(["Total Votes : " + str(totalvotes)])
csvwriter.writerow(["-----------------------------"])
csvwriter.writerow([str(candidates[0]) + ":" + " " + str(Khanpercent) + " " + str(Khanvotes)])
csvwriter.writerow([str(candidates[1]) + ":" + " "+ str(Correypercent) + " " + str(Correyvotes)])
csvwriter.writerow([str(candidates[2]) + ":" + " " + str(Lipercent) + " " + str(Livotes)])
csvwriter.writerow([str(candidates[3]) + ":" + " " + str(Otooleypercent) + " " + str(OTooleyvotes)])
csvwriter.writerow(["-----------------------------"])
csvwriter.writerow(["Winner :" + str(Winner)])
csvwriter.writerow(["-----------------------------"])
|
def prepare_puzzle(puzzle):
return [int(n) for n in puzzle[0].split(',')]
def get_number_spoken(puzzle, nth):
history = {n: i+1 for i, n in enumerate(puzzle)}
last_number = puzzle[-1]
prev_number = -1
for turn in range(len(puzzle)+1, nth+1):
last_number = 0 if prev_number == -1 else (turn-1) - prev_number
prev_number = history[last_number] if last_number in history else -1
history[last_number] = turn
return last_number
def solve_part1(puzzle):
return get_number_spoken(puzzle, 2020)
def solve_part2(puzzle):
return get_number_spoken(puzzle, 30000000)
|
def prepare_puzzle(puzzle):
return [parse_exp(exp.replace(' ', '')) for exp in puzzle]
def parse_exp(exp):
result = []
i = 0
while i < len(exp):
if exp[i] == '(':
i, exp_start, open_parentheses = i+1, i+1, 0
while exp[i] != ')' or open_parentheses > 0:
if exp[i] == ')': open_parentheses -= 1
elif exp[i] == '(': open_parentheses += 1
i += 1
result.append(parse_exp(exp[exp_start:i]))
else:
result.append(exp[i])
i += 1
return result
class Node:
def __init__(self, value):
self.value = value
self.left = None
self.right = None
def is_leaf(self):
return self.left == None and self.right == None
def construct_tree(expression):
i, operator = len(expression) -1, None
while i >= 0:
if isinstance(expression[i], str) and expression[i] in '+*':
operator = expression[i]
i -= 1
else:
if isinstance(expression[i], list): node = construct_tree(expression[i])
elif operator == None: node = Node(int(expression[i]))
if operator == None:
right_node = node
i -= 1
else:
root = Node(operator)
root.left = construct_tree(expression[:i+1])
root.right = right_node
operator = None
return root
return node
def eval_exp(root):
if root.is_leaf():
return root.value
if root.value == '+':
return eval_exp(root.left) + eval_exp(root.right)
if root.value == '*':
return eval_exp(root.left) * eval_exp(root.right)
def insert_parenteses(exp):
i = 0
while i < len(exp):
if exp[i] == '+':
new_exp = [exp[i-1], exp[i], insert_parenteses(exp[i+1])]
del exp[i:i+2]
exp[i-1] = new_exp
else:
if isinstance(exp[i], list): exp[i] = insert_parenteses(exp[i])
i += 1
return exp
def sum_eval_all(expressions):
return sum([eval_exp(tree) for tree in [construct_tree(exp) for exp in expressions]])
def solve_part1(puzzle):
return sum_eval_all(puzzle)
def solve_part2(puzzle):
return sum_eval_all([insert_parenteses(exp) for exp in puzzle])
|
def prepare_puzzle(puzzle):
return puzzle
def count_trees(puzzle, right, down = 1):
trees = 0
n = 0
for line in puzzle[1::down]:
n += right
n %= len(line)
if line[n] == '#':
trees += 1
return trees
def solve_part1(puzzle):
return count_trees(puzzle, 3)
def solve_part2(puzzle):
result = count_trees(puzzle, 1)
result *= count_trees(puzzle, 3)
result *= count_trees(puzzle, 5)
result *= count_trees(puzzle, 7)
result *= count_trees(puzzle, 1, 2)
return result
|
from __future__ import annotations
import json
from dataclasses import dataclass
from datetime import time
from enum import Enum, auto
from json.decoder import JSONDecodeError
from typing import Dict, List, Optional, Union
class ValidationError(Exception):
"""
Exception used to signal that it was not possible to process the JSON input
"""
pass
class Day(Enum):
"""
Enum used to represent a day of the week.
"""
MONDAY = 0
TUESDAY = 1
WEDNESDAY = 2
THURSDAY = 3
FRIDAY = 4
SATURDAY = 5
SUNDAY = 6
def __str__(self) -> str:
return self.name.capitalize()
# We use this to guarantee that we are going though a week in the correct order
WEEK = [Day.MONDAY, Day.TUESDAY, Day.WEDNESDAY,
Day.THURSDAY, Day.FRIDAY, Day.SATURDAY, Day.SUNDAY]
class Status(Enum):
"""
Enum used to represent the possible status of the restaurant.
"""
OPEN = auto()
CLOSE = auto()
@dataclass
class Timeslot:
"""
Class used to represent a timeslot where the restourant is open.
"""
opening: time
closing: time
@classmethod
def from_timestamps(cls, opening_timestamp: int, closing_timestamp: int) -> Timeslot:
"""
Create an object from a pair of timestamps that represent the number of seconds from midnight.
Parameters
----------
opening_timestamp : int
timestamp of the opening time in seconds from midnight
closing_timestamp : int
timestamp of the closing time in seconds from midnight
Returns
-------
Timeslot
Object representing the timeslot associated with the timestamps
"""
opening = _time_from_timestamp(opening_timestamp)
closing = _time_from_timestamp(closing_timestamp)
return cls(opening, closing)
def __str__(self) -> str:
"""
Returns the string representation of the object.
The representation will be in the format HH[:MM[:SS]] AM|PM - HH[:MM[:SS]] AM|PM
Returns
-------
str
The string representation
"""
return f"{_time_to_pretty_string(self.opening)} - {_time_to_pretty_string(self.closing)}"
RawInputs = Dict[str, List[Dict[str, Union[str, int]]]]
# These needs to be defined after the Day and Timeslot types otherwise the parser is not happy
Inputs = Dict[Day, List[Dict[str, Union[str, int]]]]
Timeslots = Dict[Day, List[Timeslot]]
def prettify_timeslots(json_input: str) -> Dict[str, str]:
"""
Prettify a string that contains a valid json representing opening hours in the "ugly format".
The ugly format is defined as a dictionary with the following format
weekday: [
{
"status": "open"/"close"
"value": int
}
...
]
where value is the number of seconds from the midnight of the day.
Days which are missing or where there are no entries are considered days where the restaurant is closed.
The prettified output is in a dictionary with the following format
weekday: "time_opening_1 - time_closing_1, ..., time_opening_n - time_closing_n"
where both time_opening and time_closing are in the 12h clock format.
Minutes and seconds are displayed only if needed.
Parameters
----------
json_input : str
A string contain a JSON encoded "ugly" list of timeslots.
Returns
-------
Dict[str, str]
A prettified version of the input
Raises
------
ValidationError
Raised if
* The JSON cannot be parsed
* If the first status, not on Monday, is a close
* There are same type entries back to back
* There is no matching close entry on Monday for an opening on Sunday
* There is no matching opening on Sunday for a closing on Monday
"""
try:
raw_inputs: RawInputs = json.loads(json_input)
except JSONDecodeError:
raise ValidationError("The input is not a valid JSON")
# Sort the raw inputs by timestamp for each day.
# This allows us to establish some invariants on the data:
# Each opening should be followed by a closing
# There are no repeated opening/closing
# If a day has only one closing then the restourant is closed for that day
inputs: Inputs = {}
for raw_day, raw_values in raw_inputs.items():
day = Day[raw_day.upper()]
inputs[day] = sorted(raw_values, key=lambda k: k['value']) if raw_values else []
timeslots: Timeslots = {}
# we use the following two variables to keep track of what was the status in the previous iteration
previous_status: Optional[Status] = None
opening_timestamp: Optional[int] = None
# As a week is circular we might have that the first entry on Monday is a Sunday closure time.
# If this is the case we flag this and we account for it after the main cycle
starts_monday_closure = False
# we cannot guarantee that we receive the day of the week in the correct order in the JSON
# so we need walk tough the week in the correct order.
# We could sort the dictionary but that would be more expensive.
for day in WEEK:
# days where there are no entries are considered as days where the restaurant is closed.
entries = inputs.get(day, [])
timeslots[day] = []
for i, entry in enumerate(entries):
# Validate the current input and check if we have back to back opening and closing
try:
current_status = Status[entry['type'].upper()]
except ValueError:
raise ValidationError(f"We expected a weekday, instead we got {entry['type']}")
if current_status == previous_status:
raise ValidationError(
f"On {(day)} the opening hours have a repeated {previous_status} status")
if current_status == Status.OPEN:
opening_timestamp = entry['value']
day_opening = day
else:
# we cannot process this right now as we need the matching opening in Sunday
if day == Day.MONDAY and i == 0:
starts_monday_closure = True
continue
# we do not support closing before opening
if previous_status is None:
raise ValidationError(
f"The first status found is a close on {day} without a previous open")
timeslots[day_opening].append(Timeslot.from_timestamps(opening_timestamp,
entry['value']))
opening_timestamp = None
previous_status = current_status
# Deal with the fact that the week is circular so a restaurant might open on Sunday and close on Monday
if previous_status == Status.OPEN:
if starts_monday_closure:
closing_entry = inputs[Day.MONDAY][0]
timeslots[Day.SUNDAY].append(Timeslot.from_timestamps(opening_timestamp,
closing_entry['value']))
else:
raise ValidationError("On Sunday the restaurant opened but it never closed")
elif starts_monday_closure:
raise ValidationError(
"The first action on Monday is close but there is no matching opening on Sunday.")
# As we can have opening and closing that span multiple days with the current implementation
# we cannot do the string conversions inside the previous loop.
# As there are only seven days in a week this is not too computationally expensive but we might need to refactor
# this behavior if the service needs to scale up to massive scale.
output = {}
for day in WEEK:
daily_timeslots = timeslots[day]
if len(daily_timeslots) == 0:
output[str(day)] = "Closed"
else:
output[str(day)] = ", ".join([str(timeslot) for timeslot in timeslots[day]])
return output
def _time_to_pretty_string(time_object: time) -> str:
"""
Cast a time object to string in a pretty format.
Parameters
----------
time_object : time
The time object to cast to string
Returns
-------
str
The pretty string
"""
if time_object.second != 0:
pretty_format = "%I:%M:%S %p"
elif time_object.minute != 0:
pretty_format = "%I:%M %p"
elif time_object.minute is not None:
pretty_format = "%I %p"
pretty_string = time.strftime(time_object, pretty_format)
# We do not want leading zero so 09 AM -> 9 AM
if pretty_string[0] == '0':
return pretty_string[1:]
else:
return pretty_string
def _time_from_timestamp(timestamp: int) -> time:
"""
Casts a timestamp representing the number of seconds from the midnigh to a time object
Parameters
----------
timestamp : int
The number of seconds since midnight
Returns
-------
time
The associated time object
"""
SECONDS_IN_MINUTE = 60
SECONDS_IN_HOUR = 60 * SECONDS_IN_MINUTE
remaining_time = timestamp
hour, remaining_time = divmod(remaining_time, SECONDS_IN_HOUR)
minute, second = divmod(remaining_time, SECONDS_IN_MINUTE)
return time(hour, minute, second)
|
import random
#Empty list that will hold the generated Characters
generated_characters=[]
#loop through 100 to generate 100 rows
for each in range(100):
#Generate characters for each row
generated_characters.append(" ".join(random.choice("AGCT") for each in range(12)))
#Opens or creates a file, greenshoe.csv, for writing only
f=open("greenshoe.csv","w")
if f:
#loops though each item of the list
for each in generated_characters:
#splits the string that has characters that should be inserted into the file above as rows
for eac in each.split(" "):
#write to the file the value of each column followed by a separator, pipe character
f.write(eac + "|")
#moves to the next row
f.write("\n")
#closes the file after writing to it
f.close()
|
# 12. Write a ship battle game, which is similar to ex.8, except it takes 1 integer as an order of matrix,
# randomly generates index (x, y) and checks user input (2 integers).
# (tip: use var1, var2 = raw_input("Enter two numbers here: ").split())
# *Visualize the game.
import random
board = []
for x in range(0,5):
board.append(["*"] * 5)
def print_board(board):
for row in board:
print (" ".join(row))
print ("Let's play Battleship!")
print_board(board)
def random_row(board):
return random.randint(0,len(board)-1)
def random_col(board):
return random.randint(0,len(board[0])-1)
ship_row = random_row(board)
ship_col = random_col(board)
#print (ship_row)
#print (ship_col)
for turn in range(4):
guess_row = int(input("Guess Row:"))
guess_col = int(input("Guess Col:"))
if guess_row == ship_row and guess_col == ship_col:
print ("Congratulations! You sunk my battleship!")
print ("My ship was here: [" + str(ship_row) + "][" + str(ship_col) + "]")
break
else:
if turn == 3:
board[guess_row][guess_col] = "X"
print_board(board)
print ("Game Over")
print ("My ship was here: [" + str(ship_row) + "][" + str(ship_col) + "]")
else:
if (guess_row < 0 or guess_row > 4) or (guess_col < 0 or guess_col > 4):
print ("Oops, that's not even in the ocean.")
elif(board[guess_row][guess_col] == "X"):
print ("You guessed that one already.")
else:
print ("You missed my battleship!")
board[guess_row][guess_col] = "X"
print (turn + 1)
print_board(board)
|
#!/usr/bin/python
import mraa
import time
"""
This script demonstrates the usage of mraa library for configuring and
using a GPIO as input port
setup:
The LED is connected port D5 and button is connected to port D6
Demo:
start the application in the command line by using following command:
python button.py
Press the button to toggle the LED from off to on, on to off...
You can exit this demo by hitting ctrl+c
Link for this tutorial:
https://navinbhaskar.wordpress.com/2015/04/06/python-on-intel-galileoedison-part-2-buttons/
"""
LED_GPIO = 5 # The LED pin
BUTTON_GPIO = 6 # The button GPIO
led = mraa.Gpio(LED_GPIO) # Get the LED pin object
led.dir(mraa.DIR_OUT) # Set the direction as output
ledState = False # LED is off to begin with
led.write(0)
btn = mraa.Gpio(BUTTON_GPIO)
btn.dir(mraa.DIR_IN)
def getButtonPress():
while 1:
if (btn.read() != 0):
continue
else:
time.sleep(0.05)
if (btn.read() == 1):
return
else:
continue
while 1:
getButtonPress()
if ledState == True:
led.write(1)
ledState = False
else:
led.write(0)
ledState = True
time.sleep(0.005)
|
text="hello hai hai hai hai hello hello"
#o/p hello:3 hai :4
#print word count
words=text.split(" ")
#print(words)
dict={}
#dict[word]=1##hello id that word not in dict
#dict[word]+=1 #if that word not in dictionary
for word in words:#"hello" 1st check then hai etc
if(word not in dict):
dict[word]=1
else:
dict[word]+=1
print(dict)
|
#class---design pattern,plan,template,blueprint
#object---real world entity
#reference
#create class using "class"
#class classname
class Person:
#attribute of person self.name,self.age,self.gender
def set_person(self,name,age,gender):
self.name=name
self.age=age
self.gender=gender
def print_person(self):
print("name",self.name)
print("age", self.age)
print("gender", self.gender)
#reference_name=class()
obj=Person()
obj.set_person("ajay",20,"male")
obj.print_person()
|
lst=[6,6,8,9,4,2,3]#otput is [7,7,9,10,3,1,2]
#if num>5 num+1 else num<5 num-1
out=[]
for num in lst:
if(num>5):
out.append(num+1)
else:
out.append(num-1)
print(out)
|
#example pgm
# 1 2 3 4
# 5 6 7 8
# 9 10 11 12
# pgm
#cnt=1
#for i in range(1,13):
# print(i, end="\t")
# if(cnt==4):
# print()
# cnt=1
# else:
# cnt+=1
#nested for loop pgm
#*
#* *
#* * *
#* * * *...........
for row in range(1,5):
for col in range(0,row):
print("*",end=" ")
print()
|
num=int(input("number"))
if(num>0):
print("+ve")
elif(num<0):
print("_ve")
elif(num==0):
print("zero")
|
num1=int(input("Enter the day:"))
num1=int(input("Enter the month:"))
num1=int(input("Enter the year:"))
|
n1=10
n2=3
add=n1+n2
sub=n1-n2
div=n1/n2
mul=n1*n2
flr=n1//n2
mod=n1%n2
print("addition:",add)
print("subsraction:",sub)
print("division:",div)
print("Multiplication:",mul)
print("mod:",mod)
print("floor:",flr)
|
import collections as c
class Node:
def __init__(self, char = ""):
self.char = char
self.children = []
self.last = False
def isNext(self, char):
for i, child in enumerate(self.children):
if child.char == char:
return i
def addChar(self, char):
nexta = self.isNext(char)
if nexta is not None:
return self.children[nexta]
newNode = Node(char)
self.children.append(newNode)
return newNode
def addWord(self, word):
if word:
firstChar = word[0]
nextNode = self.addChar(firstChar)
nextNode.addWord(word[1:])
if not word[1:]:
nextNode.last = True
def __getitem__(self, word):
currentNode = self
while word:
#print(currentNode.char)
nexta = currentNode.isNext(word[0])
if nexta is None:
return False
currentNode = currentNode.children[nexta]
word = word[1:]
return currentNode.last == True
def preOrder(self):
for node in self.children:
print(node.char)
node.preOrder()
def breadthFirst(self):
q = c.deque()
q.append(self)
while q:
rightMost = q.pop()
print(rightMost.char)
for child in rightMost.children:
q.appendleft(child)
a = Node()
a.addWord("hello")
a.addWord("hi")
a.addWord("ello")
#a.preOrder()
#a.breadthFirst()
print(a["hello"])
print(a["hi"])
print(a["ello"])
print(a["hell"])
print(a["pancake"])
|
from fenics import *
import sys
import math
def print_message (ndiv,h):
print("*********************************************************************")
print("Solving Poisson equation using %d divisions -- h = %g" % (ndiv,h))
print("*********************************************************************")
def solve_problem (ndiv):
# Calculate spatial discretization
h = float(1.0/ndiv)
# Output a message to the user
print_message(ndiv,h)
# _________________________________________________________________
# Create mesh and define function space
# Square mesh consist of ndiv by ndiv squares, where each square is divided in two triangles
mesh = UnitSquareMesh(ndiv, ndiv)
# Create the finite element function space V
# Function space consist of standard Lagrange elements with degree 1
V = FunctionSpace(mesh, 'P', 2)
# __________________________________________________________________
# Define boundary condition
u_D = Expression('1 + x[0]*x[0] + 2*x[1]*x[1]', degree=2)
def boundary(x, on_boundary):
return on_boundary
bc = DirichletBC(V, u_D, boundary)
# __________________________________________________________________
# Define variational problem
u = TrialFunction(V)
v = TestFunction(V)
f = Constant(-6.0)
a = dot(grad(u), grad(v))*dx
L = f*v*dx
# __________________________________________________________________
# Compute solution
u = Function(V)
solve(a == L, u, bc)
# __________________________________________________________________
# Plot solution and mesh
plot(u)
plot(mesh)
# __________________________________________________________________
# Save solution to file in VTK format
vtkfile = File('poisson/solution%d.pvd' % ndiv)
vtkfile << u
# __________________________________________________________________
# Compute error in L2 norm
error_L2 = errornorm(u_D, u, 'L2')
# __________________________________________________________________
# Compute maximum error at vertices
vertex_values_u_D = u_D.compute_vertex_values(mesh)
vertex_values_u = u.compute_vertex_values(mesh)
import numpy as np
error_max = np.max(np.abs(vertex_values_u_D - vertex_values_u))
return h, error_L2, error_max
def main():
if (len(sys.argv) != 2):
print("========================================================")
print("Usage:> python poisson.py <number_of_simulations>")
print("========================================================")
sys.exit(1)
n_simulations = int(sys.argv[1])
outFile = open("output.dat","w")
# Number of divisions
ndiv = 2
for i in range(n_simulations):
h, error_L2, error_max = solve_problem(ndiv)
outFile.write("%g %g %g\n" % (h,error_L2,error_max))
ndiv = ndiv * 2
outFile.close()
if __name__ == "__main__":
main()
|
import random
from playsound import playsound
def gameWin(comp, you):
if comp == you:
return None
elif comp == 'r':
if you == 's':
return False
elif you == 'p':
return True
elif comp == 'p':
if you == 'r':
return False
elif you == 's':
return True
elif comp == 's':
if you == 'p':
return False
elif you == 'r':
return True
c = 0
g = 0
for i in range(1, 100000):
print("Bot has made his decision")
you = input("Waiting for yor turn: Rock(r) Paper(p) Scissor(s)?: ")
if(you == 'r'):
z='rock'
elif(you=='p'):
z='paper'
elif(you=='s'):
z='scissor'
else:
print("You have to play Rock, Paper or Scissor by entering r,p or s")
playsound('https://assets.mixkit.co/sfx/preview/mixkit-quick-jump-arcade-game-239.mp3')
continue
randNo = random.randint(1, 3)
if randNo == 1:
comp = 'r'
f='rock'
elif randNo == 2:
comp = 'p'
f='paper'
elif randNo == 3:
comp = 's'
f='scissor'
a = gameWin(comp, you)
print(f"Computer chose {f}")
print(f"You chose {z}")
if a == None:
print("The game is a tie!")
playsound('https://assets.mixkit.co/sfx/preview/mixkit-player-jumping-in-a-video-game-2043.mp3')
i=i-1
elif a:
print("You Win this round!")
playsound('https://assets.mixkit.co/sfx/preview/mixkit-game-loot-win-2013.mp3')
c = c+1
else:
print("You Lose this round!")
playsound('https://assets.mixkit.co/sfx/preview/mixkit-retro-arcade-lose-2027.mp3')
g = g+1
print(f"Score is: Bot\t{g} You\t{c}\n")
if c == 5 or g == 5:
break
if g>c:
print("Computer won the tournament")
playsound('https://assets.mixkit.co/sfx/preview/mixkit-negative-answer-lose-2032.mp3')
else:
print("You won the tournament")
playsound('https://assets.mixkit.co/sfx/preview/mixkit-medieval-show-fanfare-announcement-226.mp3')
|
i = 1
sum = 0
while i <= 10:
user = int(raw_input("enter your number"))
sum = sum + user
average = sum / i
i = i + 1
print (average)
|
user = int(raw_input("enter your number"))
if user > 0:
print "positive umber h",user
else:
print "nagative h",user
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.