text
stringlengths
37
1.41M
magicians = ['alice', 'david', 'carolina'] for magician in magicians: print(magician.title() + ",that was a grest trick!") print("I can't wait to see your next tridk, " + magician.title() + '.\n') print("Thank you,everyone.That was a great magic show!") #pizza pizzas = ['pizzas1', 'pizzas2', 'pizzas3'] for pizza in pizzas: print('I like ' + pizza.title()) print('I really love pizza') #pet pets = ["dog", "cat", "pig", "tiger"] for pet in pets: print("A " + pet + " would make a great pet!") print('Any of these animals would make a great pet!')
""" File: sierpinski.py Name: --------------------------- This file recursively prints the Sierpinski triangle on GWindow. The Sierpinski triangle is a fractal described in 1915 by Waclaw Sierpinski. It is a self similar structure that occurs at different levels of iterations. """ import math from campy.graphics.gwindow import GWindow from campy.graphics.gobjects import GPolygon from campy.gui.events.timer import pause # Constants ORDER = 6 # Controls the order of Sierpinski Triangle LENGTH = 600 # The length of order 1 Sierpinski Triangle UPPER_LEFT_X = 150 # The upper left x coordinate of order 1 Sierpinski Triangle UPPER_LEFT_Y = 100 # The upper left y coordinate of order 1 Sierpinski Triangle WINDOW_WIDTH = 950 # The width of the GWindow WINDOW_HEIGHT = 700 # The height of the GWindow # Global Variable window = GWindow(width=WINDOW_WIDTH, height=WINDOW_HEIGHT) # The canvas to draw Sierpinski Triangle def main(): """ TODO: """ sierpinski_triangle(ORDER, LENGTH, UPPER_LEFT_X, UPPER_LEFT_Y) def sierpinski_triangle(order, length, upper_left_x, upper_left_y): """ :param order: :param length: :param upper_left_x: :param upper_left_y: :return: """ if order == 0: return else: # 運算出倒三角的三點位置 point_list = three_point(length / 2) # 依序對三點位置,做下一階的遞迴運算 for point in point_list: sierpinski_triangle(order - 1, length / 2, upper_left_x + point[0], upper_left_y + point[1]) # 只印最後的 1 order,減少重複顯示 if order == 1: draw_triangle(length, upper_left_x, upper_left_y) # pause(400) def three_point(length): """ 功能:描繪三點(x,y)位置,運用極座標-三角函數與長度 :param length: 長度 :return point_list(list): 內有三點各自的(x,y)位置 """ point_list = [] # 初始化 dis_x = 0 dis_y = 0 # 運用三角函數,描繪三點位置 for edge in range(3): # 從角度轉成弧 rad = math.radians(-120 * edge) # x向右為正,(+)cos dis_x += length * math.cos(rad) # y向下為正,(-)sin dis_y += -length * math.sin(rad) point_list.append((dis_x, dis_y)) return point_list def draw_triangle(length, start_x, start_y): """ 功能: :param length: :param start_x: :param start_y: :return: """ triangle = GPolygon() triangle.add_vertex((start_x, start_y)) for edge in range(3): triangle.add_polar_edge(length, -120 * edge) window.add(triangle) if __name__ == '__main__': main()
def root_1(a = 10, p = 3, delta = 0.001, nn = 20, i = 1): 'pth root of a - thru\' successive bifurcation' #delta is the acceptable accuracy #p is the exponent - integer #nn is the maximum number of iterations acceptable #i is the initial interval used for searching b, bp, n = 1, 1, 0 while bp < a: b += i bp = b**p b1, b2 = b - i, b while (b2 - b1 > delta) and (n < nn): n += 1 bm = (b1 + b2)/2.0 if a > bm**p:b1 = bm else: b2 = bm print('bm = ', bm, ', p = ', p, 'n = ', n, ', a = ', a) return
from enum import Enum class Element(Enum): STREET = " " BUILDING = "X" PERSON = 2 def format_block(element_enum): if element_enum == Element.STREET: return " " elif element_enum == Element.BUILDING: return "X" elif element_enum == Element.PERSON: return "2" else: return element_enum
import pandas as pd import matplotlib.pyplot as plt plt.style.use('bmh') df = pd.read_csv(r"C:\Users\mauro\Desktop\Renata\Project Python\Projects_done\SuperStore_dataset\SampleSuperstore.csv", index_col=[0]) print(df.head()) # Shape, type and verify if it has value null print('Shape = {}'.format(df.shape)) print('Data Type of each column\n{}'.format(df.dtypes)) print(df.isnull().sum()) df = df.reset_index() # Verify the Country column if there's an unique value and skip it if not print(df['Country'].nunique()) df = df.drop(['Ship Mode', 'Country', 'Postal Code', 'Region'], axis=1) print(df.head()) # Some statistics print(df.describe()) print(df['Profit'].describe()) # Format the float numbers displayed on the tables pd.options.display.float_format = '{:20,.2f}'.format # Total profit total_profit = df['Profit'].sum() print('Total profit = ${:0,.2f}'.format(total_profit)) # Create a Cost column and total cost df['Cost'] = df['Sales'] - df['Profit'] total_cost = (df['Cost'].sum()) print('Total cost = ${:0,.2f}'.format(total_cost)) # Profit in percentage print('Profit(%) = {:0,.2f}%'.format(total_profit / total_cost * 100)) # Which segment gives less profit and more costs less_profit_segment = df.groupby('Segment')['Profit'].min().plot.bar(title='Least Profitable Segment', fontsize=9) # Consumers - Corporate -Home plt.ylabel('Profit ($)') plt.xticks(rotation='horizontal') plt.show() costly_segment = df.groupby('Segment')['Cost'].max().sort_values(ascending=False).plot.bar(title='Costly Segment', fontsize=9) # Home Office - Corporate - Consumer plt.ylabel('Cost ($)') plt.xticks(rotation='horizontal') plt.show() # Proporcional relation, Cost more, more profit, Cost less, less profit # TOP 3 states that result less profit and more costs print(df.groupby('State')['Profit'].sum().nsmallest(3)) print(df.groupby('State')['Cost'].sum().nlargest(3)) # Texas has the least profit and the third most costly # Exploring more the states with less profit and more costs print(df.groupby(['State', 'City'])['Profit'].sum().nsmallest(3)) print(df.groupby(['State', 'City'])['Cost'].sum().nlargest(3)) # From the cities, Philadelphia (Pennsylvania state) has the least profit and the third most costly # Graph of profit by category # print(df.groupby(['Category', 'Sub-Category'])['Profit'].sum()) df.groupby(['Category'])['Profit'].sum().sort_values(ascending=False).plot.pie(title='Profitable category', autopct="%.2f%%", fontsize=9, figsize=(5, 5)) plt.show() print(df.groupby(['Category'])['Profit'].sum()) # Graph of costs by category df.groupby(['Category'])['Cost'].sum().sort_values(ascending=False).plot.pie(title='Costly category', autopct="%.2f%%", fontsize=9, figsize=(5, 5)) plt.show() print(df.groupby(['Category'])['Cost'].sum()) # Costs are well distributed by category # Graph of quantity sold by category df.groupby('Category')['Quantity'].sum().sort_values(ascending=False).plot.pie( title='Quantity of products sold by category', autopct="%.2f%%", fontsize=9, figsize=(5, 5)) plt.show() # Technology is more profitable, selling less quantities. Inversely proportional, less quantity for more profit and more quantity for less profit # Checking which state had highest and lowest discount print(df.groupby('State')['Discount'].max().nlargest(3)) print(df.groupby('State')['Discount'].min().nsmallest(3)) print(df.groupby(['State', 'City'])['Discount'].max().nsmallest(3)) print(df.groupby(['State', 'City'])['Discount'].min().nlargest(3)) # Discount given doesnt seems to be related to the low profit # Checking if the total sales has relation to the low profit # print(df.groupby('State')['Sales'].sum().nlargest(3)) # print(df.groupby('State')['Sales'].sum().nsmallest(3)) df.groupby('State')['Sales'].sum().nlargest(3).sort_values(ascending=False).plot.bar(title='Top 3 States of Sales ', fontsize=8, figsize=(5, 5)) plt.xlabel('States') plt.ylabel('Sales ($)') plt.xticks(rotation='horizontal') plt.show() df.groupby('State')['Sales'].sum().nsmallest(3).sort_values(ascending=True).plot.bar(title='Last 3 States of Sales ', fontsize=8, figsize=(5, 5)) plt.xlabel('States') plt.ylabel('Sales ($)') plt.xticks(rotation='horizontal') plt.show() # Texas has the least profit, but it's the third of the sales # Save analysis as csv df.to_csv('df_super_store_analysis.csv', index=False)
""" - author: Johannes Hötter (https://github.com/johannes-hoetter) - version: 1.0 - last updated on: 05/12/2018 Converts the Data from Source Format to Target / Machine Learning Format """ import pandas as pd # for dataframe operations import datetime # to convert columns in the dataframe try: import _pickle as pickle # for serialization, _pickle == cPickle (faster than pickle) except: import pickle # alternative from sklearn.preprocessing import StandardScaler # for ml format from collections import OrderedDict import numpy as np class DataConverter(): """ Transforms Data from the raw structure to the target structure, so that Machine Learning can be applied on the data. """ def __init__(self): """ Initialize the DataConverter """ self.scalers = {} def convert_df(self, df): """ convert a dataframe from source structure to target structure (splits datestamps) :param df (pandas dataframe): source dataframe :return pandas dataframe: target dataframe """ # replace whitespaces in columns with underscores df.columns = [col.replace(' ', '_') for col in df.columns] # convert datestring to dates df['Date'] = df['Date'].apply(lambda x: datetime.datetime.strptime(x, '%Y-%m-%d')) df['Year'] = df['Date'].apply(lambda x: x.year) df['Month'] = df['Date'].apply(lambda x: x.month) df['Day'] = df['Date'].apply(lambda x: x.day) df.drop('Date', axis=1, inplace=True) return df def fill_targets(self, df): """ gets the price for the share for the next date for each row except the last one - the last gets dropped :param df (pandas dataframe): dataframe containing the financial data :return pandas dataframe: dataframe with targets for machine learning """ # for each date (except the last one), get the adjusted close price from the next date df.sort_values(by=['Year', 'Month', 'Day'], inplace=True) # dates in right order next_day_adj_close = df['Adj._Close'].iloc[1:] # get the prices of the next day next_day_adj_close.index += 1 df['Adj._Close_next'] = next_day_adj_close df.reset_index(drop=True, inplace=True) # reset index so that earliest date has index 0 df.drop(df.index.max(), inplace=True) # get rid of the last row, as we don't know the target for this one return df def convert_ml_format(self, df, symbol, target='Adj._Close_next'): """ converts the dataframe into the known two array X and y containing the inputs and the labels for machine learning. :param df (pandas dataframe): source dataframe after conversion and after targets have been filled :param symbol (string): string representation of the stock (e.g. "AMZN" for Amazon) :param target (string): column of the dataframe which contains the targets :return numpy array, numpy array: X, y """ X = df.drop(target, axis=1).values # whole df except last column (which is the target) y = df[target].values # only target column scaler = StandardScaler() X = scaler.fit_transform(X) self.scalers[symbol] = scaler return X, y def convert_x(self, x, symbol): """ convert a single input so that it fits to the training data (scalewise) :param x (dictionary): contains the values :param symbol (string): string representation of the stock (e.g. "AMZN" for Amazon) :return numpy array: array in machine learning format """ ''' Example - MUST KEEP THE KEY-ORDER!: x = { 'Open': 20.6, 'High': 21.45, 'Low': 20.22, 'Close': 20.6, 'Volume': 23402800.0, 'Ex-Dividend': 0.0, 'Split_Ratio': 1.0, 'Adj._Open': 15.624619538007, 'Adj._High': 16.269324713118998, 'Adj._Low': 15.336398400897998, 'Adj._Close': 15.624619538007, 'Adj._Volume': 23402800.0, 'Year': 2008.0, 'Month': 4.0, 'Day': 23.0 } ''' x = OrderedDict(x) # don't change the value of the dict! try: scaler = self.scalers[symbol] except: raise Exception('Symbol {} not contained in Trainingset, therefore not possible to convert the input.'.format(symbol)) x_values = np.array(list(x.values())).reshape(1, -1) ml_x = scaler.transform(x_values) return ml_x def serialize(self, path='serialized_tool_objects/dataconverter.p'): """ Save the Converter to a pickle file :param path (string): path to the location where the converter gets serialized to """ with open(path, 'wb') as file: pickle.dump(self.scalers, file) def initialize(self, path='serialized_tool_objects/dataconverter.p'): """ Load the converters attributes :param path (string): path where the converter has been serialized to :return: """ with open(path, 'rb') as file: self.scalers = pickle.load(file) def __repr__(self): """ :return (string): string representation of the Object """ return 'DataConverter()'
""" Uses Vadar Sentiment Analysis to calculate the polarity of text. """ import numpy as np import pandas as pd import nltk from nltk.sentiment.vader import SentimentIntensityAnalyzer import constants as c nltk.download('vader_lexicon') def polarity(dataframe, review_column): """ Takes a dataframe and the column name containing text to calculate the sentiment polarity of. Calculates polarity then appends to existing dataframe to return. :params dataframe dataframe: :params review_column string: :returns dataframe: """ # Datatype checks if not isinstance(dataframe, pd.DataFrame): raise ValueError('dataframe is not a pandas dataframe') if not isinstance(review_column, str): raise ValueError('review_column is not a string') if not review_column in dataframe: raise ValueError('review_column is not in the dataframe') dataframe = dataframe.dropna() rows = dataframe.shape[0] scores_array = np.zeros([rows, 4]) keys = [] index_1 = 0 for review in dataframe[review_column]: scores = SentimentIntensityAnalyzer().polarity_scores(review) scores_array[index_1] = list(scores.values()) if index_1 == 0: keys = list(scores.keys()) index_1 += 1 index_2 = 0 for k in keys: dataframe[k] = scores_array[:, index_2] index_2 += 1 return dataframe def summarize_sentiment(dataframe, group_on_list, avg_over_column): """ Takes a dataframe, a list of columns you wish to group, and the column to be summarized. Calculates the mean, variance, and count of the summarized column. Outputs the summarized dataframe to a .csv and returns the dataframe. :params dataframe dataframe: :params group_on_list list: :params avg_over_column string: :returns dataframe: """ # Datatype checks if not isinstance(dataframe, pd.DataFrame): raise ValueError('dataframe is not a pandas dataframe') if not isinstance(group_on_list, list): raise ValueError('group_on_list is not a list') if not isinstance(avg_over_column, str): raise ValueError('avg_over_column is not a string') all_columns = group_on_list + [avg_over_column] results = dataframe[all_columns].groupby(group_on_list).agg( {avg_over_column : ['mean', 'var', 'count']}) results = results[avg_over_column].reset_index() results.to_csv(c.DATA_FOLDER + c.SENTIMENT_CSV, index=False) return results
import time n = int(input('Height: ')) while (n < 1 or n > 10): n= int(input('Height: ')) #prints nxn bricks for i in range(n): for j in range(n): print('#',end='') print() time.sleep(0.1) print() time.sleep(2) #prints left-sided brick steps for i in range(n): for j in range(i+1): print('#',end='') print() time.sleep(0.1) print() time.sleep(2) #prints upsided brick steps for i in range(n): for j in range(n-i): print('#',end='') print() time.sleep(0.1) print() time.sleep(2) #prints right-sided bricks for i in range(n): for j in range(n-i): print(' ', end='') for k in range(i+1): print('#', end='') print() time.sleep(0.1) print() time.sleep(2) #prints dual bricks for i in range(n): for j in range(n-i): print(' ', end='') for k in range(i+1): print('#', end='') time.sleep(0.1) for l in range(n): print(' ', end='') for m in range(i+1): print('#', end='') time.sleep(0.1) print()
from collections import Counter import time def greedy2(money,coins): result = 0 #checking if input is a string or value is negative while True: if (money.isalpha() or float(money) < 0): money= input("Change: ") else: break money = float(money) #accepts floating numbers cents = int(100*money) #converting to integer while cents >= 0: if cents >= coins[0]: cents -= coins[0] money_list.append(coins[0]) result += 1 elif cents >= coins[1]: cents -= coins[1] money_list.append(coins[1]) result += 1 elif cents >= coins[2]: cents -= coins[2] money_list.append(coins[2]) result += 1 elif cents >= coins[3]: cents -= coins[3] money_list.append(coins[3]) result += 1 else: break return result coins = [25,10, 5, 1] money_list = [] money= input("Change: ") t1= time.time() result= greedy2(money,coins) t2 = time.time() print(result) print(Counter(money_list)) print(t2-t1)
''' 请你来实现一个 atoi 函数,使其能将字符串转换成整数。 首先,该函数会根据需要丢弃无用的开头空格字符,直到寻找到第一个非空格的字符为止。 当我们寻找到的第一个非空字符为正或者负号时,则将该符号与之后面尽可能多的连续数字组合起来,作为该整数的正负号;假如第一个非空字符是数字,则直接将其与之后连续的数字字符组合起来,形成整数。 该字符串除了有效的整数部分之后也可能会存在多余的字符,这些字符可以被忽略,它们对于函数不应该造成影响。 注意:假如该字符串中的第一个非空格字符不是一个有效整数字符、字符串为空或字符串仅包含空白字符时,则你的函数不需要进行转换。 在任何情况下,若函数不能进行有效的转换时,请返回 0。 说明: 假设我们的环境只能存储 32 位大小的有符号整数,那么其数值范围为 [−231, 231 − 1]。如果数值超过这个范围,qing返回 INT_MAX (231 − 1) 或 INT_MIN (−231) 。 ''' class Solution(object): def myAtoi(self, str): #去首尾空格 str = str.strip() #判断空长度 strNum = 0 if len(str) == 0: return strNum # positive = True if str[0] == '+' or str[0] == '-': if str[0] == '-': positive = False str = str[1:] for char in str: if char >='0' and char <='9': ''' a = '8' ord(a)-ord('0') = 56-48=8 ''' strNum = strNum*10+(ord(char) - ord('0'))#这次输出就是8,下次输出就是80+newaddNum if char < '0' or char > '9':#如果后面读到的不是数字,就break 数字读取循环 break #边界判断,分别对正负边界判断 if positive == False and strNum > 2147483648: return -2147483648 elif positive == True and strNum > 2147483647: return 2147483647 if not positive: strNum = 0 - strNum return strNum
#Galilean Moons of Jupiter def radius(): radius_dict = {'Io': 1821.6, 'Europa': 1560.8, 'Ganymede': 2634.1, 'Callisto': 2410.3} return radius_dict def sur_gravity(): sur_gravity_dict = {'Io': 1.796, 'Europa': 1.314, 'Ganymede': 1.428, 'Callisto': 1.235} return sur_gravity_dict def orbital_per(): orbital_per_dict = {'Io': 1.769, 'Europa': 3.551, 'Ganymede': 7.154, 'Callisto': 16.689} return orbital_per_dict def info(user_input, radius_dict, sur_gravity_dict, orbital_per_dict): print("Moon's mean radius:", radius_dict[user_input]) print("Moon's surface gravity:", sur_gravity_dict[user_input]) print("Moon's orbital period:", orbital_per_dict[user_input]) def main(): user_input = input('Enter the name of a Galilean moons of Jupiter: ') radius_dict = radius() sur_gravity_dict = sur_gravity() orbital_per_dict = orbital_per() if user_input in radius_dict: info(user_input, radius_dict, sur_gravity_dict, orbital_per_dict) else: print('No info, check the name again.') if __name__ == '__main__': main()
#time calculator import sys seconds = int(input('Enter the number of seconds: ')) if(seconds < 0): sys.exit('Enter a right number') elif(seconds == 0): print('Seconds = 0') elif(0 < seconds < 60): print('Seconds = '+str(seconds)) elif(60 <= seconds < 3600): minutes = int(seconds / 60) seconds = int(seconds - (minutes * 60)) print('Minutes = ' +str(minutes)+ '\nSeconds = ' +str(seconds)) elif(3600 <= seconds < 86400): hours = int(seconds / 3600) seconds = int(seconds - (hours * 3600)) minutes = int(seconds / 60) seconds = int(seconds - (minutes * 60)) print('Hours = ' +str(hours)+ '\nMinutes = '+str(minutes)+ '\nSeconds = '+str(seconds)) elif (seconds >= 86400): days = int(seconds / 86400) seconds = int(seconds - (days * 86400)) hours = int(seconds / 3600) seconds = int(seconds - (hours * 3600)) minutes = int(seconds / 60) seconds = int(seconds - (minutes * 60)) print('days = ' +str(days)+ '\nHours = ' + str(hours) + '\nMinutes = ' + str(minutes) + '\nSeconds = ' +str(seconds))
#high score def main(): file = open('scores.txt','r') read = file.readline() count = 0 highest = 0 name = '' while read != '': a = read.split(' ') count += 1 read = file.readline() a[1] = int(a[1]) if a[1] > highest: highest = a[1] name = a[0] print('The total number of records:', count) print('Highest Score:', highest, 'Student Name:', name) file.close() main()
#calculating factorial import sys num = int(input('Enter a non-negative integer to find the factorial: ')) product = 1 if num < 0: sys.exit("Can't find factorial of a negative number") if num == 0: product = 0 while num > 0: product = product * num num -= 1 print('The factorial of the number is',product)
#Date printer def date_print(date): date = date.split('/') if date[0] == '01': print('January', date[1] + ',', date[2]) elif date[0] == '02': print('February', date[1] + ',', date[2]) elif date[0] == '03': print('March', date[1] + ',', date[2]) elif date[0] == '04': print('April', date[1] + ',', date[2]) elif date[0] == '05': print('May', date[1] + ',', date[2]) elif date[0] == '06': print('June', date[1] + ',', date[2]) elif date[0] == '07': print('July', date[1] + ',', date[2]) elif date[0] == '08': print('August', date[1] + ',', date[2]) elif date[0] == '09': print('September', date[1] + ',', date[2]) elif date[0] == '10': print('October', date[1] + ',', date[2]) elif date[0] == '11': print('November', date[1] + ',', date[2]) elif date[0] == '12': print('December', date[1] + ',', date[2]) else: print('Make sure you enter the right month.') def main(): date = input('Enter the date in mm/dd/yyyy format: ') date_print(date) main()
#money counting game quarters = int(input('Enter the number of quarters: ')) dime = int(input('Enter the number of dimes: ')) nickels = int(input('Enter the number of nickels: ')) penny = int(input('Enter the number of pennies: ')) amount = quarters * 0.25 + dime * 0.1 + nickels * 0.05 + penny * 0.01 if amount < 1: print('You lose, the amount is less than $1') elif amount > 1: print('You lose, the amount is more than $1') else: print('Congrats, you won')
#string repeater string = input('Enter the string: ') number = int(input('Enter the number of times you want to print the string: ')) def string_print(x, y): for num in range(y): print(x,end='') if __name__ == '__main__': string_print(string,number)
#file line viewer def readFile(): fileName = input('Enter the file name along with the extension: ') file = open(fileName, 'r') fileInfo = list() total_lines = 0 while True: line = file.readline() line = line.rstrip('\n') if line == '': break total_lines += 1 fileInfo.append(line) print('Number of lines of data in the file:', total_lines) return fileInfo def main(): fileInfo = readFile() number = int(input('Enter the line number you want to read from the file: ')) print('The data at this line number is:', fileInfo[number+1]) main()
#loan payment calculator def payment_calculator(rate, amount, months): payment_per_month = (rate * amount)/(1 - (1 + rate)**-months) print('The month payment amount will be $',format(payment_per_month, '.2f')) def main(): rate = float(input('Enter the rate of interest as a decimal (e.g. 2.5% 5 0.025): ')) amount = float(input('Enter the amount of the loan: $')) months = int(input('Enter the desired number of months: ')) payment_calculator(rate, amount, months) main()
#falling distance def falling_distance(time): g = 9.8 distance = 1/2 * g * time**2 return distance def main(): for x in range(10): time = float(input('Enter the time: ')) print('The distance(in metres) that the object has fallen in that time:', format(falling_distance(time),'.2f')) main()
# rainfall statistics def get_input(): user_input = list() for num in range(12): data = float(input('Enter the amount of rainfall in ' + str(num+1) + ' month: ')) user_input.append(data) return user_input def calculations(user_input): print('The total rainfall for the year was:', sum(user_input)) print('The average rainfall for the year was:', format(sum(user_input)/12, '.2f')) print('The minimum rainfall amount was in:', min(user_input)) print('The maximum rainfall amount was in:', max(user_input)) def main(): calculations(get_input()) main()
import employee_Class import pickle def get_data(): name = input('Enter the name: ') ID = input('Enter the ID: ') department = input('Enter the department: ') job_title = input('Enter the job_title: ') return name, ID, department, job_title def save_data(employee_dict): output_file = open('employeeData.dat', 'wb') pickle.dump(employee_dict, output_file) output_file.close() def employee_info(): try: input_file = open('employeeData.dat', 'rb') employee_dict = pickle.load(input_file) input_file.close() except IOError: employee_dict = dict() return employee_dict def look_up(employee_dict): employee_id = input('Enter the id of the employee you want to look for: ') print(employee_dict.get(employee_id, 'ID not found')) def add(employee_dict): name = input('Enter the name: ') ID = input('Enter the ID: ') department = input('Enter the department: ') job_title = input('Enter the job_title: ') obj = employee_Class.Employee(name, ID, department, job_title) if ID not in employee_dict: employee_dict[ID] = obj print('Employee information added to the database') else: print('Entry already exists') def change(employee_dict): ID = input('Enter the ID of the employee for whom you want to update the info: ') if ID in employee_dict: name = input('Enter the name: ') department = input('Enter the department: ') job_title = input('Enter the job_title: ') obj = employee_Class.Employee(name, ID, department, job_title) employee_dict[ID] = obj print('Employee information updated in the database') else: print('No employee with this ID exists.') def delete(employee_dict): ID = input('Enter the ID of the employee ypu wanna delete: ') if ID in employee_dict: del employee_dict[ID] print('Employee info deleted') else: print('No employee with this ID exists') def my_menu(): print('MENU') print('1. View details of the employees') print('2. Add a new employee') print('3. Change details for an employee') print('4. Delete an employee') print('5. Quit') usr_input = int(input('Enter your choice: ')) while 5 < usr_input or usr_input < 1: print('Enter a valid choice') usr_input = int(input('Enter your choice: ')) return usr_input def main(): employee_dict = employee_info() print('Welcome to the employee portal!!!!') choice = my_menu() while choice != 5: if choice == 1: look_up(employee_dict) elif choice == 2: add(employee_dict) elif choice == 3: change(employee_dict) elif choice == 4: delete(employee_dict) choice = my_menu() save_data(employee_dict) main()
import patientClass import procedureClass def procedure(): name = input('Enter the name of the procedure: ') date = input('Enter the date when the procedure was performed: ') name_practitioner = input('Enter the name of the practitioner who performed the procedure: ') charges = input('Enter the charges for the procedure: ') obj = procedureClass.Procedure(name, date, name_practitioner, charges) return obj def procedure_info(): print('Procedure 1') obj1 = procedure() print('Procedure 2') obj2 = procedure() print('Procedure 3') obj3 = procedure() return obj1, obj2, obj3 def print_procedure_info(obj): print('Name of procedure:', obj.get_name()) print('Date of procedure:', obj.get_date()) print('Practitioner Name:', obj.get_name_practitioner()) print('Charges:', obj.get_charges()) print('\n') def patient_info(): name = input('Enter the full name of the patient(First name followed by middle and last name): ') address = input('Enter full address with city, state and zip code: ') phone = input('Enter the phone number: ') emergency = input('Enter the name and phone number of the emergency contact: ') obj = patientClass.Patient(name, address, phone, emergency) obj1, obj2, obj3 = procedure_info() print('\n') print('Patient info') print('Name:', obj.get_name()) print('Address:', obj.get_address()) print('Phone:', obj.get_phone()) print('Emergency Contact:', obj.get_emergency()) print('\n') print('Procedure 1 info') print_procedure_info(obj1) print('Procedure 2 info') print_procedure_info(obj2) print('Procedure 3 info') print_procedure_info(obj3) total_charges = format(float(obj1.get_charges()) + float(obj2.get_charges()) + float(obj3.get_charges()), '.2f') print('Total charges for all three procedures: $', total_charges) def main(): patient_info() main()
#kilometer converter kilometer = float(input('Enter the distance in km: ')) miles = kilometer * 0.6214 print('The distance in miles is:',miles,'mph')
#ocean levels year = 25 print('Year\tLevel Rise') level = 1.6 for num in range(1,year+1): print(num,'\t\t',format(level,'.2f'),'mm') level += 1.6
sum = 0 for i in range(1,1000): if i%3==0: #Check whether i is divisible by 3 sum+=i elif i%5==0: #Check whether i is divisible by 5 sum+=i print "Sum of all the multiples of 3 or 5 below 1000:", sum
class Solution: """ A message containing letters from A-Z is being encoded to numbers using the following mapping: 'A' -> 1 'B' -> 2 ... 'Z' -> 26 Given a non-empty string containing only digits, determine the total number of ways to decode it. Example 1: Input: "12" Output: 2 Explanation: It could be decoded as "AB" (1 2) or "L" (12). Example 2: Input: "226" Output: 3 Explanation: It could be decoded as "BZ" (2 26), "VF" (22 6), or "BBF" (2 2 6). """ def numDecodings(self, s: str) -> int: if not s: return 0 dp = [0 for x in range(len(s) + 1)] dp[0] = 1 dp[1] = 0 if s[0] == "0" else 1 for i in range(2, len(s) + 1): if 0 < int(s[i-1:i]) <= 9: dp[i] += dp[i - 1] if 10 <= int(s[i-2:i]) <= 26: dp[i] += dp[i - 2] return dp[len(s)] if __name__ == "__main__": pass
""" This file contains a number of built in strategies that can be passed to the Player class as arguments for strategy_func, wager_func, or insurance_func """ import random import pandas as pd from pathlib import Path CUR_PATH = Path(__file__).resolve().parent # read in strategy files BASIC_HARD = pd.read_csv( Path(CUR_PATH, "strategy_files", "basic_hard.csv"), index_col=0 ).to_dict() BASIC_SOFT = pd.read_csv( Path(CUR_PATH, "strategy_files", "basic_soft.csv"), index_col=0 ).to_dict() BASIC_SPLIT = pd.read_csv( Path(CUR_PATH, "strategy_files", "basic_split.csv"), index_col=0 ).to_dict() def basic_strategy(player, hand, dealer_up, game_params, **kwargs): """ Function that plays with the basic strategy. Source: https://www.blackjackapprenticeship.com/blackjack-strategy-charts/ This function can be used at the strategy_func argument in an instance of of the Player class. Parameters ---------- player: instance of the Player class hand: instance of the Hand class dealer_up: dealer's up card game_params: rules of the specific game **kwargs: misc. arguements that get passed into the function Returns ------- One of the following: HIT, STAND, DOUBLE, SPLIT """ # strategy for splits if (hand.cards[0].value == hand.cards[1].value) and len(hand.cards) == 2: action = BASIC_SPLIT[str(dealer_up)][hand.cards[0].value] if action == "P": return "SPLIT" elif action == "Ph": if game_params.double_after_split: return "SPLIT" else: return "HIT" elif action == "Rp": if game_params.surrender_allowed: return "SURRENDER" else: return "SPLIT" elif action == "S": return "STAND" # strategy for hard hands if not hand.soft: action = BASIC_HARD[str(dealer_up)][hand.total] else: action = BASIC_SOFT[str(dealer_up)][hand.total] # return input accepted by the blackjack game if action == "H": return "HIT" elif action == "S": return "STAND" elif action.startswith("D"): # see if double down is allowed allowed = len(hand.cards) == 2 and hand.player.bankroll >= hand.wager if hand.from_split and allowed: allowed = game_params.double_after_split if not allowed: if action.endswith("h"): return "HIT" elif action.endswith("s"): return "STAND" return "DOUBLE" elif action == "Rh": allowed = len(hand.cards) == 2 and game_params.surrender_allowed if hand.from_split: allowed = game_params.surrender_after_split if allowed: return "SURRENDER" else: return "HIT" elif action == "Rs": allowed = len(hand.cards) == 2 and game_params.surrender_allowed if hand.from_split: allowed = game_params.surrender_after_split if allowed: return "SURRENDER" else: return "STAND" else: msg = f"{action} does not have associated action" raise ValueError(msg) def user_input(player, hand, dealer_up, count, ten_count, other_count, **kwargs): """ Function that asks the user for input to select an action This function can be used at the strategy_func argument in an instance of of the Player class. """ print(f"Total: {hand.total}") print(f"Ten Ratio: {other_count / ten_count}") action = input("\nEnter Action (h, s, d, sp): ") if action == "h": return "HIT" elif action == "s": return "STAND" elif action == "d": return "DOUBLE" elif action == "sp": return "SPLIT" def hit_to_seventeen(player, hand, **kwargs): """ Hit until the hand total reaches 17 This function can be used at the strategy_func argument in an instance of of the Player class. """ if hand.total >= 17: return "STAND" else: return "HIT" def minimum_bet(player, min_bet, max_bet, **kwargs): """ Function to serve as the default wager function if user doesn't input their own """ return min_bet def maximum_bet(player, min_bet, max_bet, **kwargs): """ Always bet the max """ return max_bet def decline_insurance(**kwargs): """ Function for always declining insurance. This can be used as the insurance_func argument in an insuance of the Player class. """ return False def accept_insurance(**kwargs): """ Function for always accepting insurance. This can be used as the insurance_func argument in an insuance of the Player class. """ return True def random_choice(**kwargs): """ Randomly pick a move """ return random.choice(["HIT", "STAND"])
def checkIfItsPrime(number): denominator = 1 max_number_of_nice_numbers = 2 current_number_of_nice_numbers = 0 number_given_was_prime = False while denominator <= number: remainder = number % denominator if remainder == 0: current_number_of_nice_numbers += 1 if current_number_of_nice_numbers > max_number_of_nice_numbers: number_given_was_prime = False break elif current_number_of_nice_numbers <= max_number_of_nice_numbers: number_given_was_prime = True denominator = denominator + 1 print("Done with loop") if number_given_was_prime == True: print("The number you gave was prime") elif number_given_was_prime == False: print("The number given was NOT prime") while True: User_Answer = input("Do you want a prime number: ") if User_Answer == "no": print("You said no. I will now exit") break elif User_Answer == "yes": print("You said yes") number = int(input("Give me a number and I'll check if its prime: ")) checkIfItsPrime(number) else: print("Say yes or no")
import math import re def check (): ans = input () if ans == "y": main () elif ans != "n": print ("Напишіть y якщо хочете продовжити роботу чи n якщо потрібно завершити роботу") check() def read (): while True: a = input () if bool (re.match(r'(?:[0]\.\d+)|(?:[1-9](?:\d+)?(?:\.\d+)?)\Z', a)): if ((float(a)>0) & (float(a)<180)): return float(a) print ("Введіть число від 0 до 180") def main (): print ("Введіть перший і другий кут трикутника") a = read () b = read () g = 180 - a - b if (a!=0) & (b!=0) & (g > 0): if (a==90) | (b==90) | (g==90): print ("Трикутник існує і є прямокутним") else: print ("Трикутник існує, але не є прямокутним") else: print ("Трикутник не існує") print ("Продовжити? (y/n)") check () print ("Беспалов Антон Дмитрович \nЛабораторна робота №1 \nВаріант 3 \nПеревірка на існування трикутника") main()
import math import re def check (): ans = input () if ans == "y": main () elif ans != "n": print ("Напишіть y якщо хочете продовжити роботу чи n якщо потрібно завершити роботу") check() def read (): a = input () while not bool(re.match(r'(?:[0]\.\d+)|(?:[1-9](?:\d+)?(?:\.\d+)?)\Z', a)): print ("Введіть число") a = input () return float(a) def main (): print ("Введіть перший і другий катет трикутника") a = read () b = read () hyp = math.sqrt(a*a + b*b) per = a + b + hyp area = a * b / 2 print ("Гіпотенуза трикутника дорінює %.10f" % hyp) print ("Периметр трикутника дорівнює %.10f" % per) print ("Площа трикутника дорівнює %.10f" % area) print ("Продовжити? (y/n)") check () print ("Беспалов Антон Дмитрович \nЛабораторна робота №1 \nВаріант 3 \nЗнахождення гіпотенузи, периметра та площі трикутника") main()
""" Our new calculator is censored and as such it does not accept certain words. You should try to trick by writing a program to calculate the sum of numbers. Given a list of numbers, you should find the sum of these numbers. Your solution should not contain any of the banned words, even as a part of another word. The list of banned words are as follows: sum import for while reduce Input: A list of numbers. Output: The sum of numbers. Precondition: The small amount of data. Let's creativity win! """ def recursive(data, i_cant_be_named_s_u_m): if not data: return i_cant_be_named_s_u_m else: i_cant_be_named_s_u_m += data.pop() return recursive(data, i_cant_be_named_s_u_m) def checkio(data): return recursive(data,0) if __name__ == '__main__': assert checkio([43,-10,68,84,91,71,-10,-80,38]) == 295 assert checkio([42]) == 42 assert checkio([96,26,54,21,4]) == 201 assert checkio([1,37,-64,57,-78,57,64,-38,-91,61,53,-89,41]) == 11 assert checkio([42,-24,-74,96,-62,5,-47]) == -64
""" The Hamming distance between two binary integers is the number of bit positions that differs (read more about the Hamming distance on Wikipedia). For example: 117 = 0 1 1 1 0 1 0 1 17 = 0 0 0 1 0 0 0 1 H = 0+1+1+0+0+1+0+0 = 3 You are given two positive numbers (N, M) in decimal form. You should calculate the Hamming distance between these two numbers in binary form. Input: Two arguments as integers. Output: The Hamming distance as an integer. Precondition: 0 < n < 106 0 < m < 106 """ def checkio(n, m): x,y = format(n,'#022b'),format(m,'#022b') count = 0 for i in range(len(x)): if x[i] != y[i]: count += 1 return count if __name__ == '__main__': #These "asserts" using only for self-checking and not necessary for auto-testing assert checkio(117, 17) == 3, "First example" assert checkio(1, 2) == 2, "Second example" assert checkio(16, 15) == 5, "Third example"
multipler = range(1, 101) for x in multipler: f = open("demofile2.txt", "a") f.write(" \n Table for " + str(x) ) print(" \n Table for " + str(x) ) for y in range(1,13): result = x*y f.write("\n" + str(x) + "X" + str(y) + "=" + str(result) ) print(str(x) + "X" + str(y) + "=" + str(result))
def grader(score, subject): counts = len(score) initial = 0 print('\n') print(subject) while initial < counts: print(score[initial]["name"]) if score[initial]['score'] >= 50 and score[initial]['score'] <= 60: print(" You barly escaped " + " " + str(score[initial]['score'])) elif score[initial]['score'] >= 60 and score[initial]['score'] <= 70 : print("congrats you passed with a C" + " " + str(score[initial]['score'])) elif score[initial]['score'] >= 70 and score[initial]['score'] <= 80 : print("congrats you passed with a B" + " " + str(score[initial]['score'])) elif score[initial]['score'] >= 80 and score[initial]['score'] <= 100: print("congrats you passed with a A" + " " + str(score[initial]['score']) ) else: print("You failed try harder next term" + str(score[initial]['score'])) initial += 1 # grader(score, subject) name = "solomon" def animal(name): print(name)
class Solution: # @return a string def convertToTitle(self, num): out = [] while num > 0: print num temp = num % 26 num = num // 26 if temp == 0: out.append('Z') num = num-1 else: out.append(chr(65+temp+-1)) return ''.join(out[::-1])
# Definition for a binary tree node # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: # @param root, a tree node # @return an integer def get_paths_num(self, root, path_numbers, num): if root.left is None and root.right is None: path_numbers.append(num + root.val) if root.left is not None: self.get_paths_num(root.left, path_numbers, (root.val+num)*10) if root.right is not None: self.get_paths_num(root.right, path_numbers, (root.val+num)*10) def sumNumbers(self, root): path_numbers = [] if root is None: return 0 else: self.get_paths_num(root, path_numbers, 0) result = 0 for number in path_numbers: result += number return result
# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: # @param two ListNodes # @return the intersected ListNode def getLength(self, head): current = head length = 0 while current != None: current = current.next length +=1 return length def getIntersectionNode(self, headA, headB): lenA = self.getLength(headA) lenB = self.getLength(headB) if lenA > lenB: lenA, lenB = lenB, lenA headA, headB = headB, headA if lenA == 0 or lenB == 0: return None currentA = headA currentB = headB for i in xrange(lenB - lenA): currentB = currentB.next while currentA != None and id(currentA) != id(currentB): currentA = currentA.next currentB = currentB.next return currentA
#http://rosalind.info/problems/hamm/ #two given DNA strings rosalind = open('rosalind_hamm.txt') string = {} string[0] = rosalind.readline()[:-1] string[1] = rosalind.readline() hamming_distance = 0 for n in range(len(string[0])): if string[0][n] == string[1][n]: pass else: hamming_distance += 1 print hamming_distance
# -*- coding: utf-8 -*- """ Command line argument format is python simProject.py <printer format> <number of trials> Dependencies: NumPy and SciPy Notes: With regards to floors so the numbers don't get confusing 0 is Cathedral ground floor, 1-38 are floors 1-38 -1 is the basement, -2 is outside the building """ import sys from numpy import random from scipy.stats import skewnorm distance = 0 #Generate floors the 8 printers are on if sys.argv[1] == "default": printers = [0] * 8 elif sys.argv[1] == "uniform": printers = random.uniform(0, 38, 8) printers = [round(x) for x in printers] printers.sort() elif sys.argv[1] == "custom": printers = [1.0, 4.0, 8.0, 9.0, 12.0, 13.0, 16.0, 33.0] #can hardcode other generation schemes if desired later else: printers = [0] * 8 #The floor the student was at before heading to the printer #Generate number of people according to command line arguments fromFloor = random.uniform(-2, 38, int(sys.argv[2])) fromFloor = [round(x) for x in fromFloor] #The floor the student is going to after printing something #change when we figure out skewed normals toFloor = skewnorm.rvs(0.72554004, loc = 2.444444444, scale = 4.747421584, size = int(sys.argv[2])) toFloor = [round(x) for x in toFloor] for i in range(int(sys.argv[2])): #figure out which list comprehension to use for printers between to and from #if there is multiple between them, which printer they go to doesn't matter #and the distance travelled is absolute value of diff diff = toFloor[i] - fromFloor[i] distance += abs(diff) if (diff < 0): printersBetween = [x for x in printers if toFloor[i] <= x <= fromFloor[i]] #double check logic else: printersBetween = [x for x in printers if fromFloor[i] <= x <= toFloor[i]] if (len(printersBetween) == 0): #if no printer between to and from, calculate closest to each and pick smallest distance of the two closestToStart = min(printers, key = lambda x: abs(x - fromFloor[i])) closestToDest = min(printers, key = lambda x: abs(x - toFloor[i])) #Thus distance traveled is diff + 2 * out of way distance to printer if none between if (closestToStart < closestToDest): distance += (2 * abs(closestToStart - fromFloor[i])) else: distance += (2 * abs(closestToDest - toFloor[i])) print(printers) print("Average number of floors traveled: " + str(distance / int(sys.argv[2])))
# Averages three numbers using an array and a loop from cs50 import get_int # Get scores scores = [] for i in range(3): scores.append(get_int("Score: ")) # Print average print(f"Average: {sum(scores) / len(scores)}")
#as still have to use start and end variables, using recursion only saves the need for #two variables. def binarySearch(sortedList, lowerNumber, upperNumber, midpoint): #(1) '''takes a sorted list of integers. Two integers that specify the interval we are searching for. And an integer calculated by the starting index of the list + (the size of the list – the starting index of the list)/2. The function will return a Boolean value.''' #initalises variables used for loop. valueFound = False #(1) endOfList = False #(1) start = 0 #(1) end = len(sortedList) #(1) #while a number in the interval is not found and the list #has not completely been checked while valueFound == False and endOfList == False: #(log(n) #if the midpoint number is in the interval return true if sortedList[midpoint] <= upperNumber and sortedList[midpoint] >= lowerNumber: #(log(n)) valueFound = True #(1) #if the midpoint number is greater than the upper interval number #then interval we're searching for is not in list AFTER the midpoint, #so get rid of that part. elif sortedList[midpoint] > upperNumber: #(log(n)) #checks if the start and end have met or gone past eachother. #if it has then end the loop as we would have already checked whether #it is a value in the interval. if start == end or start>end or end<start: #(log(n)) endOfList = True #(1) #calculates new end of searchable list and new midpoint. end = midpoint-1 #(log(n)) midpoint = int(start + (end-start)/2) #(log(n)) else: #(log(n)) if start ==end or start>end or end<start: #(log(n)) endOfList = True #(1) #calculates new beginning of searchable list and new midpoint. start = midpoint + 1 #(log(n)) midpoint = int(start + (end-start)/2) #(log(n)) #returns whether a value in the interval was found or not. return valueFound #(1) inputTest = False #(1) while inputTest == False: #(n) try: #(n) count = int(input("How many numbers are in your sorted list?")) #(n) if count < 1: #(n) raise ValueError #(n) inputTest = True #(n) except: #(n) print("please enter a postive integer") #(n) i = 0 #(1) sortedList = [] #(1) while i <= count-1: #(n) try: #(n) number = int(input("enter number")) #(n) if i == 0: #(n) sortedList.append(number) #(n) i = i + 1 #(n) elif number < sortedList[len(sortedList)-1]: #(n) raise ValueError #(n) else: #(n) sortedList.append(number) #(n) i = i+1 #(n) except ValueError: #(n) print("Please make sure your list is sorted") #(n) inputTest = False #(1) while inputTest == False: #(n) try: #(n) lowerNumber = int(input("please enter lower number in interval")) #(n) upperNumber = int(input("please enter upper number in interval")) #(n) if lowerNumber > sortedList[len(sortedList)-1] or upperNumber < sortedList[0]: #(n) print(False) #(1) inputTest = True #(1) else: #(n) if lowerNumber <= upperNumber: #(n) inputTest = True #(1) midpoint = int(0 + (len(sortedList)+0)/2) #(1) print(binarySearch(sortedList, lowerNumber, upperNumber, midpoint)) #(1) except ValueError: #(n) print("Please make sure you're entering only integers") #(n) #Runtime of algorithm excluding input validation: 10log(n)+11 #As the length of the list getting searched is shortened by moving to the midpoint, #and then eliminating the list that is either above it or below it. #The while loop thus is not run n times as it is not searched sequentially. #Thus it is instead log(n) due to it being a divide and conquer algorithm #Big O excluding input validation: O(log(n))
def division(fiveCount, number): '''This function calculates the amount of trailing 0s in the factorial of the number that is inputted. The first argument should be an integer and the second should be a float. ''' #checks for base case. if number >= 0 and number < 1: return fiveCount else: #calculates the float number of trailing 0s hold = fiveCount + number/5 #turns it into an integer to round down. fiveCount = int(hold) #calls the function again to keep it going till the base case hits. return division(fiveCount, number/5) inputTest = False while inputTest == False: try: inputNumber = input("Please enter a number") #turns it into a float so that when it is divided it can then be rounded down. floatHolder = float(inputNumber) if floatHolder<0: raise ValueError inputTest = True except ValueError: print("Please only input numbers larger than or equal to 0 into the system") #initalises the number of trailing 0s. count = 0 print(division(count, floatHolder))
from queue import Queue from threading import Thread import time _sentinel = object() # A thread that produces data def producer(out_q): n = 10 while n > 0: # Produce some data out_q.put(n) time.sleep(2) n -= 1 # Put the sentinel on the queue to indicate completion out_q.put(_sentinel) # A thread that consumes data def consumer(in_q): while True: # Get some data data = in_q.get() # Check for termination if data is _sentinel: in_q.put(_sentinel) break # Process the data print('Got:', data) print('Consumer shutting down') # 如果生产者线程需要立即知道消费线程是否处理数据了,此时应该将发送数据包装成一个Event对象 from threading import Event def producer_event(out_q): n = 10 while n > 0: # produce some data data = n # make an (data,event) pair and hand it to the consumer evt = Event() out_q.put((data, evt)) time.sleep(2) # wait for the consumer to process evt.wait() n -= 1 print("consumed!") def consumer_event(in_q): while True: # Get some data data, evt = in_q.get() # Check for termination if data is _sentinel: in_q.put(_sentinel) break # Process the data print('Got:', data) evt.set() print('Consumer shutting down') if __name__ == '__main__': q = Queue() # already have all of the required locking t1 = Thread(target=consumer_event, args=(q,)) t2 = Thread(target=producer_event, args=(q,)) t1.start() t2.start() t1.join() t2.join()
numbers = {n: i + 1 for (i, n) in enumerate(list(map(int, input().split(","))))} current = list(numbers.keys())[-1] for index in range(len(numbers), 30000000): previous = current current = index - numbers.get(current) if current in numbers else 0 numbers[previous] = index print(current) """ Advent of Code 2020, day 15 You catch the airport shuttle and try to book a new flight to your vacation island. Due to the storm, all direct flights have been cancelled, but a route is available to get around the storm. You take it. While you wait for your flight, you decide to check in with the Elves back at the North Pole. They're playing a memory game and are ever so excited to explain the rules! In this game, the players take turns saying numbers. They begin by taking turns reading from a list of starting numbers (your puzzle input). Then, each turn consists of considering the most recently spoken number: If that was the first time the number has been spoken, the current player says 0. Otherwise, the number had been spoken before; the current player announces how many turns apart the number is from when it was previously spoken. So, after the starting numbers, each turn results in that player speaking aloud either 0 (if the last number is new) or an age (if the last number is a repeat). For example, suppose the starting numbers are 0,3,6: Turn 1: The 1st number spoken is a starting number, 0. Turn 2: The 2nd number spoken is a starting number, 3. Turn 3: The 3rd number spoken is a starting number, 6. Turn 4: Now, consider the last number spoken, 6. Since that was the first time the number had been spoken, the 4th number spoken is 0. Turn 5: Next, again consider the last number spoken, 0. Since it had been spoken before, the next number to speak is the difference between the turn number when it was last spoken (the previous turn, 4) and the turn number of the time it was most recently spoken before then (turn 1). Thus, the 5th number spoken is 4 - 1, 3. Turn 6: The last number spoken, 3 had also been spoken before, most recently on turns 5 and 2. So, the 6th number spoken is 5 - 2, 3. Turn 7: Since 3 was just spoken twice in a row, and the last two turns are 1 turn apart, the 7th number spoken is 1. Turn 8: Since 1 is new, the 8th number spoken is 0. Turn 9: 0 was last spoken on turns 8 and 4, so the 9th number spoken is the difference between them, 4. Turn 10: 4 is new, so the 10th number spoken is 0. (The game ends when the Elves get sick of playing or dinner is ready, whichever comes first.) Their question is: what will be the 2020th number spoken? In the example above, the 2020th number spoken will be 436. Here are a few more examples: Given the starting numbers 1,3,2, the 2020th number spoken is 1. Given the starting numbers 2,1,3, the 2020th number spoken is 10. Given the starting numbers 1,2,3, the 2020th number spoken is 27. Given the starting numbers 2,3,1, the 2020th number spoken is 78. Given the starting numbers 3,2,1, the 2020th number spoken is 438. Given the starting numbers 3,1,2, the 2020th number spoken is 1836. Given your starting numbers, what will be the 2020th number spoken? Your puzzle answer was 289. --- Part Two --- Impressed, the Elves issue you a challenge: determine the 30000000th number spoken. For example, given the same starting numbers as above: Given 0,3,6, the 30000000th number spoken is 175594. Given 1,3,2, the 30000000th number spoken is 2578. Given 2,1,3, the 30000000th number spoken is 3544142. Given 1,2,3, the 30000000th number spoken is 261214. Given 2,3,1, the 30000000th number spoken is 6895259. Given 3,2,1, the 30000000th number spoken is 18. Given 3,1,2, the 30000000th number spoken is 362. Given your starting numbers, what will be the 30000000th number spoken? Your puzzle answer was 1505722. Input: 0,8,15,2,12,1,4 """
print ("How old are you ?"), age = input() print ("How tall are you?"), height = input() print ("How much do you weigh?"), weight = input() #print ("So you are %r of age with %r of height and %r of weight awesome" % (age, height, weight)) #print("So you are {0} of age {1} of height and {2} and of weight Awesome!!!".format(age, height, weight)) print (f"So you are {age} with {height} tall and weighing {weight} Awesome!!!!")
from sys import argv script, first, second, third = argv print ("The script is called:", script) print ("The first argument you have passed is", first) print ("The second argument you have passed is", second) print ("Third argument you have passed is", third) ''' import sys print ("number of arguments", len(sys.argv)) print ("arguments list you have passed", str(sys.argv)) age = (sys.argv[1]) height = str(sys.argv[2]) weight = (sys.argv[3]) print(f"You are age is {age} and height is {height} feet with weight {weight} kgs") ''' ''' # It is used to print tables for the number given import sys num = int(sys.argv[1]) for i in range(1,11): print(num,'x',i,'=',num*i) ''' ''' # Prints Table for the given number and squareroot of number import sys, math num = int(sys.argv[1]) for i in range(1,11): print(num,'x',i,'=',num*i) sr = int(sys.argv[2]) print(f'The squareroot of given number {sr} is', math.sqrt())
print("HelloWorld") print("Hi,Nice to see you") print("I like typing this.") print('!Yay, I would say') print('i would "say" hi') print('I would say "NO......."') print(1,2,3,4,sep=' LED ') print ('The number enter here will be in new line',1,2,3,4, sep='\n') #my_name = 'Zed A. Shaw' #print ("Let's %s talk about us." % my_name) print (1,2,3,4,5,sep='Hello ')
year=int(input("enter the year")) i=0 while i<1: if year%4==0 or year%100==0 or year%400==0: print(year,"is a leap year") else: print(year,"is not a leap year") i+=1
i=1 a=1 while i<=3: j=1 while j<=3: print(a,end=" ") a=a+1 j=j+1 print() i=i+1
i=1 while i<=100: if i%2==0: print(-i) else: print(i) i=i+1 # i=891 # while i<931: # z=i-890 # if z%3==0: # print(z) # i=i+1
i=1 sum=0 while i<=10: user=int(input("entr the number")) sum=sum+user i=i+1 print(sum)
# # Copyright 2020-21 by # # University of Alaska Anchorage, College of Engineering. # # All rights reserved. # # Contributors: ................ and # Christoph Lauter # # # class DFA: """Deterministic Finite Automaton Either positional arguments or keyword arguments are supported, but not a mix of both. Positional arguments: DFA(regex) : get the DFA corresponding to the regex, which must be a non-empty string DFA(M) : get a copy of the DFA M, renumbering the states as integers DFA(regex, Sigma) : get the DFA corresponding to the regex, over the alphabet Sigma, which is a set of 1-character strings. The regex is a string, which may be empty (yields DFA for empty word) DFA(M, Sigma) : get a copy of the DFA M, possibly extending the alphabet to Sigma DFA(type, Q, Sigma, delta, q, F) : get the DFA corresponding to the finite automaton M = (Q, Sigma, delta, q, F) type is a string, either "DFA" or "NFA" If type is "DFA", M is considered a deterministic finite automaton, i.e. delta(q, a) returns a single state and no epsilon-transitions are supported. If type is "NFA", M is considered a non-deterministic finite automaton, i.e. delta(q, a) returns a set of states and epsilon-transitions are supported. Q is a set or frozenset of states (of any hashable Python type) Sigma is a set of 1-character strings delta is either a function taking a state and a 1-character string in argument (positional arguments in this order) and returning either a state or a frozenset of states (see above) or a dictionary mapping pairs (q,a) of a state q and a 1-character string a to a state or to a frozenset of states (see above). delta must be defined on all possible combinations of states and symbols in the alphabet, i.e. the automaton must have a transition with every symbol in the alphabet for every state, possibly to a capture state. In the case when the type is "NFA", delta additionally accept the empty string '' instead of a character, which describes an epsilon-transition from the correspondent state to a (frozen) set of other states. Epsilon-transitions may be defined for some states and not for others. q is the start state, which must be in the set of states F is a frozenset, subset of the set of states, indicating the final (accepting) states Keyword arguments: DFA(regex = r) is equivalent to DFA(r) DFA(regex = r, Sigma = S) is equivalent to DFA(r, S) DFA(DFA = M) is equivalent to DFA(M) DFA(DFA = M, Sigma = S) is equivalent to DFA(M, S) DFA(type = t, Q = Q, Sigma = S, delta = d, q = q, F = F) is equivalent to DFA(t, Q, S, d, q, F) """ def __init__(self, *args, **kwargs): if (len(args) != 0) and (len(kwargs) != 0): raise Exception("Combinations of positional and keyword arguments not allowed") if len(kwargs) > 0: if "regex" in kwargs: if not isinstance(kwargs["regex"], str): raise Exception("Wrong type for keyword argument") if "Sigma" in kwargs: if len(kwargs) > 2: raise Exception("Too many keyword arguments") M = DFA(kwargs["regex"], kwargs["Sigma"]) else: if len(kwargs) > 1: raise Exception("Too many keyword arguments") M = DFA(kwargs["regex"]) elif "DFA" in kwargs: if not isinstance(kwargs["DFA"], DFA): raise Exception("Wrong type for keyword argument") if "Sigma" in kwargs: if len(kwargs) > 2: raise Exception("Too many keyword arguments") M = DFA(kwargs["DFA"], kwargs["Sigma"]) else: if len(kwargs) > 1: raise Exception("Too many keyword arguments") M = DFA(kwargs["DFA"]) elif ("type" in kwargs) and ("Q" in kwargs) and ("Sigma" in kwargs) and ("delta" in kwargs) and ("q" in kwargs) and ("F" in kwargs): if len(kwargs) > 6: raise Exception("Too many keyword arguments") M = DFA(kwargs["type"], kwargs["Q"], kwargs["Sigma"], kwargs["delta"], kwargs["q"], kwargs["F"]) else: raise Exception("Unsupported keyword arguments") self.__states = frozenset(M.__states) self.__alphabet = frozenset(M.__alphabet) self.__delta = M.__delta self.__start = M.__start self.__final = frozenset(M.__final) self.__check_consistance() else: if len(args) == 1: if isinstance(args[0], str): if len(args[0]) > 0: Sigma = { a for a in args[0] if not a in { '(', ')', '|', '*' } } M = DFA(args[0], Sigma) self.__states = frozenset(M.__states) self.__alphabet = frozenset(M.__alphabet) self.__delta = M.__delta self.__start = M.__start self.__final = frozenset(M.__final) self.__check_consistance() else: raise Exception("Empty regular expressions supported only when alphabet is given") elif isinstance(args[0], DFA): M = args[0] i = 0 Q = set() mapping = dict() for q in M.__states: Q.add(i) mapping[q] = i i = i + 1 Q = frozenset(Q) q0 = mapping[M.__start] F = set() for q in M.__final: F.add(mapping[q]) F = frozenset(F) delta = dict() for q in M.__states: for a in M.__alphabet: delta[(mapping[q],a)] = mapping[M.__delta[(q,a)]] self.__states = Q self.__alphabet = frozenset(M.__alphabet) self.__delta = delta self.__start = q0 self.__final = F self.__check_consistance() else: raise Exception("Unimplemented case: argument must be a string or another DFA") elif (len(args) == 2): if isinstance(args[0], str): if len(args[0]) == 0: self.__states = frozenset({ 1, 2 }) self.__alphabet = self.__check_alphabet(frozenset(args[1])) self.__delta = dict() for a in self.__alphabet: self.__delta[(1, a)] = 2 self.__delta[(2, a)] = 2 self.__start = 1 self.__final = frozenset({ 1 }) self.__check_consistance() elif len(args[0]) == 1: if not(args[0][0] in frozenset(args[1])): raise Exception("Character in regular expression not in alphabet") if args[0][0] in { '(', '|', ')', '*' }: raise Exception("Malformed regular expression") self.__states = frozenset({ 1, 2, 3 }) self.__alphabet = self.__check_alphabet(frozenset(args[1])) self.__delta = dict() self.__delta[(1, args[0][0])] = 2 for a in self.__alphabet: if not a == args[0][0]: self.__delta[(1, a)] = 3 self.__delta[(2, a)] = 3 self.__delta[(3, a)] = 3 self.__start = 1 self.__final = frozenset({ 2 }) self.__check_consistance() else: M = self.__regular_expression_to_dfa(args[0], self.__check_alphabet(frozenset(args[1]))) self.__states = frozenset(M.__states) self.__alphabet = frozenset(M.__alphabet) self.__delta = M.__delta self.__start = M.__start self.__final = frozenset(M.__final) self.__check_consistance() elif isinstance(args[0], DFA): M = args[0].__extend_alphabet(self.__check_alphabet(args[1])) self.__states = frozenset(M.__states) self.__alphabet = frozenset(M.__alphabet) self.__delta = M.__delta self.__start = M.__start self.__final = frozenset(M.__final) self.__check_consistance() else: raise Exception("Unimplemented case: argument not a string nor another DFA") elif len(args) == 6: if args[0] == "DFA": self.__states = frozenset(args[1]) self.__alphabet = self.__check_alphabet(frozenset(args[2])) if isinstance(args[3], dict): self.__delta = args[3] else: self.__delta = dict() for q in self.__states: for a in self.__alphabet: self.__delta[(q,a)] = args[3](q, a) self.__start = args[4] self.__final = frozenset(args[5]) self.__check_consistance() elif args[0] == "NFA": if isinstance(args[3], dict): NFA_D = args[3] else: NFA_D = dict() for q in args[1]: for a in args[2]: NFA_D[(q,a)] = args[3](q, a) if (not args[3](q, '') == None) and (not frozenset(args[3](q, '')) == frozenset()): NFA_D[(q,'')] = args[3](q, '') NFA_Q = args[1] NFA_start = args[4] NFA_Sigma = self.__check_alphabet(frozenset(args[2])) NFA_delta, NFA_F = self.__remove_epsilon(NFA_Q, NFA_Sigma, NFA_D, args[5]) if self.__nfa_delta_without_epsilon_is_deterministic(NFA_delta, NFA_Q, NFA_Sigma): self.__states = NFA_Q self.__alphabet = NFA_Sigma self.__start = NFA_start self.__delta = { (q,a) : next(iter(NFA_delta[(q,a)])) for q in NFA_Q for a in NFA_Sigma } self.__final = NFA_F self.__check_consistance() else: self.__alphabet = NFA_Sigma self.__start = frozenset({NFA_start}) delta = dict() T = dict() stable = False while not stable: stable = True for tt in T: T[tt] = 0 T[self.__start] = 1 for a in self.__alphabet: H = { tt for tt in T } while len(H) > 0: tt = H.pop() s = set() for q in tt: for r in NFA_delta[(q, a)]: s.add(r) fs = frozenset(s) delta[(tt,a)] = fs if fs in T: T[fs] = T[fs] + 1 else: T[fs] = 1 H.add(fs) stable = False Q = { q for q in T if T[q] > 0 } F = { q for q in Q if len(q.intersection(NFA_F)) != 0 } self.__states = frozenset(Q) self.__delta = delta self.__final = frozenset(F) self.__check_consistance() else: raise Exception("Unimplemented case: first argument must be 'DFA' or 'NFA'") else: raise Exception("Unimplemented case: too many or too few arguments") def __check_consistance(self): """Internal method: checks whether the automaton is consistant""" if not (self.__start in self.__states): raise Exception("Start state not in set of states") for q in self.__final: if not (q in self.__states): raise Exception("Final states not subset of set of states") for a in self.__alphabet: if not isinstance(a, str): raise Exception("Alphabet must be formed of 1-character strings") if len(a) != 1: raise Exception("Alphabet must be formed of 1-character strings") if a[0] in { '(', ')', '|', '*' }: raise Exception("Alphabet cannot include characters '(', ')', '|' or '*'") for q in self.__states: for a in self.__alphabet: if not ((q,a) in self.__delta): raise Exception("Transition function must be complete, i.e. defined for all pairs (q,a)") def __check_alphabet(self, Sigma): """Internal method: check that all elements of the alphabet are 1-character strings""" for a in Sigma: if not isinstance(a, str): raise Exception("Alphabet must be formed of 1-character strings") if len(a) != 1: raise Exception("Alphabet must be formed of 1-character strings") if a[0] in { '(', ')', '|', '*' }: raise Exception("Alphabet cannot include characters '(', ')', '|' or '*'") return Sigma def __nfa_delta_without_epsilon_is_deterministic(self, delta, Q, Sigma): """Internal method: checks if a NFA without epsilon-transitions happens to be deterministic """ for q in Q: for a in Sigma: if len(delta[(q,a)]) != 1: return False return True def __remove_epsilon(self, Q, Sigma, delta, F): """Internal method: removes epsilon-transitions on delta for an automaton (Q, Sigma, delta, <some start>, F) """ for q in Q: if (q, '') in delta: if not frozenset(delta[(q, '')]) == frozenset(): from_state = q to_state = next(iter(delta[(q, '')])) other_to_states = frozenset({ q for q in delta[(q, '')] if not q == to_state }) deltaprime = dict() for q in Q: if q == from_state: if from_state == to_state: if not other_to_states == frozenset(): deltaprime[(q, '')] = other_to_states for a in Sigma: deltaprime[(q, a)] = delta[(q, a)] else: if not other_to_states == frozenset(): if (to_state, '') in delta: T = other_to_states.union(delta[(to_state, '')]) deltaprime[(q, '')] = frozenset({ q for q in T if not q == to_state }) else: deltaprime[(q, '')] = other_to_states else: if (to_state, '') in delta: T = delta[(to_state, '')] deltaprime[(q, '')] = frozenset({ q for q in T if not q == to_state }) for a in Sigma: deltaprime[(q, a)] = delta[(q, a)].union(delta[(to_state, a)]) else: if (q, '') in delta: deltaprime[(q, '')] = delta[(q, '')] for a in Sigma: deltaprime[(q, a)] = delta[(q, a)] if (not from_state in F) and (to_state in F): T = { q for q in F } T.add(from_state) Fprime = frozenset(T) else: Fprime = F return self.__remove_epsilon(Q, Sigma, deltaprime, Fprime) return (delta, F) def __regular_expression_to_dfa(self, expr, Sigma): """Internal method: parses the regex string expr (which must be over the alphabet Sigma) and creates the corresponding DFA """ def regular_expression_to_dfa_helper(expr, Sigma, l, r): """Internal helper method for the parser: does the work""" def find_first_matching_close_parenthesis(expr, l, r): """Internal helper method for the parser: finds matching close parenthesis""" if (r <= l): return -1 if (expr[l] != '('): return -1 lev = 0 for i in range(l,r): if expr[i] == '(': lev = lev + 1 elif expr[i] == ')': lev = lev - 1 if lev == 0: return i return -1 def expr_is_trivial_concatenation(expr, l, r): """Internal helper method for the parser: checks if regexp string expr happens to be a trivial concatenation of letters """ for i in range(l,r): if expr[i] in { '(', ')', '|', '*' }: return False return True # Parser code starts here if r < l: raise Exception("Malformed expression") elif l == r: return DFA('', Sigma) elif l == r-1: if expr[l] in { '(', ')', '|', '*' }: raise Exception("Malformed expression") return DFA(expr[l], Sigma) else: if expr_is_trivial_concatenation(expr, l, r): subexpr = expr[l:r] Q = frozenset({ i for i in range(0,len(subexpr) + 2) }) final = len(subexpr) catch = final + 1 q0 = 0 F = frozenset({ final }) delta = dict() for i in range(0,len(subexpr)): c = subexpr[i] delta[(i,c)] = i+1 for a in Sigma: if not a == c: delta[(i,a)] = catch for a in Sigma: delta[(catch, a)] = catch delta[(final, a)] = catch return DFA("DFA", Q, Sigma, delta, q0, F) if expr[l] == '(': m = find_first_matching_close_parenthesis(expr, l, r) if m < l: raise Exception("Could not find matching close parenthesis") if m == r-1: return regular_expression_to_dfa_helper(expr, Sigma, l+1, r-1) else: if expr[m+1] == '|': left = regular_expression_to_dfa_helper(expr, Sigma, l, m+1) right = regular_expression_to_dfa_helper(expr, Sigma, m+2, r) return left.union(right) elif expr[m+1] == '*': i = m+1 while (i < r) and (expr[i] == '*'): i = i + 1 if i == r: left = regular_expression_to_dfa_helper(expr, Sigma, l, r-1) return left.star() else: if expr[i] == '|': left = regular_expression_to_dfa_helper(expr, Sigma, l, i) right = regular_expression_to_dfa_helper(expr, Sigma, i+1, r) return left.union(right) else: left = regular_expression_to_dfa_helper(expr, Sigma, l, i) right = regular_expression_to_dfa_helper(expr, Sigma, i, r) return left.concat(right) else: left = regular_expression_to_dfa_helper(expr, Sigma, l, m+1) right = regular_expression_to_dfa_helper(expr, Sigma, m+1, r) return left.concat(right) else: if expr[l] in { '|', '*' }: raise Exception("Malformed expression") if expr[l+1] == '|': left = regular_expression_to_dfa_helper(expr, Sigma, l, l+1) right = regular_expression_to_dfa_helper(expr, Sigma, l+2, r) return left.union(right) elif expr[l+1] == '*': i = l+1 while (i < r) and (expr[i] == '*'): i = i + 1 if i == r: left = regular_expression_to_dfa_helper(expr, Sigma, l, r-1) return left.star() else: if expr[i] == '|': left = regular_expression_to_dfa_helper(expr, Sigma, l, i) right = regular_expression_to_dfa_helper(expr, Sigma, i+1, r) return left.union(right) else: left = regular_expression_to_dfa_helper(expr, Sigma, l, i) right = regular_expression_to_dfa_helper(expr, Sigma, i, r) return left.concat(right) else: i = l+1 while (i < r) and (not(expr[i] in { '|', '(' })): i = i + 1 if i == r: j = r-1 while (j > l) and (expr[j] == '*'): j = j - 1 left = regular_expression_to_dfa_helper(expr, Sigma, l, j) right = regular_expression_to_dfa_helper(expr, Sigma, j, r) return left.concat(right) else: if expr[i] == '|': left = regular_expression_to_dfa_helper(expr, Sigma, l, i) right = regular_expression_to_dfa_helper(expr, Sigma, i+1, r) return left.union(right) else: left = regular_expression_to_dfa_helper(expr, Sigma, l, i) right = regular_expression_to_dfa_helper(expr, Sigma, i, r) return left.concat(right) return DFA(regular_expression_to_dfa_helper(expr, Sigma, 0, len(expr))) def __extend_alphabet(self, Sigma): """Internal method: returns a DFA equivalent of self with the extended alphabet Sigma""" NSigma = frozenset(frozenset(Sigma).union(frozenset(self.__alphabet))) AddedSigma = frozenset({ a for a in NSigma if not a in self.__alphabet }) if AddedSigma == frozenset(): return self Q = { (1,q) for q in self.__states } Q.add((2,0)) Q = frozenset(Q) F = { (1,q) for q in self.__final } q0 = (1,self.__start) delta = dict() for q in self.__states: for a in self.__alphabet: delta[((1,q),a)] = (1,self.__delta[(q,a)]) for a in AddedSigma: delta[((1,q),a)] = (2,0) for a in NSigma: delta[((2,0),a)] = (2,0) return DFA("DFA", Q, NSigma, delta, q0, F) def get_Q(self): """Returns a set of objects, representing the states of the DFA""" return { q for q in self.__states } def get_Sigma(self): """Returns a set of 1-character strings, representing the alphabet of the DFA""" return { a for a in self.__alphabet } def get_delta_as_dictionary(self): """Returns a dictionnary, representing the transition function of the DFA. The dictionnary maps a pair (q,a) of a state and a symbol in the alphabet to the next state. """ return self.__delta def get_q(self): """Returns an object, representing the start state of the DFA""" return self.__start def get_F(self): """Returns a set of objects, representing the final states of the DFA""" return { q for q in self.__final } def get_delta(self): """Returns the transition function of the DFA. The returned function takes a state q and a symbol in the alphabet in argument (as positional arguments in this order) and returns the state the automaton transitions into. """ d = dict(self.__delta) S = frozenset(self.__alphabet) Q = frozenset(self.__states) def aux(q, a, d, S, Q): """Internal auxilliary function""" if not isinstance(a, str): raise Exception("Given symbol must be 1-character string") if len(a) != 1: raise Exception("Given symbol must be 1-character string") if not (a in S): raise Exception("Given symbol must be in alphabet") if not (q in Q): raise Exception("Given state must be state of automaton") if not ((q, a) in d): raise Exception("Given symbol must be in alphabet") return d[(q,a)] return (lambda q, a: aux(q, a, d, S, Q)) def get_extended_delta(self): """Returns the extended transition function of the DFA. The returned function takes a state q and a string formed by symbols in the alphabet in argument (as positional arguments in this order) and returns the state the automaton transitions into. The string may be empty, in which case the state in argument is returned. """ d = self.get_delta() Q = frozenset(self.__states) def aux(q, w, delta, Q): """Internal auxilliary function""" if not isinstance(w, str): raise Exception("Given word must be a string") if w == "": if not (q in Q): raise Exception("Given state must be state of automaton") return q else: a = w[0] v = w[1:] return aux(delta(q, a), v, delta, Q) return (lambda q, w: aux(q, w, d, Q)) def recognize(self, w): """Given a string, returns a boolean indicating whether or not the DFA accepts the string.""" if not isinstance(w, str): raise Exception("Given word must be a string") q = self.__start for a in w: if not a in self.__alphabet: return False q = self.__delta[(q, a)] return q in self.__final def __convert_to_nfa(self): """Internal method: converts the DFA to a 5-tuple representing a non-deterministic finite automaton""" Q = frozenset({ frozenset({ q }) for q in self.__states }) Sigma = self.__alphabet delta = { (frozenset({ q }), a) : frozenset({ frozenset({ self.__delta[(q,a)] }) }) for q in self.__states for a in self.__alphabet } q0 = frozenset({ self.__start }) F = frozenset({ frozenset({ q }) for q in self.__final }) return (Q, Sigma, delta, q0, F) def complement(self): #students """Returns the DFA for the complement language of the language accepted by the DFA""" raise Exception("Unimplemented. Job to be done by UAA students.") def union(self, other): #students """Returns the DFA for the union language of the languages accepted by the DFA and the DFA given in argument""" if not self.__alphabet == other.__alphabet: combinedSigma = frozenset(self.__alphabet.union(other.__alphabet)) M = DFA(self, combinedSigma) N = DFA(other, combinedSigma) return M.union(N) raise Exception("Unimplemented. Job to be done by UAA students.") def intersection(self, other): #students """Returns the DFA for the intersection language of the languages accepted by the DFA and the DFA given in argument.""" raise Exception("Unimplemented. Job to be done by UAA students.") def concat(self, other): """Returns the DFA for the concatenation language of the languages accepted by the DFA and the DFA given in argument""" if not self.__alphabet == other.__alphabet: combinedSigma = frozenset(self.__alphabet.union(other.__alphabet)) M = DFA(self, combinedSigma) N = DFA(other, combinedSigma) return M.concat(N) (QA, SigmaA, deltaA, q0A, FA) = self.__convert_to_nfa() (QB, SigmaB, deltaB, q0B, FB) = other.__convert_to_nfa() Sigma = SigmaA Q = set() for q in QA: Q.add((1,q)) for q in QB: Q.add((2,q)) Q = frozenset(Q) q0 = (1,q0A) F = set() for q in FB: F.add((2,q)) F = frozenset(F) delta = dict() for q in QA: for a in SigmaA: delta[((1,q),a)] = frozenset({ (1,r) for r in deltaA[(q,a)] }) for q in QB: for a in SigmaB: delta[((2,q),a)] = frozenset({ (2,r) for r in deltaB[(q,a)] }) for q in FA: delta[((1,q),'')] = frozenset({ (2,q0B) }) return DFA("NFA", Q, Sigma, delta, q0, F) def star(self): #students """Returns the DFA for the star language of the language accepted by the DFA""" raise Exception("Unimplemented. Job to be done by UAA students.")
class Solution: def lengthOfLIS(self, nums): """ :type nums: List[int] :rtype: int """ if len(nums) == 0: return 0 longest = [1 for _ in range(len(nums))] for index, num in enumerate(nums): for i in range(index): if num > nums[i]: length = longest[i] + 1 if length > longest[index]: longest[index] = length return max(longest) nums = [] solution = Solution() print(solution.lengthOfLIS(nums))
""" 注意求解目标:Player1 能否赢 Player2,并不在意Player1 和 Player2实际得的分数 这样就可以把问题抽象成: 针对给定数列,Player1 比 Player2 最多能多获取多少分 """ class Solution: def PredictTheWinner(self, nums): """ :type nums: List[int] :rtype: bool """ score_diff = [[None for _ in range(0, len(nums))] for _ in range(0, len(nums))] return Solution.recursive(nums, 0, len(nums) - 1, score_diff) >= 0 @staticmethod def recursive(numbers, start, end, score_diff): if not score_diff[start][end]: score_diff[start][end] = max(numbers[start] - Solution.recursive(numbers, start + 1, end, score_diff), numbers[end] - Solution.recursive(numbers, start, end - 1, score_diff)) if start < end else numbers[start] return score_diff[start][end] nums = [1, 15, 3] solution = Solution() print(solution.PredictTheWinner(nums))
"""This is the main file you'll edit. """ try: from game import board_from_heights except ModuleNotFoundError: pass # 4 possible rotations for any piece. ROTATIONS = [0, 1, 2, 3] def make_move(rows, columns, heights, shape_name, x, rotation): """Takes a the tetris board as column heights and applies a particular move. Args: rows (int): Number of rows in this tetris game. columns (int): Number of columns in this tetris game. heights (Tuple[int]): List of column heights in the current board. shape_name (str): Name of the piece shape (like "L" or "O" etc.) x (int): Which column to drop the piece in. rotation (int): Rotation of the piece, either 0, 1, 2, or 3. Returns: Modified heights _after_ the piece at `x` and `rotation` have been dropped. `None` if move is invalid. """ board = board_from_heights(heights, rows, columns) try: board.move(shape_name, x, rotation) except ValueError: return None return tuple(board.skyline()) ### # DO NOT MODIFY ABOVE THIS FILE. ### def solver(rows, columns, shape_sequence, place=0, memo={}): """Solve a given tetris game. Args: rows (int): Number of rows in this game. columns (int): Number of columns in this game. shape_sequence (List[str]): List of shape names to come (This list is of size n). e.g. `shape_sequence = ["L", "O", "I", "L"]` Returns: A list of `(x, rotation)` pairs corresponding to the ideal moves to be made to survive. `None` if there is no possible way to survive. """ parent = {} memo = {} heights = tuple([0 for _ in range(columns)]) # O(nc(r+1)**c) def DP(ix, heights): '''DP that returns True or False''' # ran out of tiles -> shape_seq length if ix >= len(shape_sequence): if any([i > rows for i in heights]): return False return True if (ix, heights) in memo: # we've seen this exact config b4 return memo[(ix, heights)] # current shape shape = shape_sequence[ix] for c in range(columns): for rot in ROTATIONS: new_heights = make_move(rows, columns, heights, shape, c, rot) if not new_heights: # don't bother computing further. Seq is invalid continue try: # have we seen this config before? result_from_b4 = memo[(ix, new_heights)] # yes we have if result_from_b4: parent[(ix, heights)] = (c, rot) memo[(ix, heights)] = True return True except KeyError: # no we haven't indicator = DP(ix+1, new_heights) if indicator: memo[(ix, heights)] = True parent[(ix, heights)] = (c, rot) return True memo[(ix, heights)] = False return False start = DP(0, heights) if not start: return None out = [] now = heights for p in range(len(shape_sequence)): parent_r, parent_c = parent[(p, now)] out.append((parent_r, parent_c)) now = make_move(rows, columns, now, shape_sequence[p], parent_r, parent_c) return out
import random def lotteryfull(): print('Lotto') print('-----') print('Hello', capital, 'your Lotto numbers are:', random.sample(range(1, 60), 6)) print('Euro Millions') print('-------------') print('Your Euro Millions numbers are:', random.sample(range(1, 51), 5), 'your Lucky Stars numbers are:',random.sample(range(1,13),2)) print('Set For Life') print('------------') print('Your Set For Life numbers are:', random.sample(range(1, 48), 5), 'your Life Ball number is:',random.sample(range(1,11),1)) print('Thunderball') print('-----------') print('Your Thunderball numbers are:', random.sample(range(1, 40), 5), 'your Thunderball number is:',random.sample(range(1,15),1)) def lottery(choice): if choice == '1': return 'Hello', capital, 'your Lotto numbers are:', random.sample(range(1, 60), 6) elif choice == '2': return 'Hello', capital,'Your Euro Millions numbers are:', random.sample(range(1, 51), 5), 'your Lucky Stars numbers are:',random.sample(range(1,13),2) elif choice == '3': return 'Hello', capital, 'Your Set For Life numbers are:', random.sample(range(1,48),5), 'your Life Ball number is:',random.sample(range(1,11),1) elif choice == '4': return 'Hello', capital,'Your Thunderball numbers are:', random.sample(range(1,40),5), 'your Thunderball number is:',random.sample(range(1,15),1) elif choice == '5': return lotteryfull() else: return 'Please pick a number between 1 - 5: ' print("\n") title = "Welcome to your national lottery number picker" title1 ="===============================================\n\n" title2 = '1. Lotto' title3 = '2. Euro Millions' title4 = '3. Set for life' title5 = '4. Thunderball' title6 = '5. The Full Monty' print(title.center(148)) print(title1.center(152)) print(title2.center(142)) print(title3.center(150)) print(title4.center(150)) print(title5.center(148)) print(title6.center(152)) print("\n") print("\n") name = input("What is your name: ") pick = input('Please select your choice: ') capital = name.capitalize() result = lottery(pick) print(result)
from flask import Flask, render_template, request # import json to load JSON data to a python dictionary import json # urllib.request to make a request to api import urllib.request app = Flask(__name__) @app.route('/', methods =['POST', 'GET']) def weather(): if request.method == 'POST': city = request.form['city'] else: city = 'delhi' api = "85b8d1653b405711f28d4313b1aa5d50" # source contain json data from api data = urllib.request.urlopen('http://api.openweathermap.org/data/2.5/weather?q=' + city + '&appid=' + api).read() # converting JSON data to a dictionary dict_of_data = json.loads(data) # data for variable dict_of_data individual = { "cityname":city, "country_code": str(dict_of_data['sys']['country']), "coordinate": str(dict_of_data['coord']['lon']) + ' ' + str(dict_of_data['coord']['lat']), "temp": str(dict_of_data['main']['temp']) + ' K', "temp_cel":str("%.3f C" % (float(str(dict_of_data['main']['temp']))-273)), "pressure": str(dict_of_data['main']['pressure']), "humidity": str(dict_of_data['main']['humidity']), } print(individual) return render_template('index.html', data = individual) if __name__ == '__main__': app.run(debug = True)
#reading a file contents from a folder my_file = 'notes.txt' guest_file ='guests.txt' with open(my_file) as nano: contents = nano.read() print('\nDisplaying contents of the file notes.txt:\n' + contents.rstrip()) print("There are " + str(len(contents)) + " characters in the file notes.txt") #Program that navigates through a guest list print('\nProgram that checks the name of the user exists in the file') with open(guest_file) as my_guests: guest_list = my_guests.read() print("This is the guest list:\n" + guest_list) response = input("Do you have more guests to add? Enter Y or N: ") response = response.upper() if response == 'Y': guest_name = input("Enter the guest's name or q to quit: ") guest_name = guest_name.lower() while guest_name != 'q': # Adding more names to the guests list with open(guest_file, 'a') as add_list: add_list.write(guest_name) guest_name = input("Enter the guest's name or q to quit: ") guest_name = guest_name.lower() check_guest = ' ' for guest in guest_list: check_guest += guest name = input('Please enter your name to check if you are invited: ') name = name.title() #formatting the input to match the file contents #checking if the name is on the list if name in check_guest: print(name + ", welcome to our event") else: print('Sorry ' + name + ' your name is not on the list')
graph_list = {1: set([2,3,4]), 2: set([1,5]), 3: set([1,6,7]), 4: set([1,8]), 5: set([2, 9]), 6: set([3, 10]), 7: set([3]), 8: set([4]), 9: set([5]), 10: set([6])} root_node = 1 from collections import deque def BFS(graph, root): visit = [] queue = deque([root]) while queue: n = queue.popleft() if n not in visit: visit.append(n) queue += graph[n] - set(visit) return visit print(BFS(graph_list, root_node))
import Tkinter as tk window = tk.Tk() window.tittle = ("my window") window.geometry = ("200x200") var1 = tk.StringVar() l = tk.Label(window,bg = "blue",height = 2,textvariable = var1) l.pack() def print_selection(): value = lb.get(lb.curselection()) var1.set(value) bt1 = tk.Button(window,text = "print selection",height = 2,command = print_selection) bt1.pack() var2 = tk.StringVar() var2.set((11,22,33,44,55)) lb = tk.Listbox(window,listvariable = var2) lb.pack() items = [5,4,3,2,1] for item in items: lb.insert("end",item) lb.insert(1,"test") window.mainloop()
import random print("number guessing game") number=random.randint(1,9) numberofchances=0 print("guess a number between 1 to 9") while numberofchances<5: guess=int(input("enter your guess")) if guess==number: print("congratulation! you got it right") break elif guess<number: print("guess was too low ,guess a higher numberthan ",guess) else: print("guess was too high, guess a lower number than",guess) numberofchances+=1 if not numberofchances<5: print("you lose the number was",number)
#!/usr/bin/env python # coding: utf-8 # In[1]: print("Hello world") # In[8]: print("Welcome to letsupgrade python Essentials") # In[11]: print("'$is american currency"') # In[12]: print(" we can do, if we want") # In[16]: print("im\nsanket") # In[24]: name= "sanket" age= "19" marks= "95.67" print(" The name of person is", name, "marks is" , marks, "age" , age) # In[35]: name= "xyz" age= "19" # In[33]: type(marks) # In[34]: type(age) # In[39]: a=10 b=12 c=a*b print(c) # In[40]: d=a**b e=b/a f=d+e print(f) # In[41]: print(f%a) # In[42]: a1=25 b1=50 print(a1>b1) # In[43]: print(a1>~b1) # In[ ]:
def floodFillUtil(screen, x, y, prevC, newC): # Base cases if (x<0 or x>m or y<0 or y>m or screen[x][y]!=prevC or screen[x][y]==newC): return # Replace the color at (x, y) screen[x][y] = newC # Recur for north, east, south and west floodFillUtil(screen, x + 1, y, prevC, newC) floodFillUtil(screen, x - 1, y, prevC, newC) floodFillUtil(screen, x, y + 1, prevC, newC) floodFillUtil(screen, x, y - 1, prevC, newC) def floodFill(screen, x, y, newC): prevC = screen[x][y] floodFillUtil(screen, x, y, prevC, newC) screen = [[1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 0, 0], [1, 0, 0, 1, 1, 0, 1, 1], [1, 2, 2, 2, 2, 0, 1, 0], [1, 1, 1, 2, 2, 0, 1, 0], [1, 1, 1, 2, 2, 2, 2, 0], [1, 1, 1, 1, 1, 2, 1, 1], [1, 1, 1, 1, 1, 2, 2, 1]] x = 4 y = 5 newC = 3 print(screen[x][y]) floodFill(screen, x, y, newC) print ("Updated screen after call to floodFill:") for i in range(M): for j in range(N): print(screen[i][j], end = ' ') print()
num = 2520 while True: if(num % 11 == 0 and num % 12 == 0 and num % 13 == 0 and num % 14 == 0 and num % 15 == 0 and num % 16 == 0 and num % 17 == 0 and num % 18 == 0 and num % 19 == 0 and num % 20 == 0): print("Answer: {}".format(num)) break num += 2520
#lista1 + lista2 - serve para concatenar listas. # lista * 5 - imprime a lista cinco vezes. # <valor> in lista - verifica se o elemento existe dentro da lista. # lista.append(x) - acrescentar itens na lista. # lista.insert(posição, x) - acrescentar itens na posição tal. # lista.index(x) - Busca de posição por valor. # lista.count(x) - Contagem de ocorrências de x. lista = ['janderson', 'Hellem', 'Lays'] lista.insert(1, 'Herley') for x in lista: print(x) # MÉTODOS SUPORTADOS POR LISTAS # lista.sort() - Ordenar lista. # lista.reverse() - reverter a lista. # lista.remove(x) - remove a primeira ocorrência do item. # lista.pop(POSIÇÃO) - Remove item na posição de índice especificada. # del lista[POSIÇÃO] - Remove item na posição de índice especificada. # del lista[i:j] - Remove os itens da posição i até j. lista.sort() print(lista) lista.reverse() print(lista) #lista.remove('janderson') #print(lista) lista.pop(2) print(lista) # OPERAÇÕES COM LISTAS # lista[i] = valor - atribuição de valor à posição i. # lista[i:j] = [x1,x2,x3] - atribuição de valores ao intervalo. # lista2 = [x+1 for x in lista] - Criar a lista2 com os elementos de lista incrementados. # len(lista) - Retorna o tamanho da lista. # list(lista) - Retorna os elementos da lista. # map(f, lista) - Aplica a função f a cada um dos elementos da lista; para ver o resultado, combine com list(). len(lista) if 'Lays' not in lista: print("nome não pertence a lista.") else: print("nome encontrado!") # - ORDENAÇÃO DE DICIONÁRIO # - Dicionários não são sequências, logo não mantém nenhuma ordem específica de seus objetos. # - Portanto, se você imprimir os itens de um dicionário, eles podem aparecer em qualquer ordem, sem ordenação. # - Mas é possível exibir os itens de um dicionário em ordem, usando alguns métodos interessantes. dic = {'b': 2, 'a': 1, 'd': 4, 'c': 3} ordenada = list(dic.keys()) # criando uma lista, obtendo as chaves("keys") do dicionário. for key in sorted(dic): # verifica item por item dentro do dicionário e ordena-os. print(key, "=", dic[key])
# LOOP WHILE # Estrutura de repetição que permite executar um bloco de códico, enquanto a condição for verdadeira # Sintaxe; # while (condição): # bloco de códico. # # ex: #controle = "" #while (controle != "s"): # print("a.Pagar") # print("b.Receber") # print("c.Transferir") # print("s.Sair") # controle = input('Digite a opção desejada: ') #print('Atividade Encerrada') #WHILE COM BREAK # A declaração break termina o loop atual e consegue a execução na próxima declaração após o loop. # O usos mais comum é quando alguma condição externa é disparada e requer saída imediata do loop. # O comando brack pode ser usado tanto em loops while quanto em lopps for. cont = 20 while (cont > 0): print(f"o valor da variável é igual a {cont}") cont -= 1 if (cont == 11): break print('Loop interrompido no valor 11')
class BishopMove: def howManyMoves(self, r1, c1, r2, c2): if r1 == r2 and c1 == c2: return 0 if r1 > r2: k = r1 - r2 else: k = r2 - r1 if c1 > c2: num2 = c1 - c2; else: num2 = c2 - c1; if num2 == k: return 1 elif (num2 + k) %2 == 0: return 2 else: return -1
""" This document contains a set of functions needed to perform analyses. The functions described here are all functions that perform analyses in some way necessary to calculate the final score on configurations of garbage containers. The loading of data functions and the algorithms themselves are in the other provided .py docs. """ from shapely.geometry import Polygon, Point import pandas as pd import numpy as np from .loading_data import create_aansluitingen, get_db_afvalcluster_info, \ get_distance_matrix, distance_matrix_with_counts, create_all_households, \ load_api_data, address_in_service_area, load_geodata_containers def calculate_weighted_distance(good_result, use_count=False, w_rest=0.61, w_plas=0.089, w_papi=0.16, w_glas=0.11, w_text=0.025, return_all=False): """ Calculate weighted distance of an input dataframe. Function to calculated the weighted average walking distance as part of the score function. It calculates the mean difference per fraction and employs the weights assigned to them to combine it into a single score. Input: df_containing distance from all households to its nearest container per fraction (known as good_result) Output: float representing weighted average distance """ if not use_count: rest_mean = good_result['rest_afstand'].mean() papier_mean = good_result['papier_afstand'].mean() glas_mean = good_result['glas_afstand'].mean() plastic_mean = good_result['plastic_afstand'].mean() textiel_mean = good_result['textiel_afstand'].mean() else: rest_mean = (good_result['rest_afstand'] * good_result['count'])\ .sum() / good_result['count'].sum() papier_mean = (good_result['papier_afstand'] * good_result['count'])\ .sum() / good_result['count'].sum() plastic_mean = (good_result['plastic_afstand'] * good_result['count'])\ .sum() / good_result['count'].sum() glas_mean = (good_result['glas_afstand'] * good_result['count'])\ .sum() / good_result['count'].sum() textiel_mean = (good_result['textiel_afstand'] * good_result['count'])\ .sum() / good_result['count'].sum() # Multiply mean distance per fraction with its relative importance score = w_rest * rest_mean + w_plas * plastic_mean + w_papi * papier_mean + \ w_glas * glas_mean + w_text * textiel_mean if return_all: # Return all individual mean distances (for analysis) return rest_mean, plastic_mean, papier_mean, glas_mean, textiel_mean,\ score return score def calculate_penalties(good_result, aansluitingen, use_count=False, w_rest=0.61, w_plas=0.089, w_papi=0.16, w_glas=0.11, w_text=0.025, return_all=False): """ Calculate the amount of penalties based on described policies. This function calculates all the penalties associated with the candidate solution. It does this by calculating the number of times all constraints are violated and applies the weighing that is associated with all these violations. D_... contain the maximum allowed walking distance to a container of the specified fraction. P_... show the maximum amount of households connected to a container of the fraction specified. Input: dataframe good_result containing per adress or adress poi the distance to the nearest container for all fractions. dataframe connections containing for all clusters the amount of containers per fraction, the amount of people using these containers and percentage of occupancy compared to the norm Output: The sum of all different penalties as a single float """ # Create dict containing max_dist, max_connection and weight per fraction fractions = {'rest': [100, 100, w_rest], 'plastic': [150, 200, w_plas], 'papier': [150, 200, w_papi], 'glas': [150, 200, w_glas], 'textiel': [200, 750, w_text]} MAX_PERC = 100 # To prevent magic numbers NORMAL = 100 # Normalization factor to balance both types of penalties penalties = [] # This list will store all penalties for k, v in fractions.items(): # Per fraction # Filter data for all entries that violate maximal walking distance dist_pen = good_result[good_result[f'{k}_afstand'] > v[0]] # Filter data for all containers having to many households attached conn_pen = aansluitingen[aansluitingen[f'{k}_perc'] > MAX_PERC] if not use_count: # Average amount of meters over maximum limit penalties.append((dist_pen[f'{k}_afstand'] - v[0]).sum() / good_result.shape[0] * v[2]) # Ratio of amount of households over threshold (with normalization) penalties.append((conn_pen[f'poi_{k}'] - (conn_pen[k] * v[1])) .sum() / good_result['count'].sum() * v[2] * NORMAL) else: # Use count column to weigh according to households penalties.append(((dist_pen[f'{k}_afstand'] - v[0]) * dist_pen['count']).sum()/good_result['count'] .sum() * v[2]) penalties.append((conn_pen[f'poi_{k}'] - (conn_pen[k] * v[1])) .sum() / good_result['count'].sum() * v[2] * NORMAL) if return_all: # Return all contributing factors return penalties else: # Return only the sum of the penalties return sum(penalties) def calculate_simple_penalties(good_result, aansluitingen, use_count=True, w_rest=0.61, w_plas=0.089, w_papi=0.16, w_glas=0.11, w_text=0.025, use_weight=True, return_all=True): """ Return simplified version of penalties. Simplified version of penalty function that gives total amount of penalties. """ if use_count: penalty1 = good_result[good_result ['rest_afstand'] > 100]['count'].sum() penalty2 = good_result[good_result ['plastic_afstand'] > 150]['count'].sum() penalty3 = good_result[good_result ['papier_afstand'] > 150]['count'].sum() penalty4 = good_result[good_result ['glas_afstand'] > 150]['count'].sum() penalty5 = good_result[good_result ['textiel_afstand'] > 300]['count'].sum() else: penalty1 = good_result[good_result['rest_afstand'] > 100].shape[0] penalty2 = good_result[good_result['plastic_afstand'] > 150].shape[0] penalty3 = good_result[good_result['papier_afstand'] > 150].shape[0] penalty4 = good_result[good_result['glas_afstand'] > 150].shape[0] penalty5 = good_result[good_result['textiel_afstand'] > 300].shape[0] temp = (aansluitingen['poi_rest'] - aansluitingen['rest'] * 100) penalty6 = temp[temp > 0].sum() temp = (aansluitingen['poi_plastic'] - aansluitingen['plastic'] * 200) penalty7 = temp[temp > 0].sum() temp = (aansluitingen['poi_papier'] - aansluitingen['papier'] * 200) penalty8 = temp[temp > 0].sum() temp = (aansluitingen['poi_glas'] - aansluitingen['glas'] * 200) penalty9 = temp[temp > 0].sum() temp = (aansluitingen['poi_textiel'] - aansluitingen['textiel'] * 750) penalty10 = temp[temp > 0].sum() if use_weight: total = w_rest * (penalty1 + penalty6) + w_plas * (penalty2 + penalty7) +\ w_papi * (penalty3 + penalty8) + w_glas * (penalty4 + penalty9) +\ w_text * (penalty5 + penalty10) if return_all: return total, penalty1, penalty2, penalty3, penalty4, penalty5,\ penalty6, penalty7, penalty8, penalty9, penalty10 else: return total return penalty1+penalty2+penalty3+penalty4+penalty5+penalty6+penalty7 + \ penalty8+penalty9+penalty10 def containers_per_cluster(cluster_list): """ Convert list of configuration into counted category columns. This function does a modified version of one-hot encoding. It takes as input a list with the amount of containers per fraction (as a column in the dataframe) and returns the amount of the containers per fraction in the cluster. This function is to be used as an 'apply' function on an dataframe Input: - list containing cluster info [Glas: 3, Rest: 5] Returns: - 6 integers (amount of containers per fraction and a total) """ rest = 0 plastic = 0 papier = 0 glas = 0 textiel = 0 # Prevent an error if cluster_list is empty if type(cluster_list) != list: print("Not a list") pass else: for i in cluster_list: # Divide string in parts and match the numbers with the fraction if i.startswith("Rest:"): rest = int((i.split(':')[1])) if i.startswith("Plastic:"): plastic = int((i.split(':')[1])) if i.startswith("Papier:"): papier = int((i.split(':')[1])) if i.startswith("Glas:"): glas = int((i.split(':')[1])) if i.startswith("Textiel:"): textiel = int(i.split(':')[1]) return rest, plastic, papier, glas, textiel, sum([rest, plastic, papier, glas, textiel]) def join_api_db(db_df, api_df): """ Join API dataframe and DB dataframe based on exact coordinates match. This function join the dataframes on garbage clusters from the API and the Postgres DB together to form a dataframe that has all the necessary information regarding identification, but also on the configuration of that cluster. Input: - db_df: dataframe from the database. Needs 'type' column and coordinates - api_df: dataframe from the API. needs coordinates. Returns: - joined: joined dataframe with all information """ # Select only objects that are garbage clusters, to exclude houses db_clusters = db_df[db_df['type'] == 'afval_cluster'] # Join the API and DB data based on the coordinates joined = db_clusters.set_index(['cluster_x', 'cluster_y'])\ .join(api_df.set_index(['cluster_x', 'cluster_y']), how='outer')\ .reset_index() joined = joined.dropna() # Isolate unmatched data for further matching df_clusters_open = joined[joined['s1_afv_nodes'] .isna()].reset_index() db_clusters_open = joined[joined['aantal_per_fractie'] .isna()].reset_index() # Try matching again with less strict norms joined_try_2 = fix_remaining_into_frame(db_clusters_open, df_clusters_open) joined = joined.append([joined_try_2], ignore_index=True) return joined.drop('index', axis=1) def fix_remaining_options(i, db_clusters_open, df_clusters_open, margin=10): """ Find individual matches between API and DB. Function tries to match unmatches cluster entries from the database with a suitable option not matched in the API. This is done by increasing the margins for coordinates. This can be done in increasing margins. This is a subfunction in fix_remaining_into_frame. Inputs: - i: index of options to test(from fix_remaining_into_frame) - db_clusters_open: clusters from database not matched in dataframe - df_clusters_open: clusters from API not matched in dataframe - margin: distance margin in meters to match on (default = 10) Returns: - aantal_per_fractie: dict-like information on amount of containers - volume_per_fractie: dict-like information on volume of fractions - street_name: street_name of the cluster """ # Select a certain test option and retrieve coordinates test_option = db_clusters_open.iloc[i] x = float(test_option['cluster_x']) y = float(test_option['cluster_y']) # Create square around point where a match could be made in square = Polygon([(x-margin, y-margin), (x-margin, y+margin), (x+margin, y+margin), (x+margin, y-margin)]) # Transform coordinates into column containing Point classes df_clusters_open['point'] = df_clusters_open\ .apply(lambda row: Point(row['cluster_x'], row['cluster_y']), axis=1) # Create match if one of other points falls within square df_clusters_open['fit'] = df_clusters_open['point']\ .apply(lambda point: point.within(square)) # Filter on points having a match to_return = df_clusters_open[df_clusters_open['fit']] if to_return.shape[0] > 0: # Return match if it's there to_return = to_return.iloc[0] return to_return['aantal_per_fractie'], \ to_return['volume_per_fractie'], to_return['street_name'] else: return None, None, None # Return None if there is no match def fix_remaining_into_frame(db_clusters_open, df_clusters_open, margin=10): """ Try alternative methods to match API and DB using proximity. This function assembles all cluster information that is not joined between database and API. It tries this matching again by taking some margins in the coordinates, to hopefully get a match. Inputs: - db_clusters_open: dataframe of database results not matched - df_clusters_open: dataframe of API results not matched - margin: margin to scan for in meters (default = 10) Returns: - dataframe of matches clusters from database filled with additional information from API """ # Initialize lists to hold variables apf_list = [] vpf_list = [] str_list = [] # Loop through all unmatched container clusters for i in range(db_clusters_open.shape[0]): # Try to match using function above tmp = fix_remaining_options(i, db_clusters_open, df_clusters_open, margin=margin) apf_list.append(tmp[0]) vpf_list.append(tmp[1]) str_list.append(tmp[2]) # Fill in missing parameters for matched containers db_clusters_open['aantal_per_fractie'] = apf_list db_clusters_open['volume_per_fractie'] = vpf_list db_clusters_open['street_name'] = str_list return db_clusters_open def add_shortest_distances_to_all_households(all_households, cluster_distance_matrix, use_count=False): """ Find per POI shortest distance to container of each fraction. Function that searches for shortest distance per household and per fraction and adds this information to the all_households dataframe """ cluster_distance_matrix = cluster_distance_matrix.sort_values(by='afstand') if use_count: # Group by household and keep information on first container shortest_rest = cluster_distance_matrix[cluster_distance_matrix['rest'] > 0].\ groupby('naar_s1_afv_nodes').first()[['count', 'van_s1_afv_nodes', 'afstand']].\ rename(columns={'van_s1_afv_nodes': 'poi_rest', 'afstand': 'rest_afstand'}) else: shortest_rest = cluster_distance_matrix[cluster_distance_matrix ['rest'] > 0] \ .groupby('naar_s1_afv_nodes')\ .first()[['van_s1_afv_nodes', 'afstand']]\ .rename(columns={'van_s1_afv_nodes': 'poi_rest', 'afstand': 'rest_afstand'}) # Repeat process for all other fractions shortest_plastic = cluster_distance_matrix[cluster_distance_matrix ['plastic'] > 0].\ groupby('naar_s1_afv_nodes').first()[['van_s1_afv_nodes', 'afstand']].\ rename(columns={'van_s1_afv_nodes': 'poi_plastic', 'afstand': 'plastic_afstand'}) shortest_papier = cluster_distance_matrix[cluster_distance_matrix ['papier'] > 0].\ groupby('naar_s1_afv_nodes').first()[['van_s1_afv_nodes', 'afstand']].\ rename(columns={'van_s1_afv_nodes': 'poi_papier', 'afstand': 'papier_afstand'}) shortest_glas = cluster_distance_matrix[cluster_distance_matrix ['glas'] > 0].\ groupby('naar_s1_afv_nodes').first()[['van_s1_afv_nodes', 'afstand']].\ rename(columns={'van_s1_afv_nodes': 'poi_glas', 'afstand': 'glas_afstand'}) shortest_textiel = cluster_distance_matrix[cluster_distance_matrix ['textiel'] > 0].\ groupby('naar_s1_afv_nodes').first()[['van_s1_afv_nodes', 'afstand']].\ rename(columns={'van_s1_afv_nodes': 'poi_textiel', 'afstand': 'textiel_afstand'}) # Join all_households with shortest distances to get overview all_households = all_households.set_index('naar_s1_afv_nodes').\ join([shortest_rest, shortest_plastic, shortest_papier, shortest_glas, shortest_textiel], how='left', rsuffix='_r') # leave out for first analysis # all_households = all_households.fillna(2000) return all_households def initial_loading(): """ Combine all initial loading steps in one function. This function is the consecutive call of a few functions. This is used to make an initial environment before the algorithms are applied. It returns the variables all_households, rel_poi_df, joined and df_afstandn2. These can be formed independent of the configuration of the containers. After that a choice needs to be made regarding algorithms. """ use_count = bool(input("Do you want to use addresses instead " + "of clusters?")) subsectie = str(input("What stadsdeel do you want to make as a subsection" + "(optional parameter)?")) cut_off = int(input("What is the maximum amount of containers in a " + "cluster that is considered to be useful?")) data_source = input("Where to get db files(local/online)?") if subsectie not in ['T', 'M', 'N', 'A', 'K', 'E', 'F', 'B', 'C']: subsectie = None if subsectie == 'C': # "Centrum consisting of 4 central areas" subsectie = ['M', 'A', 'K', 'E'] if data_source == "local": # Get data from local files instead of online rel_poi_df = pd.read_csv('../Data/postgres_db/info_pois.csv', index_col='Unnamed: 0') rel_poi_df = rel_poi_df[['s1_afv_nodes', 's1_afv_poi', 'cluster_x', 'cluster_y', 'type', 'bag']] print('DB relation POIs loaded') if use_count: inpt_dfob = pd.read_csv('../Data/postgres_db/' + 'addresses_per_cluster.csv') inpt_dis = pd.read_csv('../Data/postgres_db/' + 'distance_matrix.csv') df_afstandn2 = distance_matrix_with_counts(inpt_dfob=inpt_dfob, inpt_poi=rel_poi_df, inpt_dis=inpt_dis, get_data=False) print('distance matrix loaded') else: df_afstandn2 = pd.read_csv('../Data/postgres_db/' 'distance_matrix.csv') print('distance matrix loaded') elif data_source == "online": # Make connection with PostgreSQL rel_poi_df = get_db_afvalcluster_info() print('DB relation POIs loaded') if use_count: df_afstandn2 = distance_matrix_with_counts() else: df_afstandn2 = get_distance_matrix() api_df = load_api_data(subsectie=subsectie) print('API data loaded') all_households = create_all_households(rel_poi_df, subsectie=subsectie)\ .rename(columns={'s1_afv_nodes': 'naar_s1_afv_nodes'}) print('Table all households created') joined = join_api_db(rel_poi_df, api_df) print('API and DB joined') joined['rest'], joined['plastic'], joined['papier'], joined['glas'], \ joined['textiel'], joined['totaal'] = zip(*joined['aantal_per_fractie'] .apply(lambda x: containers_per_cluster(x))) print('containers per cluster determined') # Add column to determine whether rest containers can be placed there polygon_list = load_geodata_containers() joined['move_rest'] = joined.apply(lambda row: address_in_service_area (row['cluster_x'], row['cluster_y'], polygon_list=polygon_list), axis=1) print('move_rest determined') joined = joined[joined['totaal'] <= cut_off].reset_index() # joined = joined.drop(['index', 'Unnamed: 0'], axis=1) joined = joined.drop(['index'], axis=1) return all_households, rel_poi_df, joined, df_afstandn2 def analyze_candidate_solution(joined, all_households, rel_poi_df, df_afstandn2, clean=True, use_count=False, return_all=False, exclude_outliers=False): """ Analyze the score and penalties of a provided solution. This function is the repeated calling of different functions. It is the third element of the data pipeline. The first step is initial_loading(), the second part is the proposed use of algorithms to modify the configuration of the garbage clusters and this part is a series of functions to use this modification to calculate the score associated with it. Returns not only score but also other dataframes for future use in the pipeline. """ # Join distance matrix with cluster information to get rich dataframe joined_cluster_distance = joined.set_index('s1_afv_nodes')\ .join(df_afstandn2.set_index('van_s1_afv_nodes')).reset_index()\ .rename(columns={'index': 'van_s1_afv_nodes'}) # Add shortest distances to it good_result = \ add_shortest_distances_to_all_households(all_households, joined_cluster_distance, use_count) # Cleaning step to deal with missing data good_result['count'] = good_result['count'].fillna(0) good_result = good_result[good_result['count'] > 0] good_result[['poi_rest', 'poi_plastic', 'poi_papier', 'poi_glas', 'poi_textiel']] = good_result[['poi_rest', 'poi_plastic', 'poi_papier', 'poi_glas', 'poi_textiel']].fillna(999) good_result[['rest_afstand', 'plastic_afstand', 'papier_afstand', 'glas_afstand', 'textiel_afstand']] = \ good_result[['rest_afstand', 'plastic_afstand', 'papier_afstand', 'glas_afstand', 'textiel_afstand']].fillna(2000) # Exclude households that have more than 1 fraction more than 1000 away if exclude_outliers: good_result = good_result[(((good_result[['poi_rest', 'poi_plastic', 'poi_papier', 'poi_glas', 'poi_textiel']] == 999.0) .sum(axis=1) < 2) & (good_result['count'] > 0))] if clean: # Only include houses that use rest container good_result = good_result[good_result['uses_container']] else: # Set distance to and poi to NanN to esclude rest for calculation good_result.loc[~good_result['uses_container'], 'rest_afstand'] = np.nan good_result.loc[~good_result['uses_container'], 'poi_rest'] = np.nan # Set distance of cardboard to nan is cardboard is collected there good_result.loc[good_result['collect_cardboard'], 'papier_afstand'] = np.nan good_result.loc[good_result['collect_cardboard'], 'poi_papier'] = np.nan # # Set all values of landelijk noord to np.nan # good_result.loc[good_result['in_landelijk_noord'], # [['rest_afstand', 'plastic_afstand', 'papier_afstand', # 'glas_afstand', 'textiel_afstand']]] = np.nan # good_result.loc[good_result['in_landelijk_noord'], # [['poi_rest', 'poi_plastic', 'poi_papier', 'poi_glas', # 'poi_textiel']]] = np.nan # # # Set all values of Centrum to np.nan # good_result.loc[good_result['in_centrum'], # [['rest_afstand', 'plastic_afstand', 'papier_afstand', # 'glas_afstand', 'textiel_afstand']]] = np.nan # good_result.loc[good_result['in_centrum'], # [['poi_rest', 'poi_plastic', 'poi_papier', 'poi_glas', # 'poi_textiel']]] = np.nan aansluitingen = create_aansluitingen(good_result, joined_cluster_distance, use_count=use_count) avg_distance = calculate_weighted_distance(good_result, use_count=use_count, return_all=return_all) penalties = calculate_penalties(good_result, aansluitingen, use_count=use_count, return_all=return_all) simple_penalties = calculate_simple_penalties(good_result, aansluitingen, use_count=use_count, return_all=return_all) print("Average distance is : " + str(avg_distance)) print("Penalties are: " + str(penalties)) print("Simple penalties are: " + str(simple_penalties)) return joined_cluster_distance, good_result, aansluitingen,\ avg_distance, penalties, simple_penalties
import random class Cell: def __init__(self, row: int, col: int, max_number: int): self.row = row self.col = col self.possibilities = list(range(1, max_number + 1)) self.value = 0 def __str__(self): return f"({self.value} {self.possibilities})" def __repr__(self): return self.__str__() def collapse(self, number): if self.entropy > 1: try: self.possibilities.remove(number) except ValueError: return False if self.entropy == 1: self.value = self.possibilities[0] return True return False def random_set(self): self.set(random.choice(self.possibilities)) def set(self, v: int): if v not in self.possibilities: raise ValueError(f"value {v} not in possibilities {self.possibilities}") self.value = v self.possibilities = [self.value] def collapsed(self) -> bool: return self.value != 0 @property def entropy(self): return len(self.possibilities)
# ---------------------------------------------------------------------- # Name: Permutation in String # Author(s): Trinity Nguyen # ---------------------------------------------------------------------- """ Given two strings s1 and s2, write a function to return true if s2 contains the permutation of s1. In other words, one of the first string's permutations is the substring of the second string. Example 1: Input: s1 = "ab" s2 = "eidbaooo" Output: True Explanation: s2 contains one permutation of s1 ("ba"). Example 2: Input:s1= "ab" s2 = "eidboaoo" Output: False Note: The input strings only contain lower case letters. The length of both given strings is in range [1, 10,000]. """ import collections class Solution: def checkInclusion(self, s1: str, s2: str) -> bool: s1_counter = collections.Counter(s1) for i in range(len(s2)-len(s1)+1): if i == 0: s2_counter = Counter(s2[:len(s1)]) else: s2_counter[s2[i-1]] -= 1 if not s_counter[s[i-1]]: del s_counter[s[i-1]] s2_counter[s2[i+len(s1)-1]] += 1 if len(s1_counter - s2_counter) == 0: return True return False def checkInclusion2(self, s1: str, s2: str) -> bool: l1 = len(s1) l2 = len(s2) if l1 == 0 and l2 == 0: return False if l2 < l1: return False a1 = [0 for i in range(26)] a2 = [0 for i in range(26)] a = ord('a') for c in s1: a1[ord(c) - a] += 1 for c in s2[:len(s1)]: a2[ord(c) - a] += 1 if a1 == a2: return True for i in range(l2 - l1): a2[ord(s2[i]) - a] -= 1 a2[ord(s2[i + l1]) - a] += 1 if a1 == a2: return True
# ---------------------------------------------------------------------- # Name: Maximum Sum Circular Subarray # Author(s): Trinity Nguyen # ---------------------------------------------------------------------- """ Given a circular array C of integers represented by A, find the maximum possible sum of a non-empty subarray of C. Here, a circular array means the end of the array connects to the beginning of the array. (Formally, C[i] = A[i] when 0 <= i < A.length, and C[i+A.length] = C[i] when i >= 0.) Also, a subarray may only include each element of the fixed buffer A at most once. (Formally, for a subarray C[i], C[i+1], ..., C[j], there does not exist i <= k1, k2 <= j with k1 % A.length = k2 % A.length.) Example 1: Input: [1,-2,3,-2] Output: 3 Explanation: Subarray [3] has maximum sum 3 Example 2: Input: [5,-3,5] Output: 10 Explanation: Subarray [5,5] has maximum sum 5 + 5 = 10 Example 3: Input: [3,-1,2,-1] Output: 4 Explanation: Subarray [2,-1,3] has maximum sum 2 + (-1) + 3 = 4 Example 4: Input: [3,-2,2,-3] Output: 3 Explanation: Subarray [3] and [3,-2,2] both have maximum sum 3 Example 5: Input: [-2,-3,-1] Output: -1 Explanation: Subarray [-1] has maximum sum -1 Note: 1. -30000 <= A[i] <= 30000 2. 1 <= A.length <= 30000 Hint #1: For those of you who are familiar with the Kadane's algorithm, think in terms of that. For the newbies, Kadane's algorithm is used to finding the maximum sum subarray from a given array. This problem is a twist on that idea and it is advisable to read up on that algorithm first before starting this problem. Unless you already have a great algorithm brewing up in your mind in which case, go right ahead! Hint #2: What is an alternate way of representing a circular array so that it appears to be a straight array? Essentially, there are two cases of this problem that we need to take care of. Let's look at the figure below to understand those two cases: Hint #3: The first case can be handled by the good old Kadane's algorithm. However, is there a smarter way of going about handling the second case as well? """ class Solution: def maxSubarraySumCircular(self, A: List[int]) -> int: curr_max = A[0] max_sum = A[0] curr_min = A[0] min_sum = A[0] for num in A[1:]: curr_max = max(num, curr_max + num) max_sum = max(curr_max, max_sum) curr_min = min(num, curr_min + num) min_sum = min(curr_min, min_sum) if sum(A) == min_sum: return max_sum return max(max_sum, sum(A) - min_sum)
def solve(input): listOfMoves=[] step = 0 actualIndex=0 futureIndex=0 right=0 for line in input.splitlines(): listOfMoves.append(int(line)) right = len(listOfMoves)-1 while(True): futureIndex=actualIndex+listOfMoves[actualIndex] if(futureIndex<0 or futureIndex>right): step+=1 break else: if(listOfMoves[actualIndex]>=3): listOfMoves[actualIndex]-= 1 else: listOfMoves[actualIndex]+=1 actualIndex=futureIndex step+=1 print(step) def main(): with open('textfile.txt', 'r') as f: fileinput = f.read() solve(fileinput) if __name__ == '__main__': main()
import hw1 from cse163_utils import assert_equals def test_total(): """ Tests the total method """ # The regular case assert_equals(15, hw1.total(5)) # Seems likely we could mess up 0 or 1 assert_equals(1, hw1.total(1)) assert_equals(0, hw1.total(0)) # Test the None case assert_equals(None, hw1.total(-1)) def test_count_divisible_digits(): assert_equals(4, hw1.count_divisible_digits(650899, 3)) assert_equals(1, hw1.count_divisible_digits(-204, 5)) # new tests assert_equals(0, hw1.count_divisible_digits(0, 0)) assert_equals(3, hw1.count_divisible_digits(333, 3)) def test_is_relatively_prime(): assert_equals(True, hw1.is_relatively_prime(12, 13)) assert_equals(False, hw1.is_relatively_prime(12, 14)) # new tests assert_equals(True, hw1.is_relatively_prime(1, 1)) assert_equals(True, hw1.is_relatively_prime(1, 10)) def test_travel(): assert_equals((-1, 4), hw1.travel('NW!ewnW', 1, 2)) # new tests assert_equals((0, 0), hw1.travel('', 0, 0)) assert_equals((0, 0), hw1.travel('!!!!!!!', 0, 0)) def test_compress(): assert_equals('c1o17l1k1a1n1g1a1r1o2', hw1.compress('cooooooooooooooooolkangaroo')) # new tests assert_equals('c1', hw1.compress('c')) assert_equals('a8', hw1.compress('aaaaaaaa')) def test_longest_line_length(): assert_equals(35, hw1.longest_line_length('song.txt')) # new tests assert_equals(None, hw1.longest_line_length('empty.txt')) assert_equals(5, hw1.longest_line_length('tie.txt')) def test_longest_word(): assert_equals('3: Merrily,', hw1.longest_word('song.txt')) # new tests assert_equals(None, hw1.longest_word('empty.txt')) assert_equals('1: asdf', hw1.longest_word('tie.txt')) def test_get_average_in_range(): assert_equals(5.5, hw1.get_average_in_range([1, 5, 6, 7, 9], 5, 7)) # new tests assert_equals(0, hw1.get_average_in_range([], 10, 20)) assert_equals(0, hw1.get_average_in_range([1, 2, 3], 4, 6)) def test_mode_digit(): assert_equals(1, hw1.mode_digit(12121)) # new tests assert_equals(3, hw1.mode_digit(2233)) assert_equals(1, hw1.mode_digit(1)) assert_equals(1, hw1.mode_digit(-1)) def main(): test_total() test_count_divisible_digits() test_is_relatively_prime() test_travel() test_compress() test_longest_line_length() test_longest_word() test_get_average_in_range() test_mode_digit() if __name__ == '__main__': main()
from storage import Storage class PasswordHandler: def __init__(self): self.storage_instance = Storage() self.storage = self.storage_instance.read_storage() def create_line(self, key, password): self.storage[key] = password return f'{key}:{password} was added to the storage' def del_line(self, del_key, del_password): self.storage.pop(del_key, None) return f'{del_key}:{del_password} was removed from' def read_line(self, ent_key): if ent_key in self.storage: return self.storage[ent_key] def change_line(self, change_key, new_password): if change_key in self.storage: if change_key[new_password] in self.storage: return f'{change_key} was change from storage' else: return f"I'm sorry your password Falls" else: return f"I'm sorry your key doesn't true"
a = input ("Enter character: ") if a == "a": print(1) elif a == "b": print(2) elif a == "c"
def quicksort(nums): if len(nums) <= 1: return nums else: return quicksort([i for i in nums if i < nums[0]]) + [i for i in nums if i == nums[0]] + quicksort([i for i in nums if i > nums[0]]) nums = [3,1,4,5,2,4] print(quicksort(nums)) def partition(nums,l,r): pivot = nums[l] while l < r:#因为取的是最左边的节点,所以要从右边开始遍历 while l < r and nums[r] >= pivot: r -= 1 nums[l]=nums[r] while l < r and nums[l] <= pivot: l+=1 nums[r]=nums[l] nums[l] = pivot return l def quicksort(nums, l, r): if l < r: pivot = partition(nums,l,r) quicksort(nums,l,pivot-1) quicksort(nums,pivot+1,r) return nums print(quicksort([2,1,23,2,4,5], 0, 5)) import random def quicksort(nums, l, r): if l < r: pivot = partition(nums, l, r) quicksort(nums,l,pivot-1) quicksort(nums,pivot+1,r) return nums def partition(nums,l,r): index = random.choice(range(l,r+1)) nums[l], nums[index] = nums[index], nums[l] pivot = nums[l] while l < r: while l < r and nums[r] >= pivot: r -= 1 nums[l] = nums[r] while l < r and nums[l] <= pivot: l+=1 nums[r]=nums[l] nums[l] = pivot return l print(quicksort([5,2,3,25,89,-3,1,7],0,7))
from string import digits, ascii_lowercase, ascii_uppercase def tentoany(n, base): chars = digits+ascii_lowercase+ascii_uppercase a,b = divmod(n,base) if a: return tentoany(a,base)+chars[b] else: return chars[b] def anytoten(n, base): chars = digits+ascii_lowercase+ascii_uppercase if not n: return 0 else: return base*(anytoten(n[:-1],base))+chars.index(n[-1]) def anytoten2(n, base): chars = digits+ascii_lowercase+ascii_uppercase res = 0 for i,v in enumerate(n[::-1]): res += pow(base,i)*chars.index(v) return res print(tentoany(10,2)) print(tentoany(10,8)) print(anytoten('1010',2)) print(anytoten2('1010',2)) print(tentoany(200,16)) print(anytoten2('c8',16)) print(anytoten('c8',16))
l = [1,2,3] e1 = 2 e2 = 10 def search_element(x,y): if y in x: return x.index(y) # 이 부분에 대해서 제대로 작성하지 못함 else: return False print(search_element(l,e1)) print(search_element(l,e2))
def reverse_text(x1,x2,x3,x4,x5): i = 1 if len(xi) % 2 == 0: return xi if len(xi) % 2 == 1: return reverse(xi) i += 1 print(reverse_text('tiger','lion','bear','snake','leopard'))
''' Problem: Rotate Matrix Description: Given an image represented by an NxN matrix, where each pixel in the image is 4 bytes, write a method to rotate the image by 90 degrees. Can you do this in place? Solved: Halve. Don't know how to do it in-place, did see a 1-line solution on the internet: zip(*matrix[::-1]) ''' def rotate_clockwise(m): rotated = [] for i in range(len(m)): row = [] for j in range(len(m)-1, -1, -1): row.append(m[j][i]) rotated.append(row) return rotated def rotate_counterclockwise(m): rotated = [] for j in range(len(m)-1, -1, -1): row = [] for i in range(len(m)): row.append(m[i][j]) rotated.append(row) return rotated matrix = [[1,2,3],[4,5,6],[7,8,9]] print(rotate_clockwise(matrix)) print(rotate_counterclockwise(matrix))
''' Problem: Queue via stacks Description: Implement a MyQueue class which implements a queue using two stacks. Solved: True ''' class MyQueue: to_add = None to_remove = None last_pop = False def __init__(self, size): self.to_add = Stack() self.to_remove = Stack() def add(self, el): if last_pop: while self.to_remove: self.to_add.push(self.to_remove.pop()) last_pop = False self.to_add.push(el) def remove(self): if not last_pop: while self.to_add: self.to_remove.push(self.to_add.pop()) last_pop = True return self.to_remove.pop() def peek(self): if not last_pop: while self.to_add: self.to_remove.push(self.to_add.pop()) last_pop = True return self.to_remove.peek() class Stack: stack = None def __init__(self): self.stack = [] def push(self, el): self.stack.append(el) def pop(self): return self.stack.pop() def peek(self): return self.stack[len(self.stack)-1] def is_empty(self): return self.stack == []
''' Problem: Sum Lists Description: You have two numbers represented by a linked list, where each node contains a single digit. The digits are stored in reverse order, such that the 1's digit is at the head of the list. Write a function that adds the two numbers and returns the sum as a linked list. FOLLOW UP: Suppose the digits are stored in forward order. Repeat the above problem. Solved: True ''' class Node: next = None data = None def __init__(self, d): self.data = d def get_number(node): count = 1 total = node.data node = node.next while node: total += node.data*10**count count += 1 node = node.next return total def create_reverse_from_number(number): node = Node(number-int(number/10)*10) first_node = node number = int(number/10) while number != 0: new_node = Node(number-int(number/10)*10) number = int(number/10) node.next = new_node node = new_node return first_node def create_from_number(number): l = len(str(number)) curr_number = number/(10**(l-1)) number -= curr_number*(10**(l-1)) node = Node(curr_number) first_node = node while number != 0: l = len(str(number)) curr_number = number/(10**(l-1)) number -= curr_number*(10**(l-1)) new_node = Node(curr_number) node.next = new_node node = new_node return first_node def sum_linked_lists(head1, head2): n1 = get_number(head1) n2 = get_number(head2) the_sum = n1+n2 head_reverse = create_reverse_from_number(the_sum) head_correct = create_from_number(the_sum) # test cases worked t1 = Node(7) t2 = Node(1) t3 = Node(6) t1.next = t2 t2.next = t3 t4 = Node(5) t5 = Node(9) t6 = Node(2) t4.next = t5 t5.next = t6 sum_linked_lists(t1, t4)
''' Problem: Power Set Description: Write a method to return all subsets of a set. Notes: Not sure how to flatten the list Solved: True ''' import copy def all_subsets(array, subsets, curr_solution): if not array: return curr_solution else: left_tree = all_subsets(array[1:], subsets, curr_solution) expanded_solution = copy.copy(curr_solution) expanded_solution.append(array[0]) right_tree = all_subsets(array[1:], subsets, expanded_solution) return [left_tree, right_tree] subsets = all_subsets([0, 1, 2], [], []) for el in subsets: print(el)
''' Problem: Zero Matrix Description: Write an algorithm such that if an element in an MxN matrix is 0, its entire row and column are set to O. Solved: True ''' def parse_matrix(m): indexes = [] for i in range(len(m)): for j in range(len(m[i])): if m[i][j] == 0: indexes.append([i, j]) for ind in indexes: row = ind[0] column = ind[1] m[row] = [0]*len(m[0]) for i in range(len(m)): m[i][column] = 0 return m matrix1 = [[0,2,3],[4,5,6],[7,8,9]] matrix2 = [[1,2,3],[4,0,6],[7,8,9]] matrix3 = [[1,2,3],[4,5,6],[7,8,0]] print(parse_matrix(matrix1)) print(parse_matrix(matrix2)) print(parse_matrix(matrix3))
''' Problem: Sort Stack Description: Write a program to sort a stack such that the smallest items are on the top. You can use an additional temporary stack, but you may not copy the elements into any other data structure (such as an array). The stack supports the following operations: push, pop, peek, and isEmpty. Solved: True ''' class Stack: stack = None def __init__(self): self.stack = [] def push(self, el): self.stack.append(el) def pop(self): return self.stack.pop() def peek(self): return self.stack[len(self.stack)-1] def is_empty(self): return self.stack == [] def sort(self): temp_stack = Stack() while not self.stack.is_empty(): temp = self.stack.pop() while not temp_stack.is_empty() and temp_stack.peek() > temp: self.stack.push(temp_stack.pop()) temp_stack.push(temp) while not temp_stack.is_empty(): self.stack.push(temp_stack.pop())
''' Problem: Is Unique Description: Implement an algorithm to determine if a string has all unique characters. What if you cannot use additional data structures? Solved: True ''' def is_unique(word): d = {} for c in word: if c in d: return 'Not unique!' d[c] = 0 return 'Unique' not_unique = 'jammer dit is niet uniek' unique = 'uniek' print(is_unique(not_unique)) print(is_unique(unique))
#This program will display how many calories of cookies you eat #Since the whole bag contains 30 cookies and all 30 cookies are 900 calories #We will multiply the amount of cookies eaten by 900 #And then divide that number by 30 # # #Name: Zachary Baltrus #Assignment: Homework 1 # #CIT 1400 #This line of code will be an import for how many cookies are eaten cookiesEaten = eval(input("How many cookies did you eat?: ")) #The next line of code will be calculating how many calories eaten caloriesEaten = (cookiesEaten * 900)/30 #The final line of code will be displaying how many calories eaten print("%.2f" % caloriesEaten, "calories")
# Game: Heads or Tails # This program will have a user enter heads or tails # The computer will then generate 0 or 1, which will be heads or tails. # Then the computer will report if the user is correct or incorrect. # The program will then ask the user if they want to play again. # # # Homework 5 # Zachary Baltrus # #CIS 1400 # This line is so that the computer can have a random integer. import random # Here is where the program will define the loop values with 0. gameLoop = 0 playAgainLoop = 0 # This is the first loop for the game. while gameLoop == 0: playAgainLoop = 0 # This is where the computer will randomly generate a number. for computersRange in range (0,1): computersChoice = random.randint(0,1) if computersChoice == 0: computersChoice = "heads" else: computersChoice = "tails" # This is where the user will enter their choice. userInput = input("Please enter heads or tails: ") # This decieds if the player was right or wrong. if userInput == computersChoice: print("You were correct, it was " + computersChoice + "!") else: print("You guessed wrong! It was " + computersChoice + ".") # This is the loop that asking if the player wants to run the program again. while playAgainLoop == 0: playAgainInput = input("Would you like to play again?: (y/n) ") if playAgainInput == "y" or playAgainInput == "yes": gameLoop = 0 playAgainLoop = 1 elif playAgainInput == "n" or playAgainInput == "no": gameLoop = 1 playAgainLoop = 1 print("Thanks for playing!") else: playAgainLoop = 0 print("Please enter yes or no.")
# Electrical Engineering Problem # This program will calculate the power by having # the user enter the current of the resistance # # # Lab 6 # Zachary Baltrus # # CIS 1400 # First this is defining all of the Lists to be set to their base value resistanceList = [16, 27, 39, 56, 81] currentList = [] powerList = [] # This line is having the user enter the current values for num in range(0, len(resistanceList)): print("Please enter the current of the resistance for", resistanceList[num], ":") currentInput = eval(input()) if currentInput <= 0: print ("You cannot enter a negative number.") while currentInput <= 0: print("Enter another current input.") currentInput = 0 currentList.append(currentInput) # This for loop is for calcuating the power 5 times for num in range(0, len(currentList)): powerList.append(resistanceList[num] * currentList[num]**2) # This will be printing the table for the Current and Power print("Resistance", "\t", "Current", "\t", "Power") for num in range(0, len(powerList)): print(resistanceList[num], "\t\t", currentList[num], "\t\t", powerList[num])
a = int ( input() ) i = 0 for i in range(a): b = int ( input() ) t = 2 ** b t = int(t / 12 / 1000) print (t,"kg")
#PART (1/5): Latitude and Longitude #In this part, we are going to visualize the location of the birds. We are going to plot latitude and longitude along y and x-axis respectively and visualize the location data present in the csv file. import pandas as pd import matplotlib.pyplot as plt import numpy as np birddata = pd.read_csv("bird_tracking.csv") bird_names = pd.unique(birddata.bird_name) # storing the indices of the bird Eric ix = birddata.bird_name == "Eric" x,y = birddata.longitude[ix], birddata.latitude[ix] plt.figure(figsize = (7,7)) plt.plot(x,y,"b.") ''' To look at all the birds trajectories, we plot each bird in the same plot ''' plt.figure(figsize = (7,7)) for bird_name in bird_names: # storing the indices of the bird Eric ix = birddata.bird_name == bird_name x,y = birddata.longitude[ix], birddata.latitude[ix] plt.plot(x,y,".", label=bird_name) plt.xlabel("Longitude") plt.ylabel("Latitude") plt.legend(loc="lower right") plt.show()
import random def random_numbers(): numbers = set() while len(numbers) < 5: random_number = random.randint(0, 90) numbers.add(random_number) return numbers winning_numbers = random_numbers() my_numbers = random_numbers() my_winning_numbers = winning_numbers.intersection(my_numbers) print(f"My winning numbers: {my_winning_numbers} \n" f"# hit: {len(my_winning_numbers)}")
def bfs(graph): visited = set() frontier = [0] while len(frontier) > 0: next_elm = frontier.pop(0) if next_elm in visited: continue visited.add(next_elm) for neighbour in graph[next_elm]: frontier.append(neighbour) return len(visited) def main(): with open('day12.txt', 'r') as f: lines = map(lambda l: l[:-1], f.readlines()) graph = dict() for line in lines: tokens = line.split() src = int(tokens[0]) neighbours = list() for nindex in tokens[2:]: if nindex[-1] == ',': nindex = nindex[:-1] neighbours.append(int(nindex)) graph[src] = neighbours result = bfs(graph) print result if __name__ == '__main__': main()
#leetCode problem 500 #Keyboard Row r1 = list('qwertyuiopQWERTYUIOP') r2 = list('asdfghjklASDFGHJKL') r3 = list('zxcvbnmZXCVBNM') #print (r1[10]) def fn1 (l): list_char = [] flag = False final = [] print (l) for i in range (0, len(l)): list_char.append(list(l[i])) x = 0 print(list_char) for i in range(0, len(l)): if list_char[i][0] in r1: while x in range(0, len(list_char[i])): if list_char[i][x] in r1: x += 1 print ("list_char",i,"check", "fit") flag = True else: print ("NOT working") flag = False break if flag == True: final.append(l[i]) flag = False x = 0 if list_char[i][0] in r2: while x in range(0, len(list_char[i])): if list_char[i][x] in r2: x += 1 print ("list_char",i,"check", "fit") flag = True else: print ("NOT working") flag = False break if flag == True: final.append(l[i]) flag = False x = 0 if list_char[i][0] in r3: while x in range(0, len(list_char[i])): if list_char[i][x] in r3: x += 1 print ("list_char",i,"check", "fit") flag = True else: print ("NOT working") flag = False break if flag == True: final.append(l[i]) flag = False x = 0 #print (len(l)) return final #return final test_list = ["qwwerwq","dafsasfda","Zcxvzxcxzv","zxc"] print(fn1(test_list))
# 035 # An array of number [1,3,4,6] will be called nums # A number 5, will be called target # return should be 2, since in an array # [ 1 , 3 , 4 , 6 ] // BTW array is sorted # 0 1 2 3 //position # thus return 2 since 5 is >3 and <4, thus should be added to pos 2 def solution(nums, target): if target > nums[-1]: return len(nums) elif target <= nums[0]: return 0 for index in range(len(nums)): if target > nums[index-1] and target <= nums[index]: return index def solution2(nums, target): return len([i for i in nums if i < target]) testcase1_arr = [1, 3, 4, 8, 9] testcase2_arr = [6] testcase3_arr = [2,3] print(solution(testcase2_arr, 3)) print(solution2(testcase2_arr, 3))
#LeetCode 344 #reverse String def fn (s): list_s = list(s) reversed_list = list_s[::-1] return "".join(reversed_list) test_1 = "hello" print(fn(test_1))
#!/usr/bin/env python """ n_queens.py N-queens solver (`CSPy` usage example). """ import itertools import numpy as np import matplotlib.pyplot as plt from cspy import Variable, Constraint, CSP ############## # PARAMETERS # ############## N = 8 VARIABLES = 'pieces' # either 'squares' or 'pieces'. For efficiency, choose 'pieces'. PLOT_SOLN = True ALGORITHM = 'min_conflicts' # either 'backtracking' or 'min_conflicts'. For efficiency, choose 'min_conflicts'. # Given an N x N chessboard, can we find a configuration in which to place N queens # on the board such that no two queens attack each other? def get_diagonal(r, c, heading='se'): """Returns the positions on the diagonal starting at (r, c) as a list of '<row><col>' strings. HEADING should be passed in as either 'se' (representing southeast travel) or 'ne'. """ assert heading in {'se', 'ne'}, 'invalid heading direction' diagonal = [] for i in range(N): if r < 0 or c < 0 or r >= N or c >= N: break diagonal.append('%d%d' % (r, c)) r = r + 1 if heading == 'se' else r - 1 c += 1 return diagonal def from_name(_str): """Returns a (r, c) tuple from the '<row><col>' name string _STR.""" return int(_str) // (10 * (N // 10 + 1)), int(_str) % (10 * (N // 10 + 1)) if __name__ == '__main__': csp = CSP() var_names = [] if VARIABLES == 'squares': # An illustration of how problem formulation can make all the difference. # This setup is much, much less efficient than that of 'pieces'. for r in range(N): for c in range(N): name = '%d%d' % (r, c) var_names.append(name) csp.add_variable(Variable(name, {0, 1})) by_row = [['%d%d' % (r, c) for c in range(N)] for r in range(N)] by_col = [['%d%d' % (r, c) for r in range(N)] for c in range(N)] by_dia = [get_diagonal(r, 0, 'se') for r in range(N)] by_dia.extend([get_diagonal(0, c, 'se') for c in range(N)]) by_dia.extend([get_diagonal(r, 0, 'ne') for r in range(N)]) by_dia.extend([get_diagonal(N - 1, c, 'ne') for c in range(N)]) by_row = map(tuple, by_row) by_col = map(tuple, by_col) by_dia = set(map(tuple, by_dia)) # remove duplicate diagonals for row_positions in by_row: for names in itertools.combinations(row_positions, 2): csp.add_constraint(Constraint(names, lambda v0, v1: (v0.value, v1.value) != (1, 1))) for col_positions in by_col: for names in itertools.combinations(col_positions, 2): csp.add_constraint(Constraint(names, lambda v0, v1: (v0.value, v1.value) != (1, 1))) for dia_positions in by_dia: for names in itertools.combinations(dia_positions, 2): csp.add_constraint(Constraint(names, lambda v0, v1: (v0.value, v1.value) != (1, 1))) csp.add_constraint(Constraint(var_names, lambda *args: sum([v.value for v in args]) == N)) else: for i in range(N): var_names.append(str(i)) csp.add_variable(Variable(str(i), [(r, c) for r in range(N) for c in range(N)])) for names in itertools.combinations(var_names, 2): csp.add_constraint(Constraint(names, lambda v0, v1: v0.value[0] != v1.value[0])) csp.add_constraint(Constraint(names, lambda v0, v1: v0.value[1] != v1.value[1])) csp.add_constraint(Constraint(names, lambda v0, v1: abs(v0.value[0] - v1.value[0]) != abs(v0.value[1] - v1.value[1]))) solution = csp.get_solution(algorithm=ALGORITHM) print(solution) if PLOT_SOLN and solution is not None: board = np.zeros((N, N)) if VARIABLES == 'squares': for name, value in solution.items(): r, c = from_name(name) board[r, c] = value else: for r, c in solution.values(): board[r, c] = 1 plt.imshow(board) plt.show()
def first_and_last(lists): count = 0 for i in lists: if len(i)>=2 and i[0]==i[-1]: count = count + 1 print(count) lists = list(input("Enter the elements of list:: ").split()) first_and_last(lists)
def sort(str): words = str.split() print(words) b=words.sort() print(b) return (b) a=input('enter words separated by comma:'.split(',')) print(sort(a))