text
stringlengths
37
1.41M
# https://leetcode.com/problems/two-sum/description/ # Input: nums = [2,7,11,15], target = 9 # Output: [0,1] # Input: nums = [3,2,4], target = 6 # Output: [1,2] def twoSum(nums, target): print (nums) sum_map = {} for i in range(len(nums)): dif = target - nums[i] print ("[%s] %s=%s" % (i,nums[i], dif)) comp_nums_i = sum_map.get(nums[i], None) print ('comp_nums_i=%s' % (comp_nums_i)) if comp_nums_i is None: sum_map[dif] = i print (sum_map) else: return [comp_nums_i, i] return [] nums = [2,7,11,15] nums = [3,2,4] nums = [3,3] target = 9 target = 6 print (twoSum(nums, target))
""" https://leetcode.com/problems/maximum-subarray/description/ Input: nums = [-2,1,-3,4,-1,2,1,-5,4] Output: 6 Explanation: [4,-1,2,1] has the largest sum = 6. Input: nums = [1] Output: 1 Input: nums = [0] Output: 0 Input: nums = [0] Output: 0 Input: nums = [-100000] Output: -100000 """ def maxSubArray(nums): sum = m = nums[0] for i in range(1, len(nums)): print (sum+nums[i], nums[i]) sum = max(sum+nums[i], nums[i]) m = max(m, sum) return m nums = [-2, 1, -3, 4, -1, 2, 1, -5, 4] #nums = [5,7,8,-1,-3,-3,1,2,4,-9,3,4] #nums = [-100000] print (maxSubArray(nums))
""" https://www.geeksforgeeks.org/sort-a-stack-using-recursion/ """ def insert(x, n): print ('x=%s n=%s' % (x, n)) if not x or (x and n >= x[-1]): print ('** x=%s n=%s **' % (x,n)) x.append(n) return y = x.pop() print ('y=%s' % y) insert(x, n) x.append(y) print ('after x=%s' % x) def sortstack(arr): x = [] while arr: n = arr.pop() insert(x, n) print(x) arr = [10,4,2,1,9,5,3] sortstack(arr)
""" Implement Insertion Sorting Algorithm """ def insertion_sort(a): l = len(a) print (a) for i in range(l-1): #print ('********%s********' % i) for j in range(i, -1, -1): #print (a[j], a[j+1]) if a[j+1] < a[j]: a[j], a[j+1] = a[j+1], a[j] else: break #print (a) print (a) a = [99, 44, 6, 2, 1, 5, 63, 87, 283, 4, 0] a = [1,2,3,4,10,8] insertion_sort(a)
""" https://leetcode.com/problems/valid-palindrome/ Example 1: Input: "A man, a plan, a canal: Panama" Output: true Example 2: Input: "race a car" Output: false Constraints: s consists only of printable ASCII characters. """ """ def isPalindrome(s): s = [i for i in s if i.isalnum()] s = ''.join(s).lower() return s == s[::-1] """ def isPalindrome(s): i, j = 0, len(s) - 1 while i <= j: print ("%s=%s %s=%s" % (i, s[i], j, s[j])) while i <=j and not s[i].isalnum(): i += 1 while i <= j and not s[j].isalnum(): j -= 1 #print ("AFTER %s=%s %s=%s" % (i, s[i], j, s[j])) if i <= j and not s[i].lower() == s[j].lower(): return False else: i += 1 j -= 1 return True #s = "A man, a plan, a canal: Panama" #s = "race a car" s = "-" print (isPalindrome(s))
a=0 if a>10 print("a value is greater than 0") else: print("a is less")
#!/usr/bin/env python # coding: utf-8 # In[3]: import pandas as pd Location = "C:/Users/sarai/OneDrive/Desktop/Business Intelligence/axisdata.csv" df = pd.read_csv(Location) df # In[4]: # Average cars sold per month df['Cars Sold'].mean() # In[5]: # Maximum cars sold per month df['Cars Sold'].max() # In[6]: # Minimum cars sold per month df['Cars Sold'].min() # In[7]: # Average cars sold per month by gender df.groupby('Gender')['Cars Sold'].mean() # In[13]: # Average hours worked by people selling more than three cars per month df.loc[df['Cars Sold'] > 3]['Hours Worked'].mean() # In[9]: # Average years of experience df['Years Experience'].mean() # In[10]: # Average years of experience for people selling more than three cars per month df.loc[df['Cars Sold'] > 3]['Years Experience'].mean() # In[16]: # Average cars sold per month sorted by whether they have had sales training df.groupby('SalesTraining')['Cars Sold'].mean() # In[19]: # Chart showing hours worked df.boxplot(column='Hours Worked') # In[23]: # Graph of average sales training (df.loc[:,'SalesTraining'] == 'Y').mean() df.groupby('SalesTraining')['SalesTraining'].count().plot.pie(autopct='%.2f',figsize=(5,5)) # In[ ]:
def count_substring(string, sub_string): co=0 set=0 for i in range(0,len(string)): #print(set) #print(count) string=string[set:] num=string.find(sub_string) #print(num) set=num+1 co+=1 if set<=0: break #print (co) return co-1
# Define Text Cleaning function which eliminates punctuation and figures def TextCleaning(Text): Text = str(Text) Text = Text.replace('_', ' ') Text = Text.replace('-', ' ') Text = Text.replace('+', ' ') Text = Text.replace("'", ' ') Text = Text.replace('"', '') Text = Text.replace('”', '') Text = Text.replace('(', '') Text = Text.replace(')', '') Text = Text.replace('[', '') Text = Text.replace(']', '') Text = Text.replace('{', '') Text = Text.replace('}', '') Text = Text.replace('>', ' ') Text = Text.replace('<', ' ') Text = Text.replace('@', '') Text = Text.replace('|', '') Text = Text.replace('/', '') Text = Text.replace('"', '') Text = Text.replace('=', '') Text = Text.replace('.', '') Text = Text.replace(',', '') Text = Text.replace(':', '') Text = Text.replace('!', '') Text = Text.replace('?', '') Text = Text.replace('0', '') Text = Text.replace('1', '') Text = Text.replace('2', '') Text = Text.replace('3', '') Text = Text.replace('4', '') Text = Text.replace('5', '') Text = Text.replace('6', '') Text = Text.replace('7', '') Text = Text.replace('8', '') Text = Text.replace('9', '') Text = Text.replace(' p ', '') return Text # Define Bagging function which transforms text into a clean bag of words import nltk nltk.download('punkt') nltk.download('wordnet') def BaggingText(Text): # Tokenize text Bag = nltk.word_tokenize(Text) # Make the words cleaner lemma = nltk.wordnet.WordNetLemmatizer() for i in range(0,len(Bag)): Bag[i] = Bag[i].lower() Bag[i] = lemma.lemmatize(Bag[i]) return Bag import nltk nltk.download('stopwords') from nltk.corpus import stopwords # Import Data import pandas as pd Data = pd.read_csv('/home/edward/QueryResults_Clean2.csv', sep=',', engine='python', error_bad_lines=False) # Count vectorizer from sklearn.feature_extraction.text import CountVectorizer Corpus = [] for i in range(len(Data)): Corpus.append(str(Data['Clean_Bags'].iloc[i])) count_vectorizer = CountVectorizer(analyzer='word',stop_words= 'english') X = count_vectorizer.fit_transform(Corpus) # Store Count vectorizer in a DataFrame Count_Data = pd.DataFrame(data = X.toarray(),columns = count_vectorizer.get_feature_names()) # Create list with all "real" tags and create list of all tags for each individual Data['Tag_Bags'] = 0 Tags = [] for i in range(len(Data)): Personal_Tags = [] for h in range(len(Data['Tags'].iloc[i])): if Data['Tags'].iloc[i][h] == '<': Beginning = h+1 for k in range(h, len(Data['Tags'].iloc[i])): if Data['Tags'].iloc[i][k] == '>': End = k Personal_Tags.append(Data['Tags'].iloc[i][Beginning:End]) Tags.append(Data['Tags'].iloc[i][Beginning:End]) break Data['Tag_Bags'].iloc[i] = Personal_Tags # Reorder all Tags by frequency UniqueTags = list(set(Tags)) Number = [] for i in range(len(UniqueTags)): Number.append(Tags.count(UniqueTags[i])) zipped_lists = zip(Number, UniqueTags) sorted_pairs = sorted(zipped_lists, reverse=True) tuples = zip(*sorted_pairs) Number, UniqueTags = [list(tuple) for tuple in tuples] # Store all tags that appear at least 100 times TopTags = UniqueTags[0:187] Data['Clean_Tags'] = 0 for i in range(len(Data)): Individual_Bag = [] for j in range(len(Data['Tag_Bags'].iloc[i])): if (Data['Tag_Bags'].iloc[i][j] in TopTags): Individual_Bag.append(Data['Tag_Bags'].iloc[i][j]) Data['Clean_Tags'].iloc[i] = Individual_Bag # Count vectorizer from sklearn.feature_extraction.text import CountVectorizer Corpus = [] for i in range(len(Data)): Corpus.append(str(Data['Clean_Tags'].iloc[i])) count_vectorizer = CountVectorizer(analyzer='word',stop_words= 'english') X = count_vectorizer.fit_transform(Corpus) # Store Count vectorizer in a DataFrame Targets_Data = pd.DataFrame(data = X.toarray(),columns = count_vectorizer.get_feature_names()) # Replace all Counts by a Binary for i in range(len(Targets_Data.columns)): VariableName = str(Targets_Data.columns[i]) Targets_Data[VariableName][Targets_Data[VariableName] > 0] = 1 # Fusion des 500 features avec les 200 variables targets Count_Data = Count_Data.iloc[:,0:456] Count_Data_Renamed = Count_Data for i in range(len(Count_Data.columns)): Count_Data_Renamed[str(i)] = Count_Data.iloc[:,i] Count_Data_Renamed = Count_Data_Renamed.iloc[:,456:912] Supervised_Data = pd.concat([Count_Data_Renamed, Targets_Data], axis=1) Count_Data = Count_Data.iloc[:,0:456] # Separation des données en Test et Trainnning from sklearn.utils import shuffle from sklearn.model_selection import train_test_split Shuffled_Data = shuffle(Supervised_Data) X = Shuffled_Data.iloc[:,0:456] y = Shuffled_Data.iloc[:,456::] X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=0) Supervised_train = pd.concat([X_train, y_train], axis=1) Supervised_test = pd.concat([X_test, y_test], axis=1) # Fit 200 logistic regressions - one for each Tag - on the 500 features, and store in dictionary from sklearn.metrics import accuracy_score from sklearn.linear_model import LogisticRegression X = Supervised_train.iloc[:,0:456] LogitModels = {} LogitReg = {} for i in range(456,len(Supervised_Data.columns)): LogitReg["Logit_{0}".format(i)] = LogisticRegression(random_state=0) y = Supervised_train.iloc[:,i] LogitModels["model_{0}".format(i)] = LogitReg["Logit_{0}".format(i)].fit(X, y) from sklearn.metrics import accuracy_score from sklearn.ensemble import RandomForestClassifier X = Supervised_train.iloc[:,0:456] ForestModels = {} ForestReg = {} for i in range(456,len(Supervised_train.columns)): ForestReg["Forest_{0}".format(i)] = RandomForestClassifier(n_estimators=100) y = Supervised_train.iloc[:,i] ForestModels["model_{0}".format(i)] = ForestReg["Forest_{0}".format(i)].fit(X, y) # Define function that maps def Map_to_Vectorizer(Text, Title): CleanText = TextCleaning(Text) CleanText = BaggingText(CleanText) CleanTitle = TextCleaning(Title) CleanTitle = BaggingText(CleanTitle) Bag = [] for i in range(len(CleanText)): if CleanText[i] not in stopwords.words('english'): Bag.append(CleanText[i]) for j in range(len(CleanTitle)): if CleanTitle[j] not in stopwords.words('english'): Bag.append(CleanTitle[j]) Count = [] for h in range(len(list(Count_Data.columns)[0:456])): Count.append(Bag.count(list(Count_Data.columns)[h])) Number = [] Number.append(Count) return Number, Bag # Define Tagging function def ForestLogit_Tagger(Title, Text): Test, Test_Bag = Map_to_Vectorizer(Title, Text) Test_Data = pd.DataFrame(data = Test,columns = list(Count_Data.columns)) Tags = [] for i in range(456,len(Supervised_Data.columns)): LogitVariableName = "Logit_" + str(Supervised_Data.columns[i]) ForestVariableName = "Forest_" + str(Supervised_Data.columns[i]) Test_Data[LogitVariableName] = LogitReg["Logit_{0}".format(i)].predict(Test_Data.iloc[:,:456]) Test_Data[ForestVariableName] = ForestReg["Forest_{0}".format(i)].predict(Test_Data.iloc[:,:456]) if Test_Data[LogitVariableName].iloc[0] > 0.4: Tags.append(Supervised_Data.columns[i]) if Test_Data[ForestVariableName].iloc[0] > 0.4: Tags.append(Supervised_Data.columns[i]) Tags = list(set(Tags)) return Tags import gradio as gr gr.Interface(fn=ForestLogit_Tagger, title="Generating Tags - Supervised", description="Cette API génère des tags en 'mappant' le texte dans l'espace des 500 features obtenu par le biais d'un Count Vectorizer, puis en en prédisant tour à tour si chacun des 187 tags les plus populaires doivent-être associé au texte. La fonction renvoie les tags associés à une prédiction positive.", inputs=["text","textbox"], outputs="textbox").launch()
# # A simple demonstration of using Bond for spying and mocking # an application for monitoring temperature and sending alerts # # See a full explanation of this example at # http://necula01.github.io/bond/example_heat.html # # rst_Start import time import re import urllib, urllib2 from bond import bond class HeatWatcher: """ Monitor temperature rise over time. See description in the Bond documentation. """ def __init__(self): self.last_temp = None # The last temp measurement self.last_time = None # The time when we took the last measurement self.last_alert_state = 'Ok' # Ok, Warning, Critical self.last_alert_time = float('-inf') # Time when we sent the last alert def monitor_loop(self, exit_time=None): """ Monitor the temperature and send alerts :param exit_time: the time when to exit the monitor loop. """ while True: temp = self.get_temperature() now = self.get_current_time() if exit_time is not None and now >= exit_time: return if self.last_temp is None: # First reading self.last_temp = temp self.last_time = now interval = 60 else: change_rate = (temp-self.last_temp) / (now-self.last_time) * 60 if change_rate < 1: interval = 60 alert_state = 'Ok' elif change_rate < 2: interval = 10 alert_state = 'Warning' else: interval = 10 alert_state = 'Critical' self.last_temp = temp self.last_time = now if (alert_state != self.last_alert_state or (alert_state != 'Ok' and now >= 600 + self.last_alert_time)): # Send an alert self.send_alert("{}: Temperature is rising at {:.1f} deg/min" .format(alert_state, change_rate)) self.last_alert_time = now self.last_alert_state = alert_state self.sleep(interval) # Spy this function, want to spy the result @bond.spy_point(spy_result=True, mock_only=True) def get_temperature(self): """ Read the temperature from a sensor """ resp_code, temp_data = \ self.make_request('http://system.server.com/temperature') assert resp_code == 200, 'Error while retrieving temperature!' match = re.search('<temperature>([0-9.]+)</temperature>', temp_data) assert match is not None, \ 'Error while parsing temperature from: {}'.format(temp_data) return float(match.group(1)) @bond.spy_point(mock_only=True) def get_current_time(self): """ Read the current time """ return time.time() @bond.spy_point() def sleep(self, seconds): """ Sleep a few seconds """ time.sleep(seconds) @bond.spy_point() def send_alert(self, message): """ Send an alert """ self.make_request('http://backend.server.com/messages', {'message': message}) @bond.spy_point(require_agent_result=True) def make_request(self, url, data=None): """ HTTP request (GET, or POST if the data is provided) """ resp = urllib2.urlopen(url, urllib.urlencode(data)) return (resp.getcode(), resp.read())
number = int(input("number : " )) factorial = 1 if number < 0: print("factorial of negative numbers is not calculated") elif number == 0: print("result = 1 ") else: for i in range(1,number + 1): factorial = factorial * i print("result = ", factorial)
from twython import Twython APP_KEY = "h0rZYPs6iDq4orLJzBLJ0iFYl" APP_SECRET = "y6A4U5QsfdIRzbbUNY493d696BmSVZdb4NPHRvPNp8jFpzduI4" twitter = Twython(APP_KEY, APP_SECRET, oauth_version=2) ACCESS_TOKEN = twitter.obtain_access_token() twitter = Twython(APP_KEY, access_token = ACCESS_TOKEN) tag = raw_input("Enter the term to search for-->") results = twitter.cursor(twitter.search, q=tag) target = open("TwittrSolrData.txt", 'a') #target = open("TwittrSolrData.txt", 'a') For appending to the file #number_of_tweets = raw_input("Enter the number of tweets that you want to collect-->") i = 0 key = raw_input("Enter the key-->") for result in results: #target.write(result) #target.write('\n') print result target.write(str(result[key]).encode("utf-8") + '\n') #target.write(str(result) + '\n') i = i+1 if (i > 4): break #print "File has been written to" twitter.disconnect() target.close()
# autor: zhumenger ''' 一.Message组件: 是Label组件的变体, 用于显示多行文本消息 可以自动换行,并调整文本的尺寸 ''' # 17_7_1.py # # from tkinter import * # # root = Tk() # # w1 = Message(root, text = "这是一则消息", width = 100) # w1.pack() # # w2 = Message(root, text = "我祈祷拥有一颗透明的心灵和会流泪的眼睛", width = 100) # w2.pack() # # mainloop() ''' 二.Spinbox组件: 是Enter组件的变体,用于从固定的值中选取一个, 可以通过范围或元组指定用户输入想内容 ''' # 17_7_2.py # # from tkinter import * # # root = Tk() # # # 设置范围 # w1 = Spinbox(root, from_ = 0, to = 10) # w1.pack() # # #通过元组设置内容 # w2 = Spinbox(root, value = ("one", "two", "three")) # w2.pack() # mainloop() ''' 三.PanedWindow组件 是一个空间管理组件,与frame组件类似,都是为组件提供一个框架 不过PanedWindow允许让用户调整应用程序的空间划分 ''' # 17_7_3.py # # from tkinter import * # # m = PanedWindow(orient = VERTICAL) #设置方向为垂直方向 # m.pack(fill = BOTH, expand = 1) # # top = Label(m, text = "top pane") # m.add(top) # # bottom = Label(m, text = "bottom pane") # m.add(bottom) # # mainloop() # 17_7_4.py 创建一个3个窗格的PanedWindow组件 # # from tkinter import * # # #各个窗格之间实际上是有一条看不见的线 # #可以通过设置showhandle = True让其显示出来 # m1 = PanedWindow(showhandle = True, sashrelief = SUNKEN) # m1.pack(fill = BOTH, expand = 1) # # left = Label(m1, text = "left pane") # m1.add(left) # # m2 = PanedWindow(orient = VERTICAL, showhandle = True, sashrelief = SUNKEN) # m1.add(m2) # # top = Label(m2, text = "top pane") # m2.add(top) # # bottom = Label(m2, text = "bottom pane") # m2.add(bottom) # # mainloop() ''' 四.Toplevel组件 1.独立的顶级窗口组件,类似与frame组件,但该组件拥有标题栏,边框等部件 该组件通常用在显示额外的窗口、对话框和其他弹出窗口中 2.可以通过设置attribute()这个方法,用于设置和获取窗口属性 如果只给出选项名,那么将返回当前窗口该选项的值 选项不支持关键字参数,需要在选项前加横线(-),并用字符串表示 用逗号(,)隔开选项和值 ''' # 17_7_5.py 创建一个顶级窗口 # # from tkinter import * # # root = Tk() # # def create(): # top = Toplevel() # top.title("I LOVE YOU!") # top.attributes('-alpha', 0.5) #将窗口设置为50%透明度 # # msg = Message(top, text = "I LOVE MYSELF!!!") # msg.pack() # # Button(root, text = "创建顶级窗口", command = create).pack() # # mainloop()
import math import numpy as np import random from constants import * from move import * class Human(): def human_turn(self,board_obj): board_obj.printBoard(board_obj) print("It's your turn," + HUMAN + ".Move to which place?") while(True): move = int(input()) row = int(move/3) col = int(move % 3) if board_obj.board[row][col] == EMPTY: board_obj.board[row][col] = HUMAN break else: print("That place is already filled.\nMove to which place?") continue class Agent(): def __init__(self): self.move_obj = Move() def agent_turn(self,board_obj,minimax_obj,bigtree_obj, depth_type=-1): board_obj.printBoard(board_obj) print(AGENT + " is moving please wait ...") r, c = self.move_obj.choose_optimal_move(board_obj, depth_type, minimax_obj, bigtree_obj) board_obj.board[r][c] = AGENT return r,c def agent_turn_ultimate(self,board_obj,previous_move): current_move = np.array(([-1,-1,-1,-1]), dtype=int) board_obj.printBoard(board_obj) print(AGENT + " is moving please wait ...") gr,gc,sr,sc = self.move_obj.choose_optimal_move_ultimate(board_obj,previous_move) temp_move=list() temp_move.extend([gr,gc,sr,sc]) current_move=temp_move board_obj.board[gr][gc][sr][sc] = AGENT return current_move
#!/usr/bin/env python3 # -*- coding: utf-8 -* """ COMS W4701 Artificial Intelligence - Programming Homework 2 An AI player for Othello. This is the template file that you need to complete and submit. @author: Shenzhi Zhang sz2695 """ import random import sys import time from heapq import heappush from heapq import heappop # You can use the functions in othello_shared to write your AI from othello_shared import find_lines, get_possible_moves, get_score, play_move def compute_utility(board, color): """ Computer the utility for color x. Dark tries to maximize the utility. Light tries to minimize the utility. """ score_board = [[20, -3, 11, 8, 8, 11, -3, 20], [-3, -7, -4, 1, 1, -4, -7, -3], [11, -4, 2, 2, 2, 2, -4, 11], [8, 1, 2, -3, -3, 2, 1, 8], [8, 1, 2, -3, -3, 2, 1, 8], [11, -4, 2, 2, 2, 2, -4, 11], [-3, -7, -4, 1, 1, -4, -7, -3], [20, -3, 11, 8, 8, 11, -3, 20]] utility = 0 for i in range(len(score_board)): for j in range(len(score_board)): if board[i][j] == color: utility = utility + score_board[i][j] elif board[i][j] != 0: utility = utility - score_board[i][j] return utility def other_color(color): """ A utility method to return the other color """ if color == 1: return 2 else: return 1 ############ ALPHA-BETA PRUNING ##################### def alphabeta_min_node(board, color, alpha, beta, level, limit): """ Method for min node using alpha beta pruning. If a terminal stage is reached, return current utility. Else recursively call method for max node on each possible move and do cutoffs/updates. """ if limit == level or len(get_possible_moves(board, other_color(color))) == 0: # terminal state return compute_utility(board, color) else: # order the child states ordered_states = [] for x in get_possible_moves(board, other_color(color)): # for every possible move of this min node next_board = play_move(board, other_color(color), x[0], x[1]) # get the result board of this move # put board state with maximum utility at the root of heap heappush(ordered_states, (compute_utility(next_board, color), next_board)) cur = float('inf') # keep record the min_max for this min node while(len(ordered_states) != 0): max_value = alphabeta_max_node(heappop(ordered_states)[1], color, alpha, beta, level + 1, limit) cur = min(cur, max_value) if (cur <= alpha): # min_max has dropped below parent max node's max_min value, cut off return cur beta = min(beta, cur) # update current min_max for this node return cur # cut off didn't occur, return min_max def alphabeta_max_node(board, color, alpha, beta, level, limit): """ Method for max node using alpha beta pruning. If a terminal stage is reached, return current utility. Else recursively call method for min node on each possible move and do cutoffs/updates. """ if level == limit or len(get_possible_moves(board, color)) == 0: # not cache limit level yet return compute_utility(board, color) else: ordered_states = [] for x in get_possible_moves(board, color): # for every possible move of this max node next_board = play_move(board, color, x[0], x[1]) # get the result board of this move heappush(ordered_states, (-1 * compute_utility(next_board, color), next_board)) cur = float('-inf') # keep record the max_min for this max node while(len(ordered_states) != 0): min_value = alphabeta_min_node(heappop(ordered_states)[1], color, alpha, beta, level + 1, limit) cur = max(cur, min_value) if cur >= beta: # max_min has reached above parent min node's min_max value, cut off return cur alpha = max(alpha, cur) # update current max_min for this node return cur # cut off didn't occur, return max_min def select_move_alphabeta(board, color): """ Given a board and a player color, decide on a move using ordinary minimax. The return value is a tuple of integers (i,j), where i is the column and j is the row on the board. """ result = [] cur = float('-inf') alpha = float('-inf') # initialize alpha and beta beta = float('inf') ordered_states = [] for x in get_possible_moves(board, color): # for every possible move of this max node next_board = play_move(board, color, x[0], x[1]) # get the result board of this move heappush(ordered_states, (-1 * compute_utility(next_board, color), next_board, x)) while(len(ordered_states) != 0): next_one = heappop(ordered_states) min_value = alphabeta_min_node(next_one[1], color, alpha, beta, 1, 6) # should be able to run 6 levels, 5 is safer if cur < min_value: cur = min_value result = [next_one[2][0], next_one[2][1]] # keep record of the move leads to max_min alpha = max(alpha, cur) return result[0], result[1] # return the recorded move #################################################### def run_ai(): """ This function establishes communication with the game manager. It first introduces itself and receives its color. Then it repeatedly receives the current score and current board state until the game is over. """ print("Joker") # First line is the name of this AI color = int(input()) # Then we read the color: 1 for dark (goes first), # 2 for light. while True: # This is the main loop # Read in the current game status, for example: # "SCORE 2 2" or "FINAL 33 31" if the game is over. # The first number is the score for player 1 (dark), the second for player 2 (light) next_input = input() status, dark_score_s, light_score_s = next_input.strip().split() dark_score = int(dark_score_s) light_score = int(light_score_s) if status == "FINAL": # Game is over. print else: board = eval(input()) # Read in the input and turn it into a Python # object. The format is a list of rows. The # squares in each row are represented by # 0 : empty square # 1 : dark disk (player 1) # 2 : light disk (player 2) # Select the move and send it to the manager movei, movej = select_move_alphabeta(board, color) # Use alphabeita print("{} {}".format(movei, movej)) if __name__ == "__main__": run_ai()
#!/usr/bin/env python #pyglatin project print ("Welcome to PygLatin") #def run(): original = raw_input("Enter a random word here: ") if len(original) > 0 and original.isalpha(): pyg = "ay" print (original[1:]) + (original[:1]) + pyg else: print ("invalid entry!!") #done
# This file contains all classes used in many features # If you add sth to this file feel free to add yourselves as authors # Authors: Oskar Domingos, Marceli Skorupski import json import sqlite3 from SalesFeature.Discounts.models import DiscountScheme class DB: """ This class has all methods related to Database handling. For now, there is no database, so all operations are performed on json file """ def __init__(self): self._db_name = 'Database.db' # Sales list holds every data related to sales self._sales = [] self.__fetch_sales() @staticmethod def initialize_db(db_name): """ It creates tables that are necessary to ensure that app will be working correctly :return: """ conn = sqlite3.connect(db_name) cursor = conn.cursor() # Create table for sales # cursor.execute('''CREATE TABLE IF NOT EXISTS sale( # id INTEGER PRIMARY KEY AUTOINCREMENT, # product_id INTEGER NOT NULL, # category_id INTEGER NOT NULL, # quantity INTEGER NOT NULL, # receipt_id INTEGER NOT NULL, # receipt_date TEXT # )''') # # # Create table for requests # cursor.execute('''CREATE TABLE IF NOT EXISTS request( # id INTEGER PRIMARY KEY AUTOINCREMENT, # replied_on INTEGER, # request_type TEXT, # user_id INTEGER, # content TEXT) # ''') # # # Create table for replies # cursor.execute('''CREATE TABLE IF NOT EXISTS request_reply( # id INTEGER PRIMARY KEY AUTOINCREMENT, # request_id INTEGER, # user_id INTEGER, # content TEXT) # ''') # # # Create table for discounts schemes # cursor.execute(''' # CREATE TABLE IF NOT EXISTS discount_scheme( # id INTEGER PRIMARY KEY, # details TEXT, # discount_percentage REAL) # ''') # Insert some data # Create users # cursor.execute('''INSERT INTO user(firstname, lastname, username, password) VALUES("John", "Doe", "johndoe", "johndoe1");''') # cursor.execute('''INSERT INTO user(firstname, lastname, username, password) VALUES("Alberto", "Rahim", "albi", "zaqtyui");''') # Create requests cursor.execute('''INSERT INTO request(request_type, user_id, content, replied_on) VALUES("review", 1, "This product is a crap", 0);''') cursor.execute('''INSERT INTO request(request_type, user_id, content, replied_on) VALUES("query", 2, "Can I have a refund?", 0);''') conn.commit() conn.close() def __fetch_sales(self): """ Author: Oskar Domingos It takes sales from file and wrap in appropriate data structure :return: """ with open('./Shared/sales.json', 'r') as file: self._sales = json.load(file) self._sales = self._sales['orders'] print(self._sales) # Map sales list to have appropriate fields for i in range(len(self._sales)): sale = self._sales[i] category = { "id": sale['category_id'], "name": sale['category_name'], } product = { "id": sale['product_id'], "name": sale['product_name'], "cost": sale['product_cost'], "category": category, } self._sales[i]['product'] = product self._sales[i]['category'] = category del self._sales[i]['product_id'] del self._sales[i]['product_name'] del self._sales[i]['product_cost'] del self._sales[i]['category_id'] del self._sales[i]['category_name'] def fetch_requests(self): """ Author: Oskar Domingos It takes requests from database and wrap in appropriate data structure :return list of requests which are dictionaries: """ conn = sqlite3.connect(self._db_name) cursor = conn.cursor() requests = [] for row in cursor.execute('''SELECT request.id, request.request_type, Users.username, Users.ID_number, request.content FROM request INNER JOIN Users ON request.user_id=Users.ID_number WHERE request.replied_on=0'''): request = { 'id': row[0], 'request_type': row[1], 'username': row[2], 'user_id': row[3], 'content': row[4], } requests.append(request) conn.close() return requests def add_request_reply(self, request, content): """ Author: Oskar Domingos It adds reply to a request :return: """ conn = sqlite3.connect(self._db_name) cursor = conn.cursor() cursor.execute( '''INSERT INTO request_reply(request_id, user_id, content) VALUES(?, ?, ?)''', (request.request_id, request.author.user_id, content,) ) cursor.execute( '''UPDATE request SET replied_on=1 WHERE id=?''', (request.request_id,) ) conn.commit() conn.close() return request.request_id def fetch_discounts_schemes(self): """ Author: Oskar Domingos It takes discount schemes from database and wrap in appropriate data structure :return list of discount schemes: """ conn = sqlite3.connect(self._db_name) cursor = conn.cursor() discounts_schemes = [] for row in cursor.execute('''SELECT discount_scheme.id, discount_scheme.details, discount_scheme.discount_percentage FROM discount_scheme'''): discounts_schemes.append(DiscountScheme( discount_scheme_id=row[0], details=row[1], discount_percentage=row[2], )) conn.close() return discounts_schemes def edit_discount_scheme(self, discount_scheme): """ Author: Oskar Domingos It edits discount scheme :param discount_scheme: :return: """ conn = sqlite3.connect(self._db_name) cursor = conn.cursor() cursor.execute( '''UPDATE discount_scheme SET details=?, discount_percentage=? WHERE id=?''', (discount_scheme.details, discount_scheme.discount_percentage, discount_scheme.discount_scheme_id) ) conn.commit() conn.close() def add_discount_scheme(self, discount_scheme): """ Author: Oskar Domingos :param discount_scheme: :return: """ conn = sqlite3.connect(self._db_name) cursor = conn.cursor() # Check if record with that id already exists cursor.execute('''SELECT id FROM discount_scheme WHERE id=?''', (discount_scheme.discount_scheme_id,)) result = cursor.fetchone() print(result) if result is not None: return False else: cursor.execute( '''INSERT INTO discount_scheme(id, details, discount_percentage) VALUES(?,?,?)''', (discount_scheme.discount_scheme_id, discount_scheme.details, discount_scheme.discount_percentage) ) conn.commit() conn.close() return True def remove_discount_scheme(self, discount_scheme): """ Author: Oskar Domingos IT removes discount scheme from database :param discount_scheme: :return: """ conn = sqlite3.connect(self._db_name) cursor = conn.cursor() cursor.execute( '''DELETE FROM discount_scheme WHERE id=?''', (discount_scheme.discount_scheme_id,) ) conn.commit() conn.close() def SetMaxPos(self, tbl): conn = self.create_connection() cur = conn.cursor() maxpos = 0 if tbl == 'Products': cur.execute('SELECT * FROM Products ') res = cur.fetchall() # print(res) for rec in res: maxpos = maxpos + 1 self.close_connection(conn) return maxpos elif tbl == 'Categories': cur.execute('SELECT * FROM Categories') res = cur.fetchall() # print(res) for rec in res: maxpos = maxpos + 1 self.close_connection(conn) return maxpos def FetchData(self, pos, tbl): conn = self.create_connection() cur = conn.cursor() if tbl == 'Products': cur.execute("SELECT rowid, * FROM Products WHERE rowid = '%s' " % pos) todisplay = cur.fetchall() self.close_connection(conn) return (todisplay[0])[1:] elif tbl == 'Categories': cur.execute("SELECT rowid, * FROM Categories WHERE rowid = '%s' " % pos) todisplay = cur.fetchall() self.close_connection(conn) return (todisplay[0])[1:] def del_record(self, position, tbl): conn = self.create_connection() cur = conn.cursor() if tbl == 'Products': cur.execute(' Delete from Products WHERE Product_code = (?) ', position) cur.execute("CREATE TABLE Products_Temp AS SELECT * FROM Products") cur.execute("DELETE FROM Products") cur.execute("DELETE FROM sqlite_sequence WHERE name='Products.'") cur.execute("INSERT INTO Products SELECT * FROM Products_Temp") cur.execute("DROP TABLE Products_Temp") self.close_connection(conn) elif tbl == 'Categories': cur.execute('Delete from Categories WHERE Cat_Code = (?) ', position) cur.execute("CREATE TABLE Categories_Temp AS SELECT * FROM Categories") cur.execute("DELETE FROM Categories") cur.execute("DELETE FROM sqlite_sequence WHERE name='Categories'") cur.execute(" INSERT INTO Categories (name) SELECT name FROM Categories_Temp") cur.execute("DROP TABLE Categories_Temp") self.close_connection(conn) def login_check(self, username, password): UNPS = [(username, password)] conn = self.create_connection() cur = conn.cursor() cur.execute('SELECT username, password FROM Users ') result = cur.fetchall() # print(result) for row in result: # print(row) if row == UNPS[0]: final = True else: final = False self.close_connection(conn) return final def fetchvaluesCatName(self): conn = self.create_connection() cur = conn.cursor() values = [] cur.execute('SELECT name FROM Categories') result = cur.fetchall() for row in result: # print(row) for item in row: # print(item) values.append(item) # print(values) self.close_connection(conn) return values def save(self, table, newid, newname, newdesc, newcatcode, newqty): conn = self.create_connection() cur = conn.cursor() cur.execute(""" INSERT OR REPLACE INTO Products VALUES (? , ? , ? , ? , ?)""", (newid, newname, newdesc, newcatcode, newqty)) cur.execute("CREATE TABLE Products_Temp AS SELECT * FROM Products") cur.execute("DELETE FROM Products") cur.execute("DELETE FROM sqlite_sequence WHERE name='Products'") cur.execute("INSERT INTO Products SELECT * FROM Products_Temp") cur.execute("DROP TABLE Products_Temp") self.close_connection(conn) def saveCat(self, table, newid, newname): conn = self.create_connection() cur = conn.cursor() cur.execute(""" INSERT OR REPLACE INTO Categories VALUES (? , ? )""", (newid, newname,)) cur.execute("CREATE TABLE Categories_Temp AS SELECT * FROM Categories") cur.execute("DELETE FROM Categories") cur.execute("DELETE FROM sqlite_sequence WHERE name='Categories'") cur.execute(" INSERT INTO Categories (name) SELECT name FROM Categories_Temp") # cur.execute("INSERT INTO Categories SELECT * FROM Categories_Temp") cur.execute("DROP TABLE Categories_Temp") self.close_connection(conn) def set_rec_pos(self, recid, table): conn = self.create_connection() cur = conn.cursor() if table == 'Categories': cur.execute("SELECT rowid, * FROM Categories WHERE Cat_Code = {0} ".format(recid)) newpos_ = cur.fetchall() self.close_connection(conn) elif table == 'Products': cur.execute("SELECT rowid, * FROM Products WHERE Product_Code = {0} ".format(recid)) newpos_ = cur.fetchall() self.close_connection(conn) return ((newpos_[0])[0]) def setSRdata(self): conn = self.create_connection() cur = conn.cursor() cur.execute('SELECT * FROM Products ') SRdict = cur.fetchall() # print(SRdict) return SRdict def setLSData(self): conn = self.create_connection() cur = conn.cursor() cur.execute("SELECT * FROM Products WHERE Qty <= 5 ") LSDict = cur.fetchall() return LSDict def LoworNot(self): conn = self.create_connection() cur = conn.cursor() cur.execute("SELECT * FROM Products WHERE Qty <= 5 ") LSDict = cur.fetchall() if LSDict == []: return False else: return True # Connect def create_connection(self,): conn = sqlite3.connect('Database.db') return conn def close_connection(self, conn): conn.commit() conn.close() @property def sales(self): return self._sales class Authentication: def __init__(self): self.is_authenticated = False self.token = None self.db = DB() def login(self, username, password): # It logs in the user is_correct = self.db.check_password(username, password) if is_correct: print('user is logged in') else: print('Incorect credentials!')
# required modules from turtle import * from random import randint # classic shape turtle speed(0) penup() goto(-140, 140) # racing track for step in range(15): write(step, align='center') right(90) for num in range(8): penup() forward(10) pendown() forward(10) penup() backward(160) left(90) forward(20) # first player details player_1 = Turtle() player_1.color('red') player_1.shape('turtle') # first player proceeds to racing track player_1.penup() player_1.goto(-160, 100) player_1.pendown() # 360 degree turn for turn in range(10): player_1.right(36) # second player details player_2 = Turtle() player_2.color('blue') player_2.shape('turtle') # second player enters in the racing track player_2.penup() player_2.goto(-160, 70) player_2.pendown() # 360 degree turn for turn in range(72): player_2.left(5) # third player details player_3 = Turtle() player_3.shape('turtle') player_3.color('green') # third player enters in the racing track player_3.penup() player_3.goto(-160, 40) player_3.pendown() # 360 degree turn for turn in range(60): player_3.right(6) # fourth player details player_4 = Turtle() player_4.shape('turtle') player_4.color('orange') # fourth player enters in the racing track player_4.penup() player_4.goto(-160, 10) player_4.pendown() # 360 degree turn for turn in range(30): player_4.left(12) # turtles run at random speeds for turn in range(100): player_1.forward(randint(1,5)) player_2.forward(randint(1,5)) player_3.forward(randint(1,5)) player_4.forward(randint(1,5))
from src.tool.struct import ListNode class Solution: def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode: my_head = ListNode(0) my_head.next = head next_node = my_head tmp_list = [] while next_node: tmp_list.append(next_node) if len(tmp_list) > n + 1: tmp_list.pop(0) next_node = next_node.next tmp_list[0].next = tmp_list[1].next return my_head.next def removeNthFromEnd1(self, head: ListNode, n: int) -> ListNode: my_head = ListNode(0) my_head.next = head next_node = my_head # 使用指针加固定长度数组 模拟队列 queue_len = n + 1 tmp_list = [None] * queue_len cur = 0 while next_node: tmp_list[cur % queue_len] = next_node next_node = next_node.next cur += 1 tmp_list[cur % queue_len].next = tmp_list[(cur + 1) % queue_len].next return my_head.next if __name__ == '__main__': node1 = ListNode(1) node2 = ListNode(2) node1.next = node2 print(node1) s = Solution() res = s.removeNthFromEnd1(node1, 2) print(res)
class Solution: def threeSumClosest(self, nums, target): len_nums = len(nums) if len_nums < 3: return 0 # sort nums.sort() closest = 2**31 - 1 result = None for i in range(len_nums-2): left = i + 1 right = len_nums - 1 while left < right: cur_sum = nums[i] + nums[left] + nums[right] cur_dis = abs(target - cur_sum) if cur_dis < closest: result = cur_sum closest = cur_dis if cur_sum < target: left += 1 elif cur_sum > target: right -= 1 else: return result return result if __name__ == "__main__": obj = Solution() result_ = obj.threeSumClosest([1, -1, 2, 4], 1) print(result_)
from src.tool.struct import TreeNode class Solution: def isValidBST(self, root: TreeNode) -> bool: if root is None: return True def is_valid_bst(node: TreeNode, left=None, right=None): if node is None: return True if left is not None and node.val <= left: return False if right is not None and node.val >= right: return False return is_valid_bst(node.left, left, node.val) and is_valid_bst(node.right, node.val, right) return is_valid_bst(root)
from src.tool.struct import ListNode class Solution: def middleNode(self, head: ListNode) -> ListNode or None: if not head: return None mid = cur = head count = 1 while cur.next: cur = cur.next count += 1 if count & 1 == 0: mid = mid.next return mid
class Stack: def __init__(self): self.__stack = [] self.__min_stack = [] def push(self, value): self.__stack = self.__stack + [value] if len(self.__min_stack) == 0: self.__min_stack = self.__min_stack + [value] elif self.__min_stack[len(self.__min_stack) - 1] > value: self.__min_stack = self.__min_stack + [value] else: self.__min_stack = \ self.__min_stack + [self.__min_stack[len(self.__min_stack)-1]] def pop(self): if len(self.__stack) == 0: return None else: self.__min_stack.pop() return self.__stack.pop() def min(self): return self.__min_stack[len(self.__min_stack) - 1] if __name__ == "__main__": stack = Stack() stack.push(200) stack.push(100) stack.push(300) stack.push(30) min = stack.min() print("Min:"+str(min)) value = stack.pop() print("Pop Value:"+str(value)) min = stack.min() print("Min(after pop()):"+str(min)) print("Pop Value:"+ str(stack.pop())) print("Pop Value:"+ str(stack.pop())) print("Min(after pop() 2:"+ str(stack.pop()))
class Node: def __init__(self, data): self.__data = data self.__next = None def get_next(self): return self.__next def set_next(self, next): self.__next = next def set_data(self, data): return self.__data def get_data(self): return self.__data next = property(get_next, set_next) data = property(get_data, set_data) class List: def __init__(self): self.__head = None def set_head(self, head): self.__head = head def get_head(self): return self.__head def deduplicate(self): list = List() node_prev = None node = self.head node_hash = {} while node != None: if not node.data in node_hash: node_hash[node.data] = True node_created = Node(node.data) if list.head == None: list.head = node_created node_prev = node_created node = node.next return list head = property(get_head, set_head) if __name__ == "__main__": list = List() node = Node("test1") list.set_head(node) node2 = Node("test") node.next = node2 node3 = Node("test") node2.next = node3 node = list.head while node != None: print(node.data) node = node.next list_a = list.deduplicate() node = list_a.head print("******") while node != None: print(node.data) node = node.next
#josephus problem in mathematics #we are doing the modular counting ! import string def remove_matching_letter(l1,l2): for i in range(len(l1)): for j in range (len(l2)): if (l1[i]==l2[j]): c=l1[i] l1.remove(c) l2.remove(c) l=l1+['*']+l2 return[l,True] l=l1+['*']+l2 return[l,False] print("***** F L A M E S *****") #person1 p1=input("first person name: ") p1=p1.lower() p1=p1.replace(" ","") #person2 p2=input("second person name :") p2=p2.lower() p2=p2.replace(" ","") #listng l1=list(p1) l2=list(p2) #flag based programming proceed = True while proceed: ret_list=remove_matching_letter(l1,l2) con_list=ret_list[0] proceed=ret_list[1] star_index=con_list.index('*') l1=con_list[:star_index] l2=con_list[star_index+1:] count=len(l1)+len(l2) #print(count) result=['Friends','Love','Affection','Marriage','Enemy','Sibling'] #modular counting implementation split_index=(count%len(result))-1 #if this pointer is stuck at ends then it takes -ve value #if this pointer is stuck in the middle then it take a +ve value #both the cases are handled separately while(len(result)>1): if(split_index>0): right=result[split_index+1:] left=result[:split_index] result=right+left else: result=result[:len(result)-1] print(*result)
from funcs import * def main(): letters = input() words = input().split() rows = get_rows(letters) #rows is basically the puzzle columns = get_columns(letters) backwards = ''.join([row[::-1] for row in rows]) upwards = ''.join([column[::-1] for column in columns]) print('Puzzle: ') print() for row in rows: print(row) print() #diagonal = check_diagonal(rows, columns, word) for word in words: forward = check_forward(rows, word) backward = check_backward(rows, word) downward = check_downward(columns, word) upward = check_upward(columns, word) diagonal = check_diagonal(rows, word) if check_forward(rows, word) != False: print('%s: (%s) row: %s column: %s ' % (word,forward[1],letters.find(word)//10,forward[0])) elif check_backward(rows, word) != False: print('%s: (%s) row: %s column: %s ' % (word,backward[1],backwards.find(word)//10,9-backward[0])) elif check_downward(columns, word) != False: print('%s: (%s) row: %s column: %s ' % (word,downward[1],downward[0],''.join(columns).find(word)//10)) elif check_upward(columns, word) != False: print('%s: (%s) row: %s column: %s' % (word,upward[1],9-upward[0],upwards.find(word)//10)) elif check_diagonal(rows, word) != False: print('%s: (%s) row: %s column: %s' % (word,diagonal[2],diagonal[0],diagonal[1])) else: print('%s: word not found' % (word)) if __name__ == '__main__': main()
# dict d = {'one':1, 'two':2} #{key:value, key:value} print(d['one']) print(type(d)) print(dir(d)) print(d.values()) print(d.keys()) print(d.items()) ''' 1. dict 안에는 다른 object 들이 들어갈 수 있다. 2. 값(주소값)을 변화시킬 수 없습니다. 3. 순서가 있습니다. 참고. dict를 JSON 형식으로 쓰기도 함 '''
# -*- coding: utf-8 -*- #WhileLoop counter = 5; while counter > 0: print ("Broiach = ", counter) counter = counter - 1 #Break and continue j = 0; for i in range(5): #range (start, end, step) j = j + 2 print ('i = ', i, ', j = ', j) if j == 4: continue print("I will be skipped over if j = 4") if j == 6: break #Use try to display errors
# Given a list of integers and a single sum value, return the first two values (parse from the left please) in order of appearance that add up to form the sum. # Ex: [1, 4, 8, 7, 3, 15], 8 => [1, 7] # def sum_pairs(ints, s): # ints_set = set(ints) # result = s # return_arr = [] # for x in ints: # diff = result - x # if diff in ints_set: # return_arr.append(x) # return_arr.append(diff) # print return_arr # return return_arr # else: # return None from itertools import combinations def sum_pairs(ints, s): return [pair[0] for pair in combinations(ints, 2) if sum(pair) == s] sum_pairs([1, 4, 8, 7, 3, 15], 8)
def candies(s): if len(s) <= 1: return -1 else: s.sort() base = s[-1] total = 0 for x in s: if x < base: diff = base - x total += diff print total return total candies([5,8,6,4])
# Importing all the libraries import numpy as np import copy import math import heapq import time import matplotlib.pyplot as plt import cv2 import pygame # %% # wheel dia = 76mm # full robot dia = 354 mm # distance between the wheels = 317.5mm # clearance = can be given by the user = 5 mm # for solving the path using eucledian heuristic # Getting the start time to measure the time taken for solving ####################User Inputs###################### print(' WELCOME TO THE A * PROGRAMME ') print('THIS PROGRAMME TAKES THE USER INPUTS BELOW AND SOLVES THE OBSTACLE SPACE VERY QUICKLY') print('time taken (for A* solving) ~ <1 second') print( 'To solve the necessary test cases, please know that the start and the goal points here are adjusted based on the clearance and the width of the robot') print('This avoids the goal or the start getting into the borders or any obstacles') print('For the turtle bot, this value is fixed at 35') print('If you wish to change this value, please rerun the code after doing so.') print('ALSO !! NOTE !!, the coordinates of the obstacle points have been multiplied by a factor of 100') print( 'This ensures a clearer graph. Hence, please multiply by a factor of 100, before input. For example: 5.5 will be = 5.5*100 = 550') print('Range of x coordinates you can enter = 0 - 1020') print('Range of y coordinates you can enter = 0 - 1020') x_start, y_start, start_orientation = input("Enter the x and y coordinate of the start and the initial orientation here, with a blank in between them (suggested : 10 10 30) : > ").split() x_goal, y_goal = input("Enter the x and y coordinate of the goal and the , in the form of blanks (suggested : 1010 1010) : > ").split() RPM_L, RPM_R = input("Enter the LEFT WHEEL RPM AND RIGHT WHEEL RPM : > ").split() clearance = int(input("Enter the clearance of the robot with the nearby obstacles : (suggested value < 5) : > ")) step_size = int(input("Enter the step (1-10): (suggested values = 1) : > ")) radius = 0.5 start = (int(x_start) + radius + clearance, int(y_start) + radius + clearance) goal = (int(x_goal) - radius - clearance, int(y_goal) - radius - clearance) print('Wheel radius is calculated to be 76mm/2 -> approximating to 0.5') time_run = int(input(('Please enter the time you wish to choose to run the robot ((suggested value = 1 second) : '))) start_orientation = int(start_orientation) RPM_L = int(RPM_L) RPM_R = int(RPM_R) print('Please wait while the map is being generated. Approximate wait time < 5 seconds . ') # %% # function to round the point 5 def Round2Point5(num): return (round(num * 2) / 2) def RoundToFifteen(x, base=15): return base * round(x / base) # for solving the path using eucledian heuristic def EucledianDistance(a, b): x1 = a[0] x2 = b[0] y1 = a[1] y2 = b[1] dist = math.sqrt((x2 - x1) ** 2 + (y2 - y1) ** 2) dist = Round2Point5(dist) return dist def plot_curve(X0, Y0, Theta0, UL, UR): global time_run t = 0 r = 0.5 L = 3.5 dt = 0.1 X1 = 0 Y1 = 0 dtheta = 0 Theta0 = 3.14 * Theta0 / 180 Theta1 = Theta0 while t < time_run: t = t + dt X0 = X0 + X1 Y0 = Y0 + Y1 dx = r * (UL + UR) * math.cos(Theta1) * dt dy = r * (UL + UR) * math.sin(Theta1) * dt dtheta = (r / L) * (UR - UL) * dt X1 = X1 + dx Y1 = Y1 + dy Theta1 = Theta1 + 0.5 * dtheta plt.quiver(X0, Y0, X1, Y1, units='xy', scale=1, color='r', width=1, headwidth=1, headlength=0) Xn = X0 + X1 Yn = Y0 + Y1 Thetan = 180 * (Theta1) / 3.14 return Xn, Yn, Thetan # can use manhattan or eucledian heuristic as for caclulation of the value of cost to go to the goal. ##### # function to move # Possible motions : # [0, RPM1] # [RPM1, 0] # [RPM1, RPM1] # [0, RPM2] # [RPM2, 0] # [RPM2, RPM2] # [RPM1, RPM2] # [RPM2, RPM1] # inding neighbours using the non-holonomic drive conditions # fucntion finds the immediete neighbour to which the robot drives to def ActionMove(curr_node, orientation_facing, RPM_L, RPM_R, d=1.0, L=3.5, step_size=1.0): global time_run curr_start_x = curr_node[0] curr_start_y = curr_node[1] r = d / 2 # radius = dia / 2 t = 0 dt = 0.1 X1 = 0 Y1 = 0 dtheta = 0 # x_new, y_new, new_orientation = GoTo(x,y,degree,RPM_L,RPM_R) orientation_facing_RADIANS = 3.14 * orientation_facing / 180 while t < time_run: t = t + dt curr_start_x = curr_start_x + X1 curr_start_y = curr_start_y + Y1 dx = r * (RPM_L + RPM_R) * math.cos(orientation_facing_RADIANS) * dt dy = r * (RPM_L + RPM_R) * math.sin(orientation_facing_RADIANS) * dt dtheta = (r / L) * (RPM_R - RPM_L) * dt X1 = X1 + dx Y1 = Y1 + dy orientation_facing_RADIANS = orientation_facing_RADIANS + 0.5 * dtheta new_x = curr_start_x + X1 new_y = curr_start_y + Y1 new_final_orientation = 180 * (orientation_facing_RADIANS) / 3.14 # calculating the degrees rotated from the start to the new orientation and assigning costs accordingly degrees_rotated = abs(orientation_facing - new_final_orientation) degrees_rotated = abs(degrees_rotated % 360) cost = 10 + (10 * degrees_rotated / 360) # new_final_orientation = round(new_final_orientation,2) new_final_orientation = RoundToFifteen(new_final_orientation) new_node = ((round(new_x, 2), round(new_y, 2)), new_final_orientation, cost) same_out = (curr_node, orientation_facing, 100000) if 0.00 <= new_node[0][0] <= 1020.00 and 0.00 <= new_node[0][1] <= 1020.00: return new_node, True else: return same_out, False # %% ###################################### POINTS FOR REMOVING VALUES FROM THE GRAPH # calculating all the points within the entire canvas # all possible points in integer format all_possible_int_points = [] # points to draw the map, without considering the radius and clearance of the robot. This works with # different sets of points as compared to the points created untraversable_points = [] # SCALING all by 100 times for i in range(0, 1021): # 1020 width for j in range(0, 1021): # 1020 width all_possible_int_points.append((i, j)) # appending for pt in all_possible_int_points: x = pt[0] y = pt[1] # circle shaped obstacles # circle shaped obstacle at the center of the image # for path traversal if (x - 510) ** 2 + (y - 510) ** 2 <= (100 + radius + clearance) ** 2: untraversable_points.append((x, y)) # circle shaped obstacle on top right # for path traversal if (x - 710) ** 2 + (y - 810) ** 2 <= (100 + radius + clearance) ** 2: untraversable_points.append((x, y)) # circle shaped obstacle on bottom right # for path traversal if (x - 710) ** 2 + (y - 210) ** 2 <= (100 + radius + clearance) ** 2: untraversable_points.append((x, y)) # circle shaped obstacle on bottom left # for path traversal if (x - 310) ** 2 + (y - 210) ** 2 <= (100 + radius + clearance) ** 2: untraversable_points.append((x, y)) # borders # left vertical border if 0 < x < 10 + radius + clearance: if 0 < y < 1020: untraversable_points.append((x, y)) # right vertical border if 1010 - radius - clearance < x < 1020: if 0 < y < 1020: untraversable_points.append((x, y)) # bottom horizontal border if 10 < x < 1010: if 0 < y < 10 + radius + clearance: untraversable_points.append((x, y)) # top horizontal border if 10 < x < 1010: if 1010 - radius - clearance < y < 1020: untraversable_points.append((x, y)) # squares # left square if 35 - radius - clearance <= x <= 185 + radius + clearance: if 435 - radius - clearance <= y <= 585 + radius + clearance: untraversable_points.append((x, y)) # right square if 835 - radius - clearance <= x <= 985 + radius + clearance: if 435 - radius - clearance <= y <= 585 + radius + clearance: untraversable_points.append((x, y)) # top left square if 235 - radius - clearance <= x <= 385 + radius + clearance: if 735 - radius - clearance <= y <= 885 + radius + clearance: untraversable_points.append((x, y)) # POINTS FOR DRAWING THE GRAPH # all possible points in integer format all_possible_int_points = [] # points to draw the map, without considering the radius and clearance of the robot. This works with # different sets of points as compared to the points created map_points = [] # SCALING all by 100 times for i in range(0, 1020): # 1020 width for j in range(0, 1020): # 1020 width all_possible_int_points.append((i, j)) # appending for pt in all_possible_int_points: x = pt[0] y = pt[1] # circle shaped obstacles # circle shaped obstacle at the center of the image # for path traversal if (x - 510) ** 2 + (y - 510) ** 2 <= 100 ** 2: map_points.append((x, y)) # circle shaped obstacle on top right # for path traversal if (x - 710) ** 2 + (y - 810) ** 2 <= 100 ** 2: map_points.append((x, y)) # circle shaped obstacle on bottom right # for path traversal if (x - 710) ** 2 + (y - 210) ** 2 <= 100 ** 2: map_points.append((x, y)) # circle shaped obstacle on bottom left # for path traversal if (x - 310) ** 2 + (y - 210) ** 2 <= 100 ** 2: map_points.append((x, y)) # borders # left vertical border if 0 < x < 10: if 0 < y < 1020: map_points.append((x, y)) # right vertical border if 1010 < x < 1020: if 0 < y < 1020: map_points.append((x, y)) # bottom horizontal border if 10 < x < 1010: if 0 < y < 10: map_points.append((x, y)) # top horizontal border if 10 < x < 1010: if 1010 < y < 1020: map_points.append((x, y)) # squares # left square if 35 <= x <= 185: if 435 <= y <= 585: map_points.append((x, y)) # right square if 835 <= x <= 985: if 435 <= y <= 585: map_points.append((x, y)) # top left square if 235 <= x <= 385: if 735 <= y <= 885: map_points.append((x, y)) # defining a blank canvas new_canvas = np.zeros((1020, 1020, 3), np.uint8) # for every point that belongs within the obstacle for c in map_points: # change the name of the variable l x = c[1] y = c[0] new_canvas[(x, y)] = [20, 125, 150] # assigning a yellow coloured pixel # flipping the image for correct orientation new_canvas = np.flipud(new_canvas) # showing the obstacle map cv2.imshow(' < OBSTACLE SPACE MAP > ', new_canvas) cv2.waitKey(0) cv2.destroyAllWindows() print('Please wait while your solution is being calculated . ') print('Time taken on a high end Personal Computer ~ < 1 second') print('This will generate a map with solution, backtracked path, quiver plot and an animation too! ') print('!!! NOTE: Quiver plot will take an additional 10 seconds to calculate ') ##################function to check if any point is within the obstacle space################# # including the region covered by the robot radius and its clearance # %% def checkObstaclespace(point): global radius global clearance x = point[0] y = point[1] # circle shaped obstacles # circle shaped obstacle at the center of the image # for path traversal if (x - 510) ** 2 + (y - 510) ** 2 <= (100 + radius + clearance) ** 2: # print('THIS POINT IS INSIDE : > circle shaped obstacle at the center') return False # circle shaped obstacle on top right # for path traversal elif (x - 710) ** 2 + (y - 810) ** 2 <= (100 + radius + clearance) ** 2: # print('THIS POINT IS INSIDE : > circle shaped obstacle on top right') return False # circle shaped obstacle on bottom right # for path traversal elif (x - 710) ** 2 + (y - 210) ** 2 <= (100 + radius + clearance) ** 2: # print('THIS POINT IS INSIDE : > circle shaped obstacle on bottom right') return False # circle shaped obstacle on bottom left # for path traversal elif (x - 310) ** 2 + (y - 210) ** 2 <= (100 + radius + clearance) ** 2: # print('THIS POINT IS INSIDE : > circle shaped obstacle on bottom right') return False # borders # left vertical border elif 0 < x < 10 + radius + clearance: # print('THIS POINT IS INSIDE : > left vertical border') if 0 < y < 1020: return False # right vertical border elif 1010 - radius - clearance < x < 1020: # print('THIS POINT IS INSIDE : > right vertical border') if 0 < y < 1020: return False # bottom horizontal border elif 10 < x < 1010 and 0 < y < 10 + radius + clearance: if i <= size_x and j <= size_y and i >= 0 and j >= 0: # print('THIS POINT IS INSIDE : > bottom horizontal border') return False # top horizontal border elif 10 < x < 1010 and 1010 - radius - clearance < y < 1020: if 735 <= y <= 885: # print('THIS POINT IS INSIDE : > top horizontal border') return False # squares # left square elif 35 - radius - clearance <= x <= 185 + radius + clearance and 435 - radius - clearance <= y <= 585 + radius + clearance: # print('THIS POINT IS INSIDE : > left square') return False # right square elif 835 - radius - clearance <= x <= 985 + radius + clearance and 435 - radius - clearance <= y <= 585 + radius + clearance: # print('THIS POINT IS INSIDE : > right square') return False # top left square elif 235 - radius - clearance <= x <= 385 + radius + clearance and 735 - radius - clearance <= y <= 885 + radius + clearance: # print('THIS POINT IS INSIDE : > top left square') return False else: return True # %% # showing what every child node of each parent nodes are connected to list_of_points_for_graph = [] size_x, size_y = 1021, 1021 def generateGraph(point, degree, step_size=1): # remember that this size_x and size_y are the sizes of the matrix, so not the end coordinates global list_of_points_for_graph global size_x global size_y global RPM_R global RPM_L i = point[0] # x coordinate j = point[1] # y coordinate if i <= size_x and j <= size_y and i >= 0 and j >= 0: all_neighbours = {} pos1 = ActionMove(point, degree, 0, RPM_L)[0] pos2 = ActionMove(point, degree, RPM_L, 0)[0] pos3 = ActionMove(point, degree, RPM_L, RPM_L)[0] pos4 = ActionMove(point, degree, 0, RPM_R)[0] pos5 = ActionMove(point, degree, RPM_R, 0)[0] pos6 = ActionMove(point, degree, RPM_R, RPM_R)[0] pos7 = ActionMove(point, degree, RPM_L, RPM_R)[0] pos8 = ActionMove(point, degree, RPM_R, RPM_L)[0] if pos1[0][0] >= 0 and pos1[0][1] >= 0 and pos1[0][0] <= size_x and pos1[0][1] <= size_y: all_neighbours[pos1[0]] = (round(pos1[2], 2), pos1[1]) if pos2[0][0] >= 0 and pos2[0][1] >= 0 and pos2[0][0] <= size_x and pos2[0][1] <= size_y: all_neighbours[pos2[0]] = (round(pos2[2], 2), pos2[1]) if pos3[0][0] >= 0 and pos3[0][1] >= 0 and pos3[0][0] <= size_x and pos3[0][1] <= size_y: all_neighbours[pos3[0]] = (round(pos3[2], 2), pos3[1]) if pos4[0][0] >= 0 and pos4[0][1] >= 0 and pos4[0][0] <= size_x and pos4[0][1] <= size_y: all_neighbours[pos1[0]] = (round(pos4[2], 2), pos4[1]) if pos5[0][0] >= 0 and pos5[0][1] >= 0 and pos5[0][0] <= size_x and pos5[0][1] <= size_y: all_neighbours[pos5[0]] = (round(pos5[2], 2), pos5[1]) if pos6[0][0] >= 0 and pos6[0][1] >= 0 and pos6[0][0] <= size_x and pos6[0][1] <= size_y: all_neighbours[pos6[0]] = (round(pos6[2], 2), pos6[1]) if pos7[0][0] >= 0 and pos7[0][1] >= 0 and pos7[0][0] <= size_x and pos7[0][1] <= size_y: all_neighbours[pos7[0]] = (round(pos7[2], 2), pos7[1]) if pos8[0][0] >= 0 and pos8[0][1] >= 0 and pos8[0][0] <= size_x and pos8[0][1] <= size_y: all_neighbours[pos8[0]] = (round(pos8[2], 2), pos8[1]) return all_neighbours else: pass # %% # function to backtrack so that the path from the goal to the end is obtained point_and_angle_list = [] def BackTrack(backtrack_dict, goal, start): # goal is the starting point now and start is the goal point now # initializing the backtracked list back_track_list = [] # appending the start variable to the back_track_list list back_track_list.append(start) # while the goal is not found while goal != []: # for key and values in the backtracking dictionary for k, v in backtracking_dict.items(): # for the key and values in the values, v for k2, v2 in v.items(): # checking if the first key is the start if k == start: # checking if not in the backtrackedlist if v2[0] not in back_track_list: back_track_list.append(start) point_and_angle_list.append((start, v2[1])) # updating the start variable start = v2[0] # checking if it is the goal if v2[0] == goal: goal = [] break # returns the backtracked list return (back_track_list) ######### < < < < A* algorithm code > > > > ######### # %% # empty dictionary for backtracking from child to parent upto the start backtracking = {} # list of all the visited nodes visited = set() global orientation_to_layer # Mapping of Angles to layers orientation_to_layer = {0: 0, 15: 1, 30: 2, 45: 3, 60: 4, 75: 5, 90: 6, 105: 7, 120: 8, 135: 9, 150: 10, 165: 11, 180: 12, 195: 13, 210: 14, 225: 15, 240: 16, 255: 17, 270: 18, 285: 19, 300: 20, 315: 21, 330: 22, 345: 23, 360: 24} # array to store cost from # creating a 200rows, by 300 column by 12 layers for the various costs and to check if a node is visited cost_from = np.array(np.ones((2041, 2041, 24)) * np.inf) # Initializing visited nodes as empty array V = np.zeros((2041, 2041, 24)) # array to store Heuristic distance heur = np.array(np.ones((2041, 2041)) * np.inf) # array to store total cost f f = np.array(np.ones((2041, 2041, 24)) * np.inf) # list for Explored nodes priority_queue = [] # append start point,start orientation of the bot and initialize it's cost to zero heapq.heappush(priority_queue, (0, start, start_orientation)) # initialize cost for start node to zero cost_from[int(2 * start[0])][int(2 * start[1])][orientation_to_layer[start_orientation]] = 0 f[int(2 * start[0])][int(2 * start[1])][orientation_to_layer[start_orientation]] = 0 ######### < < < < A* algorithm code > > > > ######### def a_star_Algorithm(start, goal): global step_size global untraversable_points global V break_while = 0 # create a dictionary for backtracked parents backtracking = {} # check if goal/start in obstacle space if goal in untraversable_points or start in untraversable_points: print('!!!!!!!!!!GOAL/START IS INSIDE OBSTACLE SPACE!!!!!!!!!!') print( 'Please check if the radius and clearance of the robot was \n taken into consideration and reassign again.') backtracking = 0 rounded_neighbour = 0 return False else: while True: if break_while == 1: break _, curr_vert, curr_orient = heapq.heappop(priority_queue) # append visited nodes visited.add(curr_vert) # checking if the neighbour is the goal. If goal found reached if ((curr_vert[0] - goal[0]) ** 2 + (curr_vert[1] - goal[1]) ** 2 <= (1.5) ** 2): print('^^^^^^^^^^^^^^') print('^^^^^^^^^^^^^^') print('GOAL REACHED') print('^^^^^^^^^^^^^^') print('^^^^^^^^^^^^^^') print(curr_vert) break # check whether node is in the obstacle space if checkObstaclespace(curr_vert) == True: # generate neighbours graph = generateGraph(curr_vert, curr_orient) graph_list = [] # put neighbours in a list for easy access for key, cost_value in graph.items(): graph_list.append((key, cost_value)) for neighbour, cost in graph_list: this_cost = graph[neighbour][0] breakflag = 0 orientation = graph[neighbour][1] orientation = orientation % 360 # Round the node rounded_neighbour = (Round2Point5(neighbour[0]), Round2Point5(neighbour[1])) # print("cost for this"+str(rounded_neighbour)+str(this_cost)) if rounded_neighbour in visited: breakflag = 1 # exit if found if breakflag == 1: continue # check if this neighbour is goal if ((rounded_neighbour[0] - goal[0]) ** 2 + (rounded_neighbour[1] - goal[1]) ** 2 <= (1.5) ** 2): print('^^^^^^^^^^^^^^') print('^^^^^^^^^^^^^^') print('GOAL REACHED') print('^^^^^^^^^^^^^^') print('^^^^^^^^^^^^^^') break_while = 1 break ##check whether current neighbour node is in the obstacle space if checkObstaclespace(rounded_neighbour) == True: # check if visited if V[int(2 * rounded_neighbour[0])][int(2 * rounded_neighbour[1])][ orientation_to_layer[orientation]] == 0: # if not, make it visited V[int(2 * rounded_neighbour[0])][int(2 * rounded_neighbour[1])][ orientation_to_layer[orientation]] = 1 # calculate cost from cost_from[int(2 * rounded_neighbour[0])][int(2 * rounded_neighbour[1])][ orientation_to_layer[int(orientation)]] = ( this_cost + cost_from[int(2 * curr_vert[0])][int(2 * curr_vert[1])][ orientation_to_layer[curr_orient]]) # calculate cost to go values heur[int(2 * rounded_neighbour[0])][int(2 * rounded_neighbour[1])] = EucledianDistance( rounded_neighbour, goal) # calculate f = g+h f[int(2 * rounded_neighbour[0])][int(2 * rounded_neighbour[1])][ orientation_to_layer[orientation]] = \ cost_from[int(2 * rounded_neighbour[0])][int(2 * rounded_neighbour[1])][ orientation_to_layer[orientation]] + heur[int(2 * rounded_neighbour[0])][ int(2 * rounded_neighbour[1])] # push to the explored node queue heapq.heappush(priority_queue, ( f[int(2 * rounded_neighbour[0])][int(2 * rounded_neighbour[1])][ orientation_to_layer[orientation]], rounded_neighbour, orientation)) backtracking[rounded_neighbour] = {} # adding to the backtracking dictionary backtracking[rounded_neighbour][ f[int(2 * rounded_neighbour[0])][int(2 * rounded_neighbour[1])][ orientation_to_layer[orientation]]] = (curr_vert, curr_orient) else: # if visited, check cost. if newly genrated neighbour has a lower cost, update it if (f[int(2 * rounded_neighbour[0])][int(2 * rounded_neighbour[1])][ orientation_to_layer[orientation]]) > ( f[int(2 * curr_vert[0])][int(2 * curr_vert[1])][orientation_to_layer[curr_orient]]): f[int(2 * rounded_neighbour[0])][int(2 * rounded_neighbour[1])][ orientation_to_layer[orientation]] = ( f[int(2 * curr_vert[0])][int(2 * curr_vert[1])][orientation_to_layer[curr_orient]]) backtracking[rounded_neighbour][ f[int(2 * rounded_neighbour[0])][int(2 * rounded_neighbour[1])][ orientation_to_layer[orientation]]] = (curr_vert, curr_orient) return (curr_vert, backtracking) # return the last parent node and backtracked dictionary start_time = time.time() # calling the function to solve the obstacle space using A* Algorithm new_goal_rounded, backtracking_dict = a_star_Algorithm(start, goal) print("SOLVED in =", time.time() - start_time) # Backtracking back to the goal backtracked_final = BackTrack(backtracking_dict, start, new_goal_rounded) # printing the nodes from initial to the end print(backtracked_final) # %% # Scale the visited nodes and backtracked nodes for easy visualization new_list_visited = [] for visited_node in list(visited): new_x = visited_node[0] * 2 new_y = visited_node[1] * 2 new_list_visited.append((new_x, new_y)) new_backtracked = [] for back in backtracked_final: new_x_b = back[0] * 2 new_y_b = back[1] * 2 new_backtracked.append((new_x_b, new_y_b)) # #defining a blank canvas new_canvas = np.zeros((2040, 2040, 3), np.uint8) # for every point that belongs within the obstacle for c in map_points: # change the name of the variable l x = 2 * c[1] y = 2 * c[0] new_canvas[(x, y)] = [255, 255, 255] # assigning a yellow coloured pixel # flipping the image for correct orientation new_canvas = np.flipud(new_canvas) # making a copy for backtracking purpose new_canvas_copy_backtrack = new_canvas.copy() # making a copy for showing the visited nodes on the obstacle space # can be used for the animation new_canvas_copy_visited = new_canvas.copy() # visited path for visit_path in new_list_visited: # print(path) x = int(visit_path[0]) y = int(visit_path[1]) cv2.circle(new_canvas_copy_visited, (x, 2040 - y), 5, [0, 255, 255], -1) # new_canvas_copy_visited[(2040-y,x)]=[255,255,255] #setting every backtracked pixel to white # showing the final backtracked path new_visited = cv2.resize(new_canvas_copy_visited, (600, 400)) # showing the image new_canvas_copy_visited = cv2.resize(new_canvas_copy_visited, (1020, 1020)) cv2.imshow('visited', new_canvas_copy_visited) # saving the image # cv2.imwrite('visited_img.jpg',new_visited) cv2.waitKey(0) cv2.destroyAllWindows() # new_backtracked = g # backtracked path for path in new_backtracked: # print(path) x = int(path[0]) y = int(path[1]) cv2.circle(new_canvas_copy_backtrack, (x, 2040 - y), 5, [0, 0, 255], -1) # new_canvas_copy_backtrack[(2040-y,x)]=[255,255,255] #setting every backtracked pixel to white # showing the final backtracked path # new_backtracked = cv2.resize(new_canvas_copy_backtrack,(600,400)) new_canvas_copy_backtrack = cv2.resize(new_canvas_copy_backtrack, (1020, 1020)) # showing the image cv2.imshow('backtracked image', new_canvas_copy_backtrack) # saving the image # cv2.imwrite('backtracked_img.jpg',new_backtracked) cv2.waitKey(0) cv2.destroyAllWindows() # final quiver plot fig, ax = plt.subplots() RPM1 = RPM_L RPM2 = RPM_R actions = [[0, RPM1], [RPM1, 0], [RPM1, RPM1], [0, RPM2], [RPM2, 0], [RPM2, RPM2], [RPM1, RPM2], [RPM2, RPM1]] count = 0 for point in point_and_angle_list: x = point[0][0] y = point[0][1] theta = point[1] for action in actions: X1 = plot_curve(x, y, theta, action[0], action[1]) count += 1 plt.grid() ax.set_aspect('equal') plt.title('Vector - Path', fontsize=10) plt.show()
''' Created on May 13, 2015 @author: tekrei Various square root approximations Source: Introduction to Computation and Programming Using Python book ''' import time def newton_raphson(y): ''' Newton-Raphson for square root ''' epsilon = 0.01 ans = y / 2.0 guess_count = 0 while abs(ans * ans - y) >= epsilon: guess_count += 1 ans = ans - (((ans ** 2) - y) / (2 * ans)) return ans, guess_count def exhaustive_enumeration(x): ''' Approximating the square root using exhaustive enumeration ''' epsilon = 0.01 step = epsilon ** 2 guess_count = 0 ans = 0.0 while abs(ans ** 2 - x) >= epsilon and ans <= x: ans += step guess_count += 1 if abs(ans ** 2 - x) >= epsilon: print("failed on square root of %s" % x) else: print("%s is close to square root of %s" % (ans, x)) return ans, guess_count def bisection(x): ''' Bisection search to approximate square root ''' epsilon = 0.01 guess_count = 0 low = 0.0 high = max(1.0, x) ans = (high + low) / 2.0 while abs(ans ** 2 - x) >= epsilon: # print 'low =', low, 'high =', high, 'ans =', ans guess_count += 1 if ans ** 2 < x: low = ans else: high = ans ans = (high + low) / 2.0 return ans, guess_count if __name__ == '__main__': numbers = [4, 9, 16, 25, 81, 144, 256, 262144] for x in numbers: print("-------%d------" % x) start_time = time.time() print("Exhaustive enumeration %s (%fs)" % (str(exhaustive_enumeration(x)), time.time() - start_time)) start_time = time.time() print("Bisection %s (%fs)" % (str(bisection(x)), time.time() - start_time)) start_time = time.time() print("Newton Raphson %s (%fs)" % (str(newton_raphson(x)), time.time() - start_time))
''' Created on May 16, 2015 @author: tekrei ''' class Item(object): ''' Item class for knapsack problem ''' def __init__(self, n, v, w): self.name = n self.value = float(v) self.weight = float(w) def getName(self): return self.name def getValue(self): return self.value def getWeight(self): return self.weight def __str__(self): return '<' + self.name + ', ' + str(self.value) + ', ' + str(self.weight) + '>' def value(item): return item.getValue() def weight_inverse(item): return 1.0 / item.getWeight() def density(item): return item.getValue() / item.getWeight() def build_items(): ''' build example items for test ''' names = ['clock', 'painting', 'radio', 'vase', 'book', 'computer'] vals = [175, 90, 20, 50, 10, 200] weights = [10, 9, 4, 2, 1, 20] items = [] for i in range(len(vals)): items.append(Item(names[i], vals[i], weights[i])) return items
################################################################################# # Quick Sort # # A quick sort first selects a value, which is called the pivot value # # The actual position where the pivot value belongs in the final sorted list, # # the split point, will be used to divide the list for subsequent calls # ################################################################################# def quickSort(alist): """Quick Sort of alist""" return quickSortHelper(alist,0,len(alist)-1) def quickSortHelper(alist,first,last): """quick sort from first to last (included)""" # first == last, list of one element is already sorted if first < last: # pivot is at splitpoint in the final sorted list indexPivot = medianOf3(alist, first, last) splitpoint = partition(alist,first,last, indexPivot) # index < splitpoint => alist[index] <= pivot leftComparaisons = quickSortHelper(alist,first,splitpoint-1) # index > splitpoint => alist[index] > pivot rightComparaisons = quickSortHelper(alist,splitpoint+1,last) return (last - first) + leftComparaisons + rightComparaisons else: return 0 def partition(alist,first,last, indexPivot): """pivot at first position""" alist[first], alist[indexPivot] = alist[indexPivot], alist[first] pivotvalue = alist[first] i = first + 1 for j in range(first+1, last+1): if alist[j] < pivotvalue: alist[j], alist[i] = alist[i], alist[j] i += 1 alist[first], alist[i-1] = alist[i-1], alist[first] #print (alist[i-1],alist[first], i-1 ) return (i-1) def is_median(ar, i, j, k): """Determines whether ar[i] is a median of ar[i], ar[j] and ar[k]""" return (ar[i] < ar[j] and ar[i] > ar[k]) or (ar[i] > ar[j] and ar[i] < ar[k]) def medianOf3(ar,l,r): """return the index of the median of three""" m = l + ((r-l) >> 1) if is_median(ar, l, m, r): return l elif is_median(ar, m, l, r): return m else: return r ################## # Main() to test # ################## if __name__ == '__main__': alist = [54,26,93,17,77,31,44,55,20] print("Nb Comparaisons = {0}".format(quickSort(alist))) print(alist)
s="manjugiri" #s[::2] returns the element on the even position which is divisible by 2. print("Elements of even index position:", s[::2])
# def wash(dry=False, water=8): # print('加水', water, '分滿') # print('加洗衣精') # print('旋轉') # if dry: # print(dry, '烘衣服') # # # wash(True, 10) # # # def say_hi(): # print('hi!') # # # say_hi() # # # def add(x=0, y=0): # print(x + y) # # # add(123, 1223) # # # add() # def average(numbers): # avg = sum(numbers) / len(numbers) # return avg # # # print(average([1, 2, 3])) # print(average([1, 2, 3])) # 測驗 # def add(x, y): # print(x + y) # # # add(1, 1) # def hello(x, y=1): # print(x, y) # # # hello(3, 4) def crazy(x, y=3, z=2): return x * 2 + y * 3 + z crazy(2) # 15 crazy(3, 1) # 11 crazy(3, 2, 0) # 12 # 以上沒有print或接收值,所以不會印出東西
import os import csv import openpyxl import numpy from tkinter import * import tkinter.filedialog def prompt(): print('This program will calculate the rate constant (k) using two time points with N hellistein,' ' k using two time points with experimental N, binomial distribution, and plateau with corresponding N.' 'also total labeling. Output is to an excel file. ') print('Please choose an option from the list:') print('1. Find these values for a single peptide [DEBUGGING PURPOSES]') print('2. Find these values for all petides in the given file with bwe included. ') print('3. Find these values for all peptides with manually entered BWE') print('Please enter 1, 2 or 3') selection = input('Enter your choice: ').strip() while check_selection(selection) == False: print('\n') print('This is an invalid input.') print('Please enter 1 or 0') selection = input('Enter your choice: ').strip() Ne = input('Enter the number of Isotopomers you want to use, up to two: ').strip() while check_selection(Ne) == False: print('Enter 1 or 2') Ne = input('Enter the number of Isotopomers you want to use, up to two: ').strip() #BWE = input('Please enter BWE as a decimal: ').strip() return selection, Ne def check_selection(selection): if selection == '1' or selection == '2' or selection == '3': return True else: return False def find_folder(): window = Tk() print("Please select a directory.") folder_name = tkinter.filedialog.askdirectory(initialdir = os.getcwd(), title= "Please select a directory that contains your files") print("Your choice is %s" % folder_name) window.withdraw() return folder_name def read_csv(file_path): #latest task here (NOT WORKING) """ From the CSV file given from read_file(), this will generate the Peptides dictionary The first key is the time points from the experiment. """ pepDict = dict() temp_list = list() with open(file_path, 'r') as csvfile: CSVReader = csv.reader(csvfile) for rCount, row in enumerate(CSVReader): if rCount == 0: first_row = row for count in first_row: pepDict[count] = [] else: for i, peptide in enumerate(first_row): if row[i] == '': pass else: pepDict[peptide].append(row[i]) #print(pepDict) return first_row, pepDict def read_file(folder_name): """ This will find the csv file where the first cell value is equal to A1. Program will throw error if not found """ file_count = int(0) A1 = 'time' for file_name in os.listdir(folder_name): #this creates a list from the directory (list of specimens) file_name_split = file_name.split('.') if file_name_split[1] == "csv" and file_count == 0: file_path = os.path.sep.join([folder_name,file_name]) with open(file_path) as file: file_count += 1 for row in file: row = row.split(',') if row[0] == A1: first_row, pepDict = read_csv(file_path) break else: print("File: {0} is not the correct file".format(file_path)) return first_row, pepDict def find_mass(peptide): """ This is not actually needed within this program, it is only to check if all amino acids were included into the protein """ return def calc_k(t, Y1, Y0, P): """ Calculate the rate constant k using: t = time of selected Y point Y1 = select Y point Y0 = Y value at time 0 P = plateau, be either Plateau at Hellinsten N or New N from experiment """ t = float(t) k = 0 k = -1/(t*numpy.log(1-(Y1-Y0)/(P-Y0))) return k def calc_abundance(BWE = 0): """ % abundances """ try: BWE = float(BWE) except ValueError: print("BWE was not a decimal! Please retry") X2, X13, X14, X16, X17, X18, X32, X33, X34 = 0.00015, 0.011074,0.99635,0.99759, 0.00037, 0.00204, 0.95,0.0076,0.0422 X1, X12, X15 = 1-X2, 1-X13, 1-X14 Y2, Y13, Y15, Y17, Y18, Y33, Y34 = X2/X1, X13/X12, X15/X14, X17/X16, X18/X16, X33/X32, X34/X32 if(BWE ==0.0): D2 = X2 else: D2 = BWE D1 = 1- D2 YD2 = D2/D1 abundance = [Y2, Y13, Y15, Y17 , Y33,YD2, Y18, Y34] return abundance def calc_totLabel(M10, M20, M30): """ this calculates the total labeling given M10,M20,M30.... 1- sum(m0 to m2) / sum(m1 to m2) Ne is not needed due to the fact that the excluded distributions will be 0 by default (defined in binomial_distribution() arguments) """ msumD = 1 + M10+ M20 + M30 totalLabel = 1 - ((M10+ M20+ M30)/ msumD) return totalLabel def calc_plateau(Y0, Ne, elements, BWE, N = 0): #N = elements[5] hp = elements[0] - N #hp defined by total H minus Dp hp0 = elements[0] #save original value of hp0 elements[0] = hp #this is then passed into the elements list as such abd = calc_abundance(BWE) #abd[0] is YD0 in Visual Basic, and abd[5] is YD2 YD0 = abd[0] YD2 = abd[5] #calculate beta beta = 0 for i in range(5): beta += elements[i]*abd[i] #calculate gamma gamma = 0 for i in range(5): gamma += elements[i]*(elements[i]-1)*((abd[i])**2) #calculate omega omega = 0 for i in range(4): if(i == 1): continue else: omega += elements[1]*abd[1]*elements[i]*abd[i] #calculate sigma sigma = 0 sigma= elements[3]*abd[6] + elements[4]*abd[7] + elements[3]*abd[3]*elements[4]*abd[4] + omega #plat1 is the denominator to the equation if(Ne == '1'): plat1 = N*(YD0-YD2) elif(Ne == '2'): plat1 = N*(YD2 - YD0)*(1+beta+((N-1)/2)*(YD2+YD0)) elif(N == '3'): plat1 = N*(YD2-YD0)(1+beta+gamma+ ((N-1)/2)*(YD2+YD0)+((N-1)/6)*(YD2**2+YD2*YD0+YD0**2)) #plat1 = N*(YD2-YD0)*(1+(gamma/2)+sigma+((N-1)/2)*(YD2-YD0)*(1+beta)+(N-1)*(N-2)*(YD2**2 + YD2*YD0)/6) elif(N == '4'): pass Plat = 1-1/(1/(1-Y0)+plat1) elements[0] = hp0 # restore back to original Hp return Plat def find_total_elements(peptide): """ 'key' : Sa,Ca,Na,Oa,Ha,Da(hellenstein), expDa (Experiment). This is theoretical values- given the amino acid code expDa- the list of experimental N from experiment """ peplist = list(peptide) #this creates an array of the characters Sp,Cp,Np,Op,Hp,Dp, expDa = 0,0,0,0,0,0,0 AA_dict = { 'G': [0,2,1,1,3,2.06,1.530], 'A': [0,3,1,1,7,4,3.560], 'S': [0,3,1,2,5,2.61,1.763], 'P': [0,5,1,1,7,2.59,0.848], 'V': [0,5,1,1,9,0.42,0.519], 'T': [0,4,1,2,7,0.2,0.261], 'C': [1,3,1,1,5,1.62,1.589], 'c': [1,5,2,2,8,1.62, 1.589], #no given value for c in excel table, assuming the same 'L': [0,6,1,1,11,0.6,0.434], 'I': [0,6,1,1,11,1,0.846], 'N': [0,4,2,2,6,1.89,0.921], #'O': [0,5,2,1,10,1], 'D': [0,4,1,3,5,1.89,2.087], 'Q': [0,5,2,2,8,3.95,2.812], 'K': [0,6,2,1,12,0.54,0.245], 'E': [0,5,1,3,7,3.95,3.365], 'M': [1,5,1,1,9,1.12,0.865], 'm': [1,5,1,2,9,1.12,0.865], #no given value for c in excel table, assuming the same 'H': [0,6,3,1,7,2.88,1.555], 'F': [0,9,1,1,9,0.32, 0.284], 'R': [0,6,4,1,12,3.43,1.835], 'Y': [0,9,1,2,9,0.42, 0.381], 'W': [0,11,2,1,10,0.08, 0.219] } for i in peplist: try: Sp += AA_dict[i][0] Cp += AA_dict[i][1] Np += AA_dict[i][2] Op += AA_dict[i][3] Hp += AA_dict[i][4] Dp += AA_dict[i][5] expDa += AA_dict[i][6] except KeyError: print("Key not found, skipping:", i) pass elements = [Hp,Cp,Np,Op,Sp, Dp,expDa] return elements def binomial_distribution(peptide,Ne, elements, BWE = 0, M10 = 0, M20 = 0, M30 = 0, M40 = 0): #hp now equals hp -N, where N is Dp at every calcualtion of the binomial distribution y0 = elements[0] elements[0] = elements[0] - elements[5] print('hp {0} defined by total H minus Dp for peptide: {1}'.format(elements[0], peptide)) print('Elements ',elements) abd = calc_abundance(BWE) m202, m203, m204, m205 = 0, 0, 0, 0 print('abundance = {0}'.format(abd)) try: Ne = float(Ne) except ValueError: print("Ne was not a integer! Please retry") for i in range(6): M10 += abd[i]*elements[i] if(Ne >= 1): print(M10) elements[0] = y0 return M10,M20,M30 elif(Ne >= 2): for i in range(6): M20 += (elements[i]*(elements[i]-1)*(abd[i]**2))/2 m202 = abd[0]*elements[0]*(abd[1]*elements[1]+abd[2]*elements[2]+abd[3]*elements[3]+abd[4]*elements[4]+abd[5]*elements[5]) m202 += abd[1]*elements[1]*(abd[2]*elements[2]+abd[3]*elements[3]+abd[4]*elements[4]+abd[5]*elements[5]) m202 += abd[2]*elements[2]*(abd[3]*elements[3]+abd[4]*elements[4]+abd[5]*elements[5]) m202 += elements[5]*abd[5]*(elements[3]*abd[3]+elements[4]*abd[4]) m202 += elements[4]*abd[4]*elements[3]*abd[3] M20 += m202 + elements[3]*abd[6]+elements[4]*abd[7] elements[0] = y0 return M10,M20,M30 elif(Ne >= 3): #TO DO .... m303,m302,m301 = 0,0,0 for i in range(6): m303 += (elements[i]*(elements[i]-1)*(elements[i]-2)*(abd[i]**3))/6 m303 = m303 + elements[3]*(elements[3]-1)*abd[3]*abd[6] + elements[4]*(elements[4]-1)*abd[4]*abd[7] m302 = elements[0]*(elements[0]-1)*(abd[0]**2)*(abd[1]*elements[1]+abd[2]*elements[2]+abd[3]*elements[3]+abd[4]*elements[4]+abd[5]*elements[5]) m302 += elements[1]*(elements[1]-1)*(abd[1]**2)*(abd[0]*elements[0]+abd[2]*elements[2]+abd[3]*elements[3]+abd[4]*elements[4]+abd[5]*elements[5]) m302 += elements[2]*(elements[2]-1)*(abd[2]**2)*(abd[0]*elements[0]+abd[1]*elements[1]+abd[3]*elements[3]+abd[4]*elements[4]+abd[5]*elements[5]) m302 += elements[3]*(elements[3]-1)*(abd[3]**2)*(abd[0]*elements[0]+abd[1]*elements[1]+abd[2]*elements[2]+abd[4]*elements[4]+abd[5]*elements[5]) m302 += elements[4]*(elements[4]-1)*(abd[4]**2)*(abd[0]*elements[0]+abd[1]*elements[1]+abd[2]*elements[2]+abd[3]*elements[3]+abd[5]*elements[5]) m302 += elements[5]*(elements[5]-1)*(abd[5]**2)*(abd[0]*elements[0]+abd[1]*elements[1]+abd[2]*elements[2]+abd[3]*elements[3]+abd[4]*elements[4]) m302 = m302/2 for i in range(6): if i == 3 or i == 4: pass else: m301 += (abd[6]*elements[3]+abd[7]*elements[4])*(abd[i]*elements[i]) m301 += abd[3]*elements[3]*abd[7]*elements[4]+abd[6]*elements[3]*abd[4]*elements[4] m301 += abd[0]*elements[0]*abd[5]*elements[5]*(abd[1]*elements[1]+ abd[2]*elements[2]+abd[4]*elements[4]) m301 += abd[1]*elements[1]*abd[5]*elements[5]*(abd[2]*elements[2]+ abd[2]*elements[2]+abd[4]*elements[4]) m301 += abd[1]*elements[1]*abd[0]*elements[0]*(abd[2]*elements[2]+ abd[3]*elements[3]+abd[4]*elements[4]) m301 += abd[1]*elements[1]*abd[2]*elements[2]*(abd[3]*elements[3]+ abd[4]*elements[4]) #questioning this line m301 += abd[0]*elements[0]*abd[2]*elements[2]*(abd[3]*elements[3]+ abd[5]*elements[5]) m301 += abd[5]*elements[5]*abd[2]*elements[2]*(abd[3]*elements[3]+ abd[4]*elements[4]+abd[0]*elements[0]) elements[0] = y0 return M10,M20,M30 def single_peptide(peptide,Ne, BWE, data = None, t = 0, index = 0): """ Comment: This deals with a single peptide. If there are more than one, this will loop. """ print(peptide) elements = find_total_elements(peptide) #find total elements in a peptide print('elements = ', elements) M10, M20, M30 = binomial_distribution(peptide,Ne, elements) #calculate distribution at start Y0 print("M10 at Start: ", M10) print("M20 at Start: ", M20) print("M30 at Start: ", M30) TL0 = calc_totLabel(M10 , M20, M30) #calcualte TL at start M10, M20, M30 = binomial_distribution(peptide ,Ne, elements,BWE) #calculate distribution at Plateau BWE.. elements become overwritten print("M10 at Plateau (BWE): ", M10) print("M20 at Plateau (BWE): ", M20) print("M30 at Plateau (BWE): ", M30) TL2 = calc_totLabel(M10, M20, M30) #calculate TL at plateau print('TL0 at time 0: {0}, TL2 at plataeu: {1}'.format(TL0,TL2)) if data is None: data = [] theoryPlat = calc_plateau(TL0, Ne, elements,BWE, elements[5]) #calculate theory plateau... elements become overwritten. This is using hellisten N (elements[5]) return else: #experimental peptide data will be in structure "data" argument #using this data, find the plateau. this will need to include Y0 value form experiment, Y1 (corersponds to t value) Y0 = (float(data[0]) + float(data[1]))/2 Y1 = (float(data[index]) + float(data[index+1]))/2 PlateauNhell = calc_plateau(Y0, Ne, elements, BWE, elements[5]) PlateauNexp = calc_plateau(Y0, Ne, elements, BWE, elements[6]) #elements[6] is the sum of N from experiment kNhell = calc_k(t, Y1, Y0, PlateauNhell) kexpN = calc_k(t, Y1, Y0, PlateauNexp) print('rate/Y0Nhell: {0}, rate/newN: {1}'.format(kNhell,kexpN)) return def single_distribution(Ne): """ This is for debugging purposes. """ peptide = input('Please enter peptide: ').strip() BWE = input('Please Enter BWE as a decimal: ').strip() single_peptide(peptide, Ne, BWE) return def full_distribution_fileBWE(Ne): """ This method takes the data from pepDict and runs single_peptide() for each peptide in the peptide_list. More details on how these values are found are in read_file(). ------------DOES NOT WORK YET--------------- """ BWE = None#will be in file... not sure how to handle this yet folder_name = find_folder() first_row, pepDict = read_file(folder_name) peptide_list = first_row[1:] t = input('Type in hours the timpoint to use: ').strip() index = pepdict['time'].index(t) for peptide in peptide_list: single_peptide(peptide, Ne, BWE, pepDict[peptide], t, index) return def full_distribution_file(Ne): """ This message uses the full distribution method, but without the BWE from the excel file. """ BWE = input('Please Enter BWE as a decimal: ').strip() folder_name = find_folder() first_row, pepDict = read_file(folder_name) peptide_list = first_row[1:] t = input('Type in hours the timpoint to use (t): ').strip() index = pepDict['time'].index(t) for peptide in peptide_list: single_peptide(peptide, Ne, BWE, pepDict[peptide], t, index) return def main(): selection, Ne = prompt() if selection == '1': single_distribution(Ne) elif selection == '2': full_distribution_fileBWE(Ne) elif selection == '3': full_distribution_file(Ne) main() print('Done')
print("This is running") def our_firstfunction(): print("inside our_firstfunction") x = 1 + 2 return x print(our_firstfunction()) def add(n1, n2): return n1 + n2 a = add(3,4) print(a)
def roman(n): if n//10 == 0: value="" elif n//10 == 1: value = "X" elif n//10 == 2: value = "XX" elif n//10 == 3: value = "XXX" elif n//10 == 4: value = "XL" elif n//10 == 5: value = "L" elif n//10 == 6: value ="LX" elif n//10 == 7: value = "LXX" elif n//10 == 8: value = "LXXX" elif n//10 == 9: value = "XC" elif n//10 == 10: value = "C" if n%10 == 0: value2= "" elif n%10 == 1: value2= "I" elif n%10 == 2: value2= "II" elif n%10 == 3: value2= "III" elif n%10 == 4: value2= "IV" elif n%10 == 5: value2= "V" elif n%10 == 6: value2= "VI" elif n%10 == 7: value2= "VII" elif n%10 == 8: value2= "VIII" elif n%10 == 9: value2= "IX" return value + value2 for i in range(1,100): if i % 5 == 0: print() print(i, roman(i), ", ", end="")
def factorial(n): """ Using recusion, return the factorial of the number n Returns:An integer """ if n == 1: return 1 else: res = n*factorial(n-1) return res def my_range(n, m): if n == m: return 0 else: return [n] return -1 def palindrome(word): """ Returns a boolean (True or False) if the string is a palindrome. Must do this recursively. Returns: Boolean """ count = -1 reversevalue = "" for i in x: reversevalue = reversevalue+x[count] count=count-1 Final = x == reversevalue return Final return "a" def removePos(x, lst): """ Removes an item from the list that is the same as x. Must do this recursively. Returns: List with an occurences of x gone """ return -1 def sum2DList(lst): """ Recursively go through and sum all the values from each row and add the result of each row together to get a final value. Ex) [[1, 2, 3], [4, 5, 6], [7, 8, 9]] ---> 45 Returns: Integer """ return [] def print_chars_recursive(inpt, pos): """ Print all characters from the list recursively. Returns: Nothing """ pass def recursive_factorial(n, isFirstRun): """ Recursively computes the factorial and only writes to the file once Returns: Integer """ return "a" def recursive_file_sum(filename, fh, sm, isFirstRun): """ Takes in a file and adds the numbers in the file. Returns: Integer """ return "A"
symbol = {'0':0, '1':1, '2':2, '3':3, '4':4, '5':5, '6':6, '7':7, '8':8, '9':9, 'A':10, 'B':11, 'C':12, 'D':13, 'E':14, 'F':15} def hex_dec(hex): power = len(hex) - 1 num = 0 for i in hex: num += symbol[i] * 16 ** power power -= 1 return num hex = input("Hex: ") print(hex_dec(hex))
x = True y = False z = 12 a = 10 b = not (x or not (x or y)) and True if b: print("Happy") elif b and x: print("Valentines") elif not b and not x and not y: print("day!") else: None ################### #2################# if (z < a): print("C200") elif (2*a<z): print("is bliss") else: None ################### #3################# if not (not (x and y) or not x): print(a) ################### #4################# if (2 > z) or not x: print("1") elif 2 == 1: print("2") elif y and not x: print("3") elif y: print("4") def f(x): return (x==4)*100 + (x==3)*10 + (x==2)*1000 + (x!=4)*(x!=3)*(x!=2)*100000 print(f(4)) print(f(3)) print(f(2)) print(f(1))
import math #question 1 f = lambda r :math.pi*(r**2) print (f(5)) #question 2 lst1 = [1,2,3,4,8] lst2 = [4,1,4,2] k = map(f,lst1,lst2) k = map( (lambda x,y:y if y>x else x), lst1, lst2) for i in k: print(i) for i in k: print(i) #question 3 def filter (x): aa = [1,2,3,4,5,6] if x: kor = filter( (lambda x:x<4), aa) return True else: return False print (list(filter) def comprehension(x): #question 4 lst = [1,2,3,4,5,6,7] k = [x*20 for x in lst if x<4] print (comprehension)
class Cola (object): def __init__(self): self.items=[] def encolar (self,dato): self.items.append(dato) def desencolar (self): if self.esta_vacia(): return None else: return self.items.pop(0) def esta_vacia(self): if len(self.items)==0: return True else: return False def mirarElementos(self): x="" if len(self.items)!=0: for i in self.items: x+=("-"+i.detalles()) return x; def buscarPlaca(self, p): if len(self.items)!=0: for i in self.items: if i.getPlaca() == p: return "EXISTE: "+i.detalles() return "No se encontro la placa"; def buscarColor(self, p): if len(self.items)!=0: for i in self.items: if i.getColor() == p: return "EXISTE: "+i.detalles() return "No se encontro moto con dicho Color"; def buscarPropietario(self, p): if len(self.items)!=0: for i in self.items: if i.getPropietario() == p: return "EXISTE: "+i.detalles() return "No se encontro moto con dicho propietario"; class Moto: def __init__(self, placa, color, propietario): self.p = placa self.c = color self.pr = propietario def detalles (self): return self.p +" "+ self.c +" "+ self.pr def getPlaca (self): return self.p+"" def getColor (self): return self.c+"" def getPropietario (self): return self.pr+"" def main (): q = Cola() moto1=Moto("BIP890","Rojo","No se") moto2=Moto("S","Verde","Aiuda") q.encolar(moto1) q.encolar(moto2) print(q.mirarElementos()) print(q.buscarPlaca("BIP890")) print(q.buscarPlaca("BIP89")) print(q.buscarColor("Rojo")) print(q.buscarColor("BR")) print(q.buscarPropietario("Nas")) print(q.buscarPropietario("Aiuda")) #placa = raw_input("Ingrese Placa de la moto") #color = raw_input("Ingrese color de la moto") #propietario = raw_input("Ingrese propietario de la moto") main()
# A Simple Bouncer Program age = input('What is your age ') x = int(age) if x < 18: print('Sorry You are too young') elif x >= 18 and x <= 21: print('You are allowed to go') else: print('You are old enough for this')
# #This is a simple guessing game in Python. from random import * number = randint(1,10) while True: guess = input('Pick a number from 1 to 10: ') guess = int(guess) if guess < number: print('Its too low') elif guess > number: print('its to high') else: print('You Won') break
''' Just like a balloon can have multiple ribbons, an object can also have multiple reference variables. Both the references are referring to the same object. When you assign an already created object to a variable, a new object is not created. ''' class Mobile: def __init__(self, price, brand): print ("Inside constructor") self.price = price self.brand = brand mob1=Mobile(1000, "Apple") mob2=mob1 print ("Id of object referred by mob1 reference variable is :", id(mob1)) print ("Id of object referred by mob2 reference variable is :", id(mob2)) #mob1 and mob2 are reference variables to the same object
#Static Method continued ''' Since static variable is object independent, we need a way to access the getter setter methods without an object. This is possible by creating static methods. Static methods are those methods which can be accessed without an object. They are accessed using the class name. There are two rules in creating such static methods: The methods should not have self @staticmethod must be written on top of it ''' @staticmethod def get_discount(): return Mobile.__discount @staticmethod def set_discount(discount): Mobile.__discount=discount
''' What happens when we pass an object as a parameter to a function? In the below code, what will be the output? ''' class Mobile: def __init__(self, price, brand): self.price = price self.brand = brand def change_price(mobile_obj): mobile_obj.price = 3000 mob1=Mobile(1000, "Apple") change_price(mob1) print (mob1.price)
class node: def __init__(self,value): self.value=value self.leftChild=None self.rightChild=None self.totalChild=0 class binaryTree: def __init__(self): self.rootVal=None def insertLeft(self, val): rootNode=self.rootVal if(rootNode.leftChild is None): self.rootVal.leftChild=val else: print("Left Child Full") #self.totalChild=self.totalChild+1 def insertRight(self, val): rootNode=self.rootVal if(rootNode.rightChild is None): self.rootVal.rightChild=val else: print("Right Child Full") # self.totalChild=self.totalChild+1 def addNode(self,value): self.rootVal=node(value) def printNode(self): printVal=self.rootVal if printVal is not None: print(printVal.value) if(printVal.leftChild is not None): print(printVal.leftChild) if(printVal.rightChild is not None): print(printVal.rightChild) nodeVal=int(input("Enter root node: ")) bt=binaryTree() bt.addNode(nodeVal) insertVal=int(input("Enter insert val: ")) if insertVal<nodeVal: bt.insertLeft(insertVal) else: bt.insertRight(insertVal) insertVal=int(input("Enter insert val: ")) if insertVal<nodeVal: bt.insertLeft(insertVal) else: bt.insertRight(insertVal) bt.printNode()
#A=int(input("ingrese un para comparar si es mayor numero\n")) #B=int(input("ingrese otro numero para comparar si es mayor\n")) #C=int(input("ingrese un nuemero para comparar si es mayor\n")) def mayor(A,B,C): var = 0 if(A > B and A > C): print("El numero mayor es " + str(A)) var = A else: if(B > A and B > C): print("El numero mayor es " + str(B)) var = B else: print("El numero mayor es " + str(C)) var = C return var
class Solution: def isMatch(self, A,B): if not len(A) and not len(B): return True if not len(B): return False if len(B) - B.count('*') > len(A): return False A = "@" + A B = "@" + B dp = [[None for j in range(len(B))] for i in range(len(A))] for i in range(len(A)): for j in range(len(B)): if i == 0 and j == 0: dp[i][j] = True else: if A[i] == B[j] or B[j] == "?": dp[i][j] = dp[i-1][j-1] if i > 0 and j > 0 else False else: if B[j] == "*": dp[i][j] = dp[i][j] or ( dp[i-1][j] if i > 0 else False) dp[i][j] = dp[i][j] or (dp[i-1][j-1] if i > 0 and j > 0 else False) dp[i][j] = dp[i][j] or ( dp[i][j-1] if j >0 else False) return True if dp[len(A)-1][len(B)-1] else False #return 1 if self.match(len(A),len(B)) else 0 """def match(self, i,j): if i == 0 and j==0: return True elif self.memo[i][j] != None: return self.memo[i][j] else: res = None if self.A[i] == self.B[j]: res = self.match(i-1,j-1) if i > 0 and j > 0 else False else: if self.B[j]=="?": res = self.match(i-1,j-1) if i > 0 and j > 0 else False elif self.B[j]=="*": res = res or ( self.match(i-1,j) if i > 0 else False) res = res or (self.match(i-1,j-1) if i > 0 and j > 0 else False) res = res or ( self.match(i, j-1) if j >0 else False) else: res = False if i >=0 and j >= 0: self.memo[i][j] = res return res """ def main(): s = Solution() print(s.isMatch("ab","?*") ) main()
# -*- coding: UTF-8 -*- from descontos import Desconto_por_cinco_itens, Desconto_por_mais_de_quinhentos_reais, Sem_desconto class Calculador_de_descontos(object): def calcular(self, orcamento): desconto = Desconto_por_cinco_itens(Desconto_por_mais_de_quinhentos_reais(Sem_desconto())).aplicar(orcamento) return desconto if __name__ == '__main__': from orcamento import Orcamento, Item orcamento = Orcamento() orcamento.adiciona_item(Item('Item 1', 100)) calculador = Calculador_de_descontos() desconto_calculado = calculador.calcular(orcamento) print 'Desconto calculado = %s' % (desconto_calculado)
import cv2 as cv # 1) Adição de imagens image1 = cv.imread('images/superman.png') image2 = cv.imread('images/batman.png') addedImage = cv.add(image1, image2) #addedImage = image1 + image2 # Assim também é possível, porém não haverá tratamento dos pixels e pode resultar na distorção das cores cv.imshow('Imagem somada', addedImage) cv.waitKey(0) cv.destroyAllWindows() # 2) Subtração de imagens image1 = cv.imread('images/superman.png') image2 = cv.imread('images/batman.png') subtractedImage = cv.subtract(image1, image2) #subtractedImage = image1 - image2 # Assim também é possível, porém não haverá tratamento dos pixels e pode resultar na distorção das cores cv.imshow('Imagem subtraída', subtractedImage) cv.waitKey(0) cv.destroyAllWindows() # 3) Soma Ponderada ''' A soma ponderada mescla, com perda de dados, duas imagens em apenas uma. Método addWeighted(src1, alpha, src2, beta, gamma): src1 = Matriz referente a primeira imagem alpha = Peso (Itensidade) da primeira imagem src1 = Matriz referente a segunda imagem beta = Peso (Itensidade) da segunda imagem gamma = Valor escalar adicionado a cada soma OBS.: Os valores de alpha e beta variam de 0.1 a 1, sendo 0.1 equivalente a imagem transparente e 1 a intensidade máxima da imagem. O gamma é utilizado para realizar ajustes na imagem. Saída: Matriz da imagem mesclada ''' image1 = cv.imread('images/superman.png') image2 = cv.imread('images/batman.png') mergedImage = cv.addWeighted(image1, 0.3, image2, 0.7, 0) cv.imshow('Imagem Mesclada', mergedImage) cv.waitKey(0) cv.destroyAllWindows()
#!/usr/bin/env python3 """ Copyright 2020, University of Freiburg Author: Marco Kaiser <kaiserm@informatik.uni-freiburg.de> Usage of the Script: This script opend the File kami.txt parses it and prints an ouput which is a problem in pddl. Make sure to have a correct kami.txt file, otherwise the problem will just fail. For example use: python3 create_pddl.py > porblem.pddl """ # create_pddl.py, written on: Donnerstag, 13 Oktober 2020. import sys colors = ['R', 'G', 'B', 'Y'] # red, green, blue, yellow def main(): try: f = open(sys.argv[1],"r") except FileNotFoundError: print("Invalid file or file path! Exiting...") exit(1) content = f.readlines() vertical = [] for line in content: acc = [] for char in line: if char == '\n': break acc.append(char) vertical.append(acc) acc_one = [] acc_two = [] acc_color = [] for y, line in enumerate(vertical): for x, char in enumerate(line): if char != " ": acc_one.append("tile%d%d " %(x, y)) acc_one.append("- tile") max_y = len(vertical) for y, line in enumerate(vertical): max_x = len(line) for x, char in enumerate(line): if char == " ": continue elif char == "R": acc_two.append("(color_value tile%d%d red)" % (x, y)) if "red " not in acc_color: acc_color.append("red ") elif char == "G": acc_two.append("(color_value tile%d%d green)" % (x, y)) if "green " not in acc_color: acc_color.append("green ") elif char == "B": acc_two.append("(color_value tile%d%d blue)" % (x, y)) if "blue " not in acc_color: acc_color.append("blue ") elif char == "Y": acc_two.append("(color_value tile%d%d yellow)" % (x, y)) if "yellow " not in acc_color: acc_color.append("yellow ") if x + 1 < max_x: if vertical[y][x+1] != " ": acc_two.append("(is_neighbour tile%d%d tile%d%d)" % (x, y, x+1, y)) if x - 1 >= 0: if vertical[y][x-1] != " ": acc_two.append("(is_neighbour tile%d%d tile%d%d)" % (x, y, x-1, y)) if y + 1 < max_y and x < len(vertical[y+1]): if vertical[y+1][x] != " ": acc_two.append("(is_neighbour tile%d%d tile%d%d)" % (x, y, x, y+1)) if y - 1 >= 0 and x < len(vertical[y-1]): if vertical[y-1][x] != " ": acc_two.append("(is_neighbour tile%d%d tile%d%d)" % (x, y, x, y-1)) print("""(define (problem kami-prob) (:domain kami-dom) (:objects %s %s- color true - bool) (:init (= (total-cost) 0) %s) (:goal (and (not (curr_color true)) (or """ % ("".join(acc_one), "".join(acc_color), "\n".join(acc_two)), end="\n") for c in acc_color: print(" (forall (?t - tile) (color_value ?t %s))" % (c[:-1]), end="\n") print(" )))\n") print(" (:metric minimize (total-cost))\n)") f.close() if __name__ == '__main__': if len(sys.argv) != 2: exit(1) main()
''' This program counts and displays the vowels in a string using two different methods. Input: String(User Input) Output: Number & List of vowels in the string ''' def vowel_count( string, vowel): vowel_num = [each for each in string if each in vowel] print("Number of vowels in your string:%d"%len(vowel_num)) print("The list of vowels in your string:%s"%vowel_num) def count_vowel( string, vowel): count = {}.fromkeys(vowel,0) for each in string: if each in count: count[each] += 1 print("Number of vowels in your string:", count) vowel="AaEeIiOoUu" string = input("Enter your string:") input_choice = int(input("Which method would you prefer? \n1. For loop\n2. Dictionary\nEnter your choice(1-2):")) if input_choice == 1: vowel_count(string,vowel) elif input_choice == 2: count_vowel(string, vowel) else: print("Wrong Input")
#!/usr/bin/python3 def search_replace(my_list, search, replace): if my_list is None: return new_list = [0 for i in my_list] for idx, val in enumerate(my_list): if val == search: new_list[idx] = replace else: new_list[idx] = val return new_list
#John Paul Lee #Problem Sheet for Week 3 of Programming and Scripting #Ask user to input a sentance. s = str(input("Please enter a sentence: ")) sliced = s[::-1] #sliced the sentence in reverse. No input between the colons to allow for unlimited length of sentance. print(sliced[::2]) #print every second word of the sliced (reversed) sentence . #how to print evey second word in of the sentence correct order print(s[0:99:2]). # References: # "Built-in Types" section of A Whirlwind Tour of Python by Jake Vanderplas. # https://www.programiz.com/python-programming/methods/built-in/slice # https://www.journaldev.com/23584/python-slice-string
def addition1(): result = 5 + 5 return result def addition(n = 35): result = 5 + n return result def multiply(): return 5 * 5 def get_message(): return "le résulat du calcul est" print(get_message(), multiply()) print("le résulat du calcul est", addition1()) print("le résulat du calcul est", addition()) print("le résulat du calcul est", addition(4)) print("le résulat du calcul est", addition(5)) print("le résulat du calcul est", addition(9))
food1 = input("Please enter a favorite food ") food2 = input("Please enter another favorite food ") print(food1+food2) input("\n\nPress the enter key to exit.")
#Asks person for favorite song #Replaces "m" with "n" when they enter line from song song = input("Please enter a line from your favorite song ") print(song.replace("o","a")) print(song.replace("m","n")) input("\n\nPress the enter key to exit.")
class Czas: """Stwórz klasę Czas, której konstruktor (__init__) będzie brał trzy opcjonalne argumenty, godzine, minuty, sekundy i zapisywal je w odpowiednich zmiennych w klasie.""" def __init__(self, h=0, mins=0, sec=0): self.h = h self.mins = mins self.sec = sec def __str__(self): # return "Czas: h = {}m = } s={}".format(self.h, self.mins, self.sec) temp = "{}".format(self._get_name()) for atr in dir(self): if not atr.startwith("_") and not callable(getattr(self, atr)): temp += "{}{} ".format(atr, getattr(self, atr)) return temp @classmethod def _get_name(cls): return cls.__name__ def set_time(self, h = None, mins = None, sec = None): self.h = h self.mins = mins self.sec = sec if h: self.h = h if mins: self.mins = mins if sec: self.sec = sec #self.sec = s or self.sec (jako alternatywa) def add_time(self, h=None, mins=None, sec=None): if s: if self.s + s > 59 self.mins += 1 self.s = self.s +s = 60 else: self.s += s if m: self.mins += mins if self.mins // 60 >= 1: self.h += self.m //60 self.m = self.m % 60 # # get_seconds(self): # pass # # get_minutes(self): # pass # # get_hours(self): # pass class Zegar(Czas): def __init__(self, time_format, *args, **kwargs): super().__init__(*args, **kwargs) self.time_format = time_format class DokladnyZegar(Zegar): def _init__(self, *args, ms=0, **kwargs): super().__init__(*args, **kwargs) self.ms = ms def set_time(self, ms=None, **kwargs): super().set_time(kwargs) if ms: self.ms = ms def mojprint(): pass zeg = DokladnyZegar('12H', h = 20, ms = 44 mins=44, sec=45) print(zeg)
mapdict = {10:'A', 11:'B', 12:'C', 13:'D', 14:'E', 15:'F'} '''def convert(number,n): answer = '' if number // n < 1: remain = number % n if remain >= 10: remain = mapdict[remain] answer = str(remain) + answer while number // n >=1: remain = number % n if remain >= 10: remain = mapdict[remain] number = number // n answer = str(remain) + answer if n > number: if number >= 10: number = mapdict[number] answer = str(number) + answer return answer''' def convert(num, n): arr = "0123456789ABCDEF" ret = '' if num == 0: return '0' while num > 0: ret = arr[num % n] + ret num = num // n return ret def solution(n, t, m, p): i = 0 res = [] while True: _i = convert(i, n) res += list(_i) if len(res) > m*t: break i += 1 answer = '' for j in range(p-1, t*m, m): answer += res[j] answer = answer[:t] return answer
s=''' <35 F 35 to 59 D 60 to 79 C 80 to 89 B 90 to 100 A ''' print(s) m=int(input("\nPlease Enter your Marks:\n")) if(m<35): print("F") elif(m>=35 and m<60): print("D") elif(m>=60 and m<80): print("C") elif(m>=80 and m<90): print("B") elif(m>=90 and m<101): print("A") else: print("Invalid") # not if(not False): print("hhh") if(3!=6): print("fdsfsdhhh") if(3 is not 6): print("dkhsdfkdkhdgkdgkjdkjdghhh")
from PIL import Image def resize(img_names,size=(200,200)): for img_name in img_names: img=Image.open(img_name) img=img.resize(size) img.save("resized"+img_name) img_names=["1.jpg","2.jpg","3.jpg"] resize(img_names) print("____________\n\n") #cropping img=Image.open("1.jpg") img.show() img=img.crop((100,100,400,400)) img=img.rotate(90) img.show()
#requests library to get the HTML content of the website import requests #urllib library to parse the URL links from urllib.parse import urlparse, urljoin #HTMLParser library is used to parse the HTML content scraped using requests from html.parser import HTMLParser internal_urls = set() hrefs = [] #since all anchor tags are not valid, this function will make sure that proper scheme and domain name exists in the URL. def is_valid(url): parsed = urlparse(url) return bool(parsed.netloc) and bool(parsed.scheme) #handle_starttag parses the HTML content to take anchor tag data. hrefs is a list that contains all the URLs in it. class MyHTMLParser(HTMLParser): def handle_starttag(self, tag, attrs): if tag != 'a': return attr = dict(attrs) href = attr["href"] hrefs.append(href) #This function returns all URLs that is found on `url` in which it belongs to the same website def get_all_website_links(url): # all URLs of `url urls = set() # domain name of the URL without the protocol domain_name = urlparse(url).netloc html = requests.get(url) parser = MyHTMLParser() parser.feed(html.text) for href in hrefs: if href == "" or href is None: # href empty tag continue #Since not all links are absolute join the URL if it's relative href = urljoin(url, href) parsed_href = urlparse(href) href = parsed_href.scheme + "://" + parsed_href.netloc + parsed_href.path if not is_valid(href): # not a valid URL continue if href in internal_urls: # already in the set continue if domain_name not in href: # external link continue urls.add(href) internal_urls.add(href) #file that stores all the internal links f = open("links.txt", "a") f.write(href+'\n') f.close() return urls # number of urls visited so far will be stored here total_urls_visited = 0 #this function gets all the links of the first page and then call itself recursively to follow all the links extracted previously. def crawl(url, max_urls=50): global total_urls_visited total_urls_visited += 1 links = get_all_website_links(url) for link in links: if total_urls_visited > max_urls: break crawl(link, max_urls=max_urls) if __name__ == "__main__": crawl("https://www.medium.com")
prob_failure = .10 three_fails_prob = 1.0 for i in range(0,3): three_fails_prob = three_fails_prob * prob_failure print("Probability of 3 consecutive failures: {}".format(three_fails_prob))
""" Question: Given an array of integers, return a new array such that each element at index i of the new array is the product of all the numbers in the original array except the one at i. For example, if our input was [1, 2, 3, 4, 5], the expected output would be [120, 60, 40, 30, 24]. If our input was [3, 2, 1], the expected output would be [2, 3, 6]. Follow-up: what if you can't use division? """ def new_prod_array(input_array): """ creates a new array with product of all element but 1 Args: input array Returns: new prod array """ new_array = [] prod = 1 for elem in input_array: prod = prod*elem for elem in input_array: new_array.append(prod//elem) return new_array a = [1, 2, 3, 4, 5] assert (new_prod_array(a) == [120, 60, 40, 30, 24]),"Failed" print(new_prod_array(a)) """ TIME COMPLEXITY: O(n) 2 un cascaded for loops SPACE COMPLEXITY : O(n) storing the entire new array and prod """ # WITHOUT DIVISION # can also be done with multiple cascaded for loops in longer time import math def new_prod_array(input_array): """ creates a new array with product of all element but 1 Args: input array Returns: new prod array """ new_array = [] sum1 = 0 for elem in input_array: sum1 = sum1 + math.log10(elem) for elem in input_array: new_array.append(round(pow(10,sum1-math.log10(elem)))) return new_array a = [1, 2, 3, 4, 5] print(new_prod_array(a)) assert (new_prod_array(a) == [120, 60, 40, 30, 24]),"Failed" """ TIME COMPLEXITY: O(n) 2 un cascaded for loops SPACE COMPLEXITY : O(n) storing the entire new array and prod """
list1 = [int(i) for i in input().split()] x = int(input()) if x in list1: for i in range(len(list1)): if list1[i] == x: print(i, end=' ') else: print('Отсутствует')
#!/usr/bin/python # Haversine formula example in Python # Author: Wayne Dyck import math def distance(origin, destination): lat1, lon1 = origin lat2, lon2 = destination radius = 6371000 # m dlat = math.radians(lat2-lat1) dlon = math.radians(lon2-lon1) a = math.sin(dlat/2) * math.sin(dlat/2) + math.cos(math.radians(lat1)) \ * math.cos(math.radians(lat2)) * math.sin(dlon/2) * math.sin(dlon/2) c = 2 * math.atan2(math.sqrt(a), math.sqrt(1-a)) d = radius * c return d # TODO - Improve method - faster, better result (lat_distance and lon_distance lower) def latLonFromCentLatLon(centlat, centlon, nnxp, nnyp, deltax, deltay): dist_y = nnyp * deltay dist_x = nnxp * deltax lat_distance = 0 while lat_distance < 90: lat_distance += 0.05 lat_up = centlat + lat_distance lat_down = centlat - lat_distance lon_distance = 0 while lon_distance < 90: lon_distance += 0.05 lon_left = centlon - lon_distance lon_right = centlon + lon_distance lon_dist = distance((lat_up, lon_left), (lat_up, lon_right)) lat_dist = distance((lat_up, lon_left), (lat_down, lon_left)) if lat_dist >= dist_y and lon_dist >= dist_x: return lat_up, lat_down, lon_left, lon_right
#Comment """ Multiline Comment """ print("Welcome To Our TFP Calc") firstNum = int(input("Enter The First Number")) operator = str(input("Enter The Operator")) secondNumm = int(input("Enter The Second Number")) def Calculator(): if operator == "+": print(firstNum + secondNumm) elif operator == "-": print(firstNum - secondNumm) elif operator == "*": print(firstNum * secondNumm) elif operator == "/": print(firstNum / secondNumm) else: print("Please Check Your Operator. And Try Again!") Calculator()
from collections import namedtuple q = namedtuple('Q', 'question') def line_to_q(line): return q(question=line.rstrip("\n")) def q_to_line(q): return "%s\n" % q.question def csv_to_qs(csv_file): with open(csv_file, encoding='utf-8') as f: qs = f.readlines() qs = [line_to_q(l) for l in qs] return qs
import math import unittest def statement(invoice, plays): total_amount = 0 volume_credits = 0 result = f'Statement for {invoice["customer"]}\n' def format_as_dollars(amount): return f"${amount:0,.2f}" for perf in invoice['performances']: play = plays[perf['playID']] if play['type'] == "tragedy": this_amount = 40000 if perf['audience'] > 30: this_amount += 1000 * (perf['audience'] - 30) elif play['type'] == "comedy": this_amount = 30000 if perf['audience'] > 20: this_amount += 10000 + 500 * (perf['audience'] - 20) this_amount += 300 * perf['audience'] else: raise ValueError(f'unknown type: {play["type"]}') # add volume credits volume_credits += max(perf['audience'] - 30, 0) # add extra credit for every ten comedy attendees if "comedy" == play["type"]: volume_credits += math.floor(perf['audience'] / 5) # print line for this order result += f' {play["name"]}: {format_as_dollars(this_amount/100)} ({perf["audience"]} seats)\n' total_amount += this_amount result += f'Amount owed is {format_as_dollars(total_amount/100)}\n' result += f'You earned {volume_credits} credits\n' return result class statementTest(unittest.TestCase): def test_comedy_audience_more_than_30(self): self.assertEqual("Statement for BigCo\n As You Like It: $580.00 (35 seats)\nAmount owed is $580.00\nYou earned 12 credits\n", statement({"customer": "BigCo", "performances": [{"playID": "as-like","audience": 35}]}, {"as-like": {"name": "As You Like It", "type": "comedy"}})) def test_comedy_audience_less_than_30(self): self.assertEqual( "Statement for BigCo\n As You Like It: $360.00 (20 seats)\nAmount owed is $360.00\nYou earned 4 credits\n", statement({"customer": "BigCo", "performances": [{"playID": "as-like", "audience": 20}]}, {"as-like": {"name": "As You Like It", "type": "comedy"}})) def test_tragedy_audience_less_than_20(self): self.assertEqual( "Statement for BigCo\n Hamlet: $400.00 (10 seats)\nAmount owed is $400.00\nYou earned 0 credits\n", statement({"customer": "BigCo", "performances": [{"playID": "hamlet", "audience": 10}]}, {"hamlet": {"name": "Hamlet", "type": "tragedy"}})) def test_tragedy_audience_more_than_20(self): self.assertEqual( "Statement for BigCo\n Hamlet: $500.00 (40 seats)\nAmount owed is $500.00\nYou earned 10 credits\n", statement({"customer": "BigCo", "performances": [{"playID": "hamlet", "audience": 40}]}, {"hamlet": {"name": "Hamlet", "type": "tragedy"}})) def test_tragedy_audience_more_than_20_and_comedy_audience_more_than_30(self): self.assertEqual( "Statement for BigCo\n Hamlet: $500.00 (40 seats)\n As You Like It: $580.00 (35 seats)\nAmount owed is $1,080.00\nYou earned 22 credits\n", statement({"customer": "BigCo", "performances": [{"playID": "hamlet","audience": 40}, {"playID": "as-like","audience": 35}]}, {"hamlet": {"name": "Hamlet", "type": "tragedy"}, "as-like": {"name": "As You Like It", "type": "comedy"}})) def test_tragedy_audience_less_than_20_and_comedy_audience_more_than_30(self): self.assertEqual( "Statement for BigCo\n Hamlet: $400.00 (10 seats)\n As You Like It: $580.00 (35 seats)\nAmount owed is $980.00\nYou earned 12 credits\n", statement({"customer": "BigCo", "performances": [{"playID": "hamlet","audience": 10}, {"playID": "as-like","audience": 35}]}, {"hamlet": {"name": "Hamlet", "type": "tragedy"}, "as-like": {"name": "As You Like It", "type": "comedy"}})) def test_tragedy_audience_more_than_20_and_comedy_audience_less_than_30(self): self.assertEqual( "Statement for BigCo\n Hamlet: $500.00 (40 seats)\n As You Like It: $330.00 (10 seats)\nAmount owed is $830.00\nYou earned 12 credits\n", statement({"customer": "BigCo", "performances": [{"playID": "hamlet","audience": 40}, {"playID": "as-like","audience": 10}]}, {"hamlet": {"name": "Hamlet", "type": "tragedy"}, "as-like": {"name": "As You Like It", "type": "comedy"}})) def test_tragedy_audience_less_than_20_and_comedy_audience_less_than_30(self): self.assertEqual( "Statement for BigCo\n Hamlet: $400.00 (5 seats)\n As You Like It: $315.00 (5 seats)\nAmount owed is $715.00\nYou earned 1 credits\n", statement({"customer": "BigCo", "performances": [{"playID": "hamlet","audience": 5}, {"playID": "as-like","audience": 5}]}, {"hamlet": {"name": "Hamlet", "type": "tragedy"}, "as-like": {"name": "As You Like It", "type": "comedy"}})) def test_no_performances(self): self.assertEqual( "Statement for BigCo\nAmount owed is $0.00\nYou earned 0 credits\n", statement({"customer": "BigCo", "performances": []}, {"hamlet": {"name": "Hamlet", "type": "tragedy"}})) def test_empty_plays_raises_key_error(self): with self.assertRaises(KeyError): statement({"customer": "BigCo", "performances": [{"playID": "hamlet", "audience": 10}]}, {}) def test_no_play_with_given_id_raises_key_error(self): with self.assertRaises(KeyError): statement({"customer": "BigCo", "performances": [{"playID": "hamlet", "audience": 10}]}, {"othello": {"name": "Othello", "type": "tragedy"}}) def test_no_audience_raises_key_error(self): with self.assertRaises(KeyError): statement({"customer": "BigCo", "performances": [{"playID": "hamlet"}]}, {"hamlet": {"name": "Hamlet", "type": "tragedy"}}) def test_wrong_type_raises_value_error(self): with self.assertRaises(ValueError): statement({"customer": "BigCo", "performances": [{"playID": "hamlet", "audience": 10}]}, {"hamlet": {"name": "Hamlet", "type": "asdasd"}}) def test_empty_invoice_raises_key_error(self): with self.assertRaises(KeyError): statement({}, {"hamlet": {"name": "Hamlet", "type": "asdasd"}}) if __name__ == "__main__": unittest.main()
#Предварительная обработка данных import numpy as np from sklearn import preprocessing input_data = np.array([[2.1, -1.9, 5.5], [-1.5, 2.4, 3.5], [0.5, -7.9, 5.6], [5.9, 2.3, -5.8]]) # Применение методов предварительной обработки # Бинаризация data_binarized = preprocessing.Binarizer(threshold = 0.5).transform(input_data) print("\tБинаризация\n", data_binarized) # Среднее удаление print("\n\tСреднее удаление\nmean = ", input_data.mean(axis = 0)) # Средние значение print("Standart deviation = ", input_data.std(axis = 0)) # Среднее отклонение data_scaled = preprocessing.scale(input_data) print("standart deviation = ", data_scaled.std(axis = 0)) # Пересчет data_scaler_minmax = preprocessing.MinMaxScaler(feature_range=(0,1)) data_scaled_minmax = data_scaler_minmax.fit_transform(input_data) # Вычисление -> преобразование print ("\n\tПересчет\n", data_scaled_minmax) #Нормализация data_normalized_l1 = preprocessing.normalize(input_data, norm = 'l1') print("\n\tL1 нормализация\n", data_normalized_l1) data_normalized_l2 = preprocessing.normalize(input_data, norm = 'l2') print("\n\tL2 нормализация\n", data_normalized_l2)
#break i=1 while i <= 5: if i==4: print('吃够了') break i +=1 #continue i=1 while i<=5: if i==3: print('跳过3') i +=1 continue print(i) i+=1
print('创建⼀个0-10的列表。') print('--------------while循环实现-------------------') list1=[] i=0 while i<=10: list1.append(i) i+=1 print(list1) print('---------------for循环实现------------------') list1=[] for i in range(10+1): list1.append(i) print(list1) print('-----------------列表推导式实现----------------') list2 = [i for i in range(10+1)] print(list2) print('需求:创建0-10的偶数列表') print('-----------带if的列表推导式----------------------') list1 = [i for i in range(0,33,2)] print(list1) list1=[i for i in range(20) if i%2 == 0] print(list1) print('-------------多个for循环实现列表推导式--------------------') #[(1, 0), (1, 1), (1, 2), (2, 0), (2, 1), (2, 2)] list1=[(i,j) for i in range (1,3) for j in range (3)] print(list1) list1=[(i,j) for i in range (1,10) if i%2 ==0 for j in range (3)] print(list1) print('--------------字典推导式-------------------') print('----------------字典key是1-5数字,value是这个数字的2次⽅。-----------------') #字典key是1-5数字,value是这个数字的2次⽅。 dict1 ={i:i**2 for i in range(1,5)} print(dict1) i=0 dict1={} for i in range(1,5): dict1[i]=i**2 i+=1 print(dict1) print('----------------将两个列表合并为⼀个字典-----------------') list1 = ['name', 'age', 'gender'] list2 = ['Tom', 20, 'man'] dict1 ={list1[i]:list2[i] for i in range(len(list1))} print(dict1) print('------------------提取字典中⽬标数据---------------') counts = {'MBP': 268, 'HP': 125, 'DELL': 201, 'Lenovo': 199, 'acer': 99} count1={key:value for key,value in counts.items() if value>=200} print(count1) print('-------------创建⼀个集合,数据为下⽅列表的2次⽅--------------------') list1 = [1, 1, 2,3] set1 ={i **2 for i in list1} print(set1) print('---------------------------------')
print('-------创建集合使⽤ {} 或 set() , 但是如果要创建空集合只能使⽤ set() ,因为 {} ⽤来创建空字典。---------------') s1={10,20,30,40,50} print(s1) s2={10,20,30,40,50,30,40,50,}#集合自动去重、无序 print(s2) s3=set('qweew') print(s3) s4 =set() #集合类型 print(type(s4)) s5={} #字典类型 print(type(s5)) print('------------add()当向集合内追加的数据是当前集合已有数据的话,则不进⾏任何操作。----------') s1={100,200} s1.add(100) s1.add(111) print(s1) print('-----------update(), 追加的数据是序列。-----------') s1={100,200} #s1.update(125) TypeError: 'int' object is not iterable s1.update([100,200,300]) s1.update('sdsdd') print(s1) print('------------remove(),删除集合中的指定数据,如果数据不存在则报错。----------') s1 = {10, 20} s1.remove(10) print(s1) #s1.remove(10) KeyError: 10 数据不存在则报错 print('---------discard(),删除集合中的指定数据,如果数据不存在也不会报错。-------------') s1 = {10, 20} s1.discard(10) print(s1) s1.discard(10) print(s1) print('---------pop(),随机删除集合中的某个数据,并返回这个数据。-------------') s1 = {10, 20, 30, 40, 51, 40} delNum=s1.pop() print(delNum) print(s1) fruits = {"apple", "banana", "cherry"} x = fruits.pop() print(fruits) print(x) print('---------in:判断数据在集合序列-------------') s1 = {10, 20, 30, 40, 50} print(10 in s1) print(13 in s1) print('----------not in:判断数据不在集合序列------------') s1 = {10, 20, 30, 40, 50} print(10 not in s1) print(13 not in s1)
import functools list1=[2,3,5,76,8] def func(a,b): return a+b res=functools.reduce(func,list1) print(res)
mystr = "hello world and supertest and chaoge and Python" #count统计出现次数 print(mystr.count('and')) print(mystr.count('ands')) print(mystr.count('and',0,30))
''' How it works? Its the same as homework2 except that every eval function (of the Cexp classes) returns the next command to be executed and the current state. How it prints the command? By an INORDER traversal of the tree recursively. Every class has a printx() function, that calls the printx() function of its children. ''' class State: def __init__(self): self.dictx={} def read(self,x): a=self.dictx.get(x,-1) return a def write(self,x,val): self.dictx[x]=val def getall(self): return self.dictx.keys() def printstate(self): statestack=['{'] for el in self.dictx: statestack.append(str(el)) statestack.append(':') statestack.append(str(self.dictx[el])) statestack.append(',') if len(statestack)>1: statestack.pop() statestack.append('}') return "".join(statestack) class Aexp: def __init__(self,a1): self.left=a1 def eval(self,sx): if type(self.left)==int: return self.left elif type(self.left)==Var: return sx.read(self.left.varname()) else: return self.left.eval(sx) def printx(self,stck): if type(self.left)==int: stck.append(str(self.left)) elif type(self.left)==Var: stck.append(self.left.varname()) else: stck.extend(self.left.printx([])) return stck class Add: def __init__(self,left,right): #left is Aexp and right is Aexp self.left=left self.right=right def eval(self,sx): return self.left.eval(sx)+self.right.eval(sx) def printx(self,stck): # self.left.printx() # print('+') # self.right.printx() stck.extend(self.left.printx([])) stck.append("+") stck.extend(self.right.printx([])) return stck class Sub: def __init__(self,left,right): #left is Aexp and right is Aexp self.left=left self.right=right def eval(self,sx): return self.left.eval(sx)-self.right.eval(sx) def printx(self,stck): stck.extend(self.left.printx([])) stck.append("-") stck.extend(self.right.printx([])) return stck class Mul: def __init__(self,left,right): self.left=left self.right=right def eval(self,sx): return self.left.eval(sx)*self.right.eval(sx) def printx(self,stck): stck.extend(self.left.printx([])) stck.append("*") stck.extend(self.right.printx([])) #Boolean expressions and their derived classes class Bexp: def __init__(self,a1): self.left=a1 def eval(self,sx): if type(self.left)==bool: return self.left else: return self.left.eval(sx) def printx(self,stck): #self.left.printx() stck.extend(self.left.printx([])) return stck class OpAnd: def __init__(self,a,b): self.a=a self.b=b def eval(self,sx): return self.a.eval(sx) and self.b.eval(sx) def printx(self,stck): # self.a.printx() # print('AND') # self.b.printx() stck.extend(self.a.printx([])) stck.append("<") stck.extend(self.b.printx([])) return stck class OpOr: def __init__(self,a,b): self.a=a self.b=b def eval(self,sx): return self.a.eval(sx) or self.b.eval(sx) def printx(self,stck): stck.extend(self.a.printx([])) stck.append("<") stck.extend(self.b.printx([])) return stck class Equalto: def __init__(self,a,b): self.a=a self.b=b def eval(self,sx): if self.a.eval(sx)==self.b.eval(sx): return True else: return False def printx(self,stck): stck.extend(self.a.printx([])) stck.append("==") stck.extend(self.b.printx([])) return stck class LessThan: def __init__(self,a,b): self.a=a self.b=b def eval(self,sx): if self.a.eval(sx)<self.b.eval(sx): return True else: return False def printx(self,stck): stck.extend(self.a.printx([])) stck.append("<") stck.extend(self.b.printx([])) return stck #Cexp and derived classes class Var: def __init__(self,x): self.x=x def eval(self,sx): return sx.read(self.x) def varname(self): return self.x def printx(self,stck): stck.append(self.x) return stck class Assign: def __init__(self,varx,valx): #varx is of type Var and valx is of type Aexp self.varx=varx self.valx=valx def eval(self,sx): p=self.varx.varname() q=self.valx.eval(sx) sx.write(p,q) s1=Skip() return s1,sx def printx(self,stck): stck.extend(self.varx.printx([])) stck.append(":=") stck.extend(self.valx.printx([])) return stck class Cexp: def __init__(self,a): self.a=a def eval(self,sx): return self.a.eval(sx) def printx(self,stck): stck.extend(self.a.printx([])) return stck class Skip: def __init__(self): sopos=0 def eval(self): return None def printx(self,stck): stck.append('Skip') return stck class IfElse: def __init__(self,a,b,c): self.a=a self.b=b self.c=c def eval(self,sx): stat=self.a.eval(sx) if stat==True: return self.b,sx else: return self.c,sx def printx(self,stck): stck.append('If ') stck.extend(self.a.printx([])) stck.append(' Then ') stck.extend(self.b.printx([])) stck.append(' Else ') stck.extend(self.c.printx([])) return stck class While: def __init__(self,a,b): self.a=a self.b=b def eval(self,sx): stat=self.a.eval(sx) if stat==True: s1=Seq(self.b,self) return s1,sx else: return Skip(),sx def printx(self,stck): stck.append('While ') stck.extend(self.a.printx([])) stck.append(' Do ') stck.extend(self.b.printx([])) return stck class Seq: def __init__(self,a,b): #a is a Cexp and b is a Cexp self.a=a self.b=b def eval(self,sx): if type(self.a)==Assign: temp=self.a.eval(sx) ax=Seq(temp[0],self.b) return ax, temp[1] #returned the state elif type(self.a)==Seq: rexx=self.a.eval(sx) #returns the state after executing the first command of the left x1=Seq(rexx[0],self.b) return x1,rexx[1] elif type(self.a)==Skip: #print(type(self.b)) return self.b,sx elif type(self.a)==IfElse: rex=self.a.eval(sx) s1=Seq(rex[0],self.b) return s1,rex[1] elif type(self.a)==While: rex=self.a.eval(sx) s1=Seq(rex[0],self.b) return s1,rex[1] elif type(self.a)==Cexp: rex=self.a.eval(sx) s1=Seq(rex[0],self.b) return s1,rex[1] def printx(self,stck): stck.extend(self.a.printx([])) stck.append('; ') stck.extend(self.b.printx([])) return stck #--------------------------------------------------------------THE MAIN FUNCTION------------------------------------------------- def run_this_system(p1): #the main function that executes and prints s1=State() structx=[p1,s1] res0=structx[0].printx([]) print("<","".join(res0),s1.printstate(),">") while type(structx[0])!=Skip: resx=structx[0].eval(structx[1]) res1=resx[0].printx([]) print("<","".join(res1),resx[1].printstate(),">") del structx[:] structx.extend(resx) #----------------------------------------------------------------------TEST CASES------------------------------------------------- #test case1 ''' x=5; y=25; while x<y: x=x+2 y=y-2 ''' s1=State() incr1=Aexp(Add(Var('x'),Aexp(2))) decr1=Aexp(Sub(Var('x'),Aexp(2))) x1=Cexp(Assign(Var('x'),Aexp(5))) y1=Cexp(Assign(Var('y'),Aexp(25))) xy1=Seq(incr1,decr1) b1=Bexp(LessThan(Var('x'),Var('y'))) wh1=While(b1,xy1) p1=Seq(x1,y1) p2=Seq(p1,wh1) #testcase2: ''' x=5; if x<6: x=x+1 else: x=x-1 ''' xx1=Cexp(Assign(Var('x'),Aexp(5))) bb1=Bexp(LessThan(Var('x'),Aexp(6))) xplus=Cexp(Assign(Var('x'),incr1)) xminus=Cexp(Assign(Var('x'),decr1)) ie=Cexp(IfElse(bb1,xplus,xminus)) finalx=Seq(xx1,ie) #res0=finalx.printx([]) #print("<","".join(res0),s1.printstate(),">") #test_case3: #this test case includes a while, an if-else, a comparison, ''' a=5; b=11; while a<b: a=a+1; b=b-1; if a==b: a=a+b; b=0; else: b=a+b; a=0 ''' a1=Cexp(Assign(Var('a'),Aexp(5))) b1=Cexp(Assign(Var('b'),Aexp(11))) seq1=Seq(a1,b1) cond1=Bexp(LessThan(Var('a'),Var('b'))) add1=Cexp(Assign(Var('a'),Aexp(Add(Var('a'),Aexp(1))))) sub1=Cexp(Assign(Var('b'),Aexp(Sub(Var('b'),Aexp(1))))) seq2=Seq(add1,sub1) wh1=Cexp(While(cond1,seq2)) #while statement cond2=Bexp(Equalto(Var('a'),Var('b'))) add2=Cexp(Assign(Var('a'),Aexp(Add(Var('a'),Var('b'))))) b0=Cexp(Assign(Var('b'),Aexp(0))) seq3=Seq(add2,b0) add3=Cexp(Assign(Var('b'),Aexp(Add(Var('a'),Var('b'))))) a0=Cexp(Assign(Var('a'),Aexp(0))) seq4=Seq(add3,a0) ifel1=Cexp(IfElse(cond2,seq3,seq4)) #ifelse seq5=Seq(wh1,ifel1) seq6=Seq(seq1,seq5) #------------------------------------------------------RUN THE TEST CASES-------------------------------------------------------- print("\n") run_this_system(seq6) #pass 'finalx' in place of 'seq6' if you want to run test case 2, and 'p2' if you want to run test case 1 #The output of the above test case is as follows ''' < a:=5; b:=11; While a<b Do a:=a+1; b:=b-1; If a==b Then a:=a+b; b:=0 Else b:=a+b; a:=0 {} > < Skip; b:=11; While a<b Do a:=a+1; b:=b-1; If a==b Then a:=a+b; b:=0 Else b:=a+b; a:=0 {a:5} > < b:=11; While a<b Do a:=a+1; b:=b-1; If a==b Then a:=a+b; b:=0 Else b:=a+b; a:=0 {a:5} > < Skip; While a<b Do a:=a+1; b:=b-1; If a==b Then a:=a+b; b:=0 Else b:=a+b; a:=0 {b:11,a:5} > < While a<b Do a:=a+1; b:=b-1; If a==b Then a:=a+b; b:=0 Else b:=a+b; a:=0 {b:11,a:5} > < a:=a+1; b:=b-1; While a<b Do a:=a+1; b:=b-1; If a==b Then a:=a+b; b:=0 Else b:=a+b; a:=0 {b:11,a:5} > < Skip; b:=b-1; While a<b Do a:=a+1; b:=b-1; If a==b Then a:=a+b; b:=0 Else b:=a+b; a:=0 {b:11,a:6} > < b:=b-1; While a<b Do a:=a+1; b:=b-1; If a==b Then a:=a+b; b:=0 Else b:=a+b; a:=0 {b:11,a:6} > < Skip; While a<b Do a:=a+1; b:=b-1; If a==b Then a:=a+b; b:=0 Else b:=a+b; a:=0 {b:10,a:6} > < While a<b Do a:=a+1; b:=b-1; If a==b Then a:=a+b; b:=0 Else b:=a+b; a:=0 {b:10,a:6} > < a:=a+1; b:=b-1; While a<b Do a:=a+1; b:=b-1; If a==b Then a:=a+b; b:=0 Else b:=a+b; a:=0 {b:10,a:6} > < Skip; b:=b-1; While a<b Do a:=a+1; b:=b-1; If a==b Then a:=a+b; b:=0 Else b:=a+b; a:=0 {b:10,a:7} > < b:=b-1; While a<b Do a:=a+1; b:=b-1; If a==b Then a:=a+b; b:=0 Else b:=a+b; a:=0 {b:10,a:7} > < Skip; While a<b Do a:=a+1; b:=b-1; If a==b Then a:=a+b; b:=0 Else b:=a+b; a:=0 {b:9,a:7} > < While a<b Do a:=a+1; b:=b-1; If a==b Then a:=a+b; b:=0 Else b:=a+b; a:=0 {b:9,a:7} > < a:=a+1; b:=b-1; While a<b Do a:=a+1; b:=b-1; If a==b Then a:=a+b; b:=0 Else b:=a+b; a:=0 {b:9,a:7} > < Skip; b:=b-1; While a<b Do a:=a+1; b:=b-1; If a==b Then a:=a+b; b:=0 Else b:=a+b; a:=0 {b:9,a:8} > < b:=b-1; While a<b Do a:=a+1; b:=b-1; If a==b Then a:=a+b; b:=0 Else b:=a+b; a:=0 {b:9,a:8} > < Skip; While a<b Do a:=a+1; b:=b-1; If a==b Then a:=a+b; b:=0 Else b:=a+b; a:=0 {b:8,a:8} > < While a<b Do a:=a+1; b:=b-1; If a==b Then a:=a+b; b:=0 Else b:=a+b; a:=0 {b:8,a:8} > < Skip; If a==b Then a:=a+b; b:=0 Else b:=a+b; a:=0 {b:8,a:8} > < If a==b Then a:=a+b; b:=0 Else b:=a+b; a:=0 {b:8,a:8} > < a:=a+b; b:=0 {b:8,a:8} > < Skip; b:=0 {b:8,a:16} > < b:=0 {b:8,a:16} > < Skip {b:0,a:16} > '''
# Basically just a function that uses a "yield" command to return data to the caller, similar to an iterator but without defining a next() method. def reverse(data): for index in range(len(data)-1, -1, -1): yield data[index]
from my_mod import enlarge from pandas import DataFrame print("HELLO") df = DataFrame({"a": [1, 2, 3], "b": [4, 5, 6]}) print(df) x = 11 print(enlarge(x))
# coding=utf-8 class Singleton_Lazy(object): __instance = None def __init__(self): if not Singleton_Lazy.__instance: print("I have already got an instance!") else: print("I don't have got an instance!") @classmethod def getInstance(cls): if not cls.__instance: cls.__instance = Singleton_Lazy() return cls.__instance class Singleton_Strict(object): def __new__(cls, *args, **kwargs): if not hasattr(cls, 'instance'): cls.instance = super(Singleton_Strict, cls).__new__(cls) return cls.instance sl = Singleton_Lazy() sl2 = Singleton_Lazy() print("sl: %s, sl2: %s" % (sl.getInstance(), sl2.getInstance())) ss = Singleton_Strict() ss2 = Singleton_Strict() print('ss: %s, ss2: %s' % (ss, ss2))
start = "487912365" # start = "389125467" cups = [int(c) for c in start] mincup = min(cups) maxcup = max(cups) current = cups[0] moves = 100 def pick3(cups,current): # print(cups, current) temp = cups.copy() temp.extend(cups) # print(temp, current) # print(current in temp) curr_index = temp.index(current) triplet = temp[curr_index+1:curr_index+4] new = [i for i in temp if i not in triplet] new = new[:len(cups)-3] return triplet, new for move in range(moves): print(cups,current) triplet, rest = pick3(cups,current) print(triplet, rest) dest = current-1 if dest == 0: dest = 9 while dest in triplet: dest -= 1 if dest == 0: dest = 9 print("Destination:",dest,"\n") d_i = rest.index(dest) cups = rest[:d_i+1]+triplet+rest[d_i+1:] c_i = cups.index(current) if c_i == len(cups)-1: current = cups[0] else: current = cups[c_i+1] print(cups)
# Compute the Powerset of a list # items = [1, 2] # powerset = [[], [1], [2], [1, 2]] import itertools def potenzmenge(items): powerset = [x for length in range(len(items)+1) for x in itertools.combinations(items, length)] return powerset def min_potenzmenge(items): powerset = [x for length in range(len(items)+1) for x in itertools.combinations(items, length)] return powerset
__author__ = 'nolanemirot' def gridChallenge(arr): tmp = 'a' for e in arr: if tmp <= e: tmp = e else: return False return True def checkColumn(arr, wl): x = 0 while x < wl: y = 0 tmp = 'a' while y < wl: elemen = arr[y][x] if tmp <= elemen: tmp = elemen else: return False y += 1 x += 1 return True if __name__ == '__main__': nb_test_case = int(input()) for i in range(nb_test_case): size = int(input()) l = "" c = [] for e in range(size): line = input() a = gridChallenge(sorted(line)) b = sorted(line) c.append(b) if a == "NO": print(a) break if checkColumn(c, size): print("YES") else: print("NO")
__author__ = 'nolanemirot' def stringCompression(string): s = "" i = 0 count = 0 end = "" while i < len(string)-1: if string[i] == string[i+1]: count+=1 else : s+= string[i] + str(count+1) count = 0 i+=1 end = string[i] if(string[len(string)-1]== end): count+=1 s += string[i] + str(count) print(s) if __name__ == '__main__': stringCompression("aacvvvvvbbbbb")
__author__ = 'nolanemirot' def traverse(graph, start): traversed = [] stack = [start] while stack: v = stack.pop() if v not in traversed: traversed.append(v) for n in graph[v]: stack += n print(traversed) if __name__ == '__main__': graph = {'A':['B','C'],'B':['F','G'],'F':['A'],'G':[],'C':[]} edge = traverse(graph, 'A')
__author__ = 'nolanemirot' import math class Point(): def __init__(self, x, y,z): self.x = x self.y = y self.z = z def __sub__(self, other): xx = self.x - other.x yy = self.y - other.y zz = self.z - other.z return Point(xx, yy, zz) def __mul__(self, other): xx = self.y * other.z - self.z * other.y yy = self.z * other.x - self.x * other.z zz = self.x * other.y - self.y * other.x return Point(xx, yy, zz) def dot(self, other): xx = self.x * other.x yy = self.y * other.y zz = self.z * other.z return xx + yy + zz def absolute_val(self): return math.sqrt(self.x **2 + self.y **2 + self.z ** 2) if __name__ == '__main__': ax ,ay, az = map(float, input().split()) a = Point(ax, ay, az) bx ,by, bz = map(float, input().split()) b = Point(bx, by, bz) cx , cy, cz = map(float, input().split()) c = Point(cx, cy, cz) cx , cy, cz = map(float, input().split()) d = Point(cx, cy, cz) X = (b - a) * (c - b) Y = (c - b) * (d - c) A = X * Y XX = X.absolute_val() YY = Y.absolute_val() res = (X.dot(Y)) / (XX * YY) res = math.acos(res) print("%.2f" % math.degrees(res))
def fibonacci(num): i = 0 arr = [] if num == 0: return 0 if num == 1: return 1 while i <= num: if i < 2: arr.append(i) else: arr.append((arr[i-1]) + arr[i-2]) i += 1 return arr[len(arr)-1] def fibonnaci_rec(num): if num == 0: return 0 if num == 1: return 1 return fibonnaci_rec(num-1) + fibonnaci_rec(num -2) print(fibonacci(0)) print(fibonacci(1)) print(fibonacci(2)) print(fibonacci(3)) print(fibonacci(4)) print(fibonacci(5)) print(fibonacci(6)) print(fibonacci(7)) print("--------------------------") print(fibonnaci_rec(0)) print(fibonnaci_rec(1)) print(fibonnaci_rec(2)) print(fibonnaci_rec(3)) print(fibonnaci_rec(4)) print(fibonnaci_rec(5)) print(fibonnaci_rec(6)) print(fibonnaci_rec(7))
__author__ = 'nolanemirot' nbTestCase = int(input()) def findNbDigit(N): i = 0 a = N rep = "" five = 0 while a > 0: if a % 3 == 0: five = a break a -= 5 trees = N - five if five <= 0 and trees % 5 != 0: return print("-1") while(five > 0): rep += "5" five -= 1 while trees > 0: rep += "3" trees -= 1 print(rep) while nbTestCase > 0: N = int(input()) findNbDigit(N) nbTestCase = nbTestCase - 1
def funny_string(s1, s2): #print("s1:",s1) #print("s2:",s2) i = 1 while i < len(s1): if (abs(ord(s1[i-1])-ord(s1[i])) != abs(ord(s2[i-1])-ord(s2[i]))): return "Not Funny" i += 1 return "Funny" if __name__ == '__main__': nb_test = int(input()) for i in range(0, nb_test): funny = input() print(funny_string(funny, funny[::-1]))
__author__ = 'nolanemirot' def calcGrade(name, dic): arr = dic[name] val = 0.00 for i in arr: val += i print(format(val/len(arr), '.2f')) if __name__ == '__main__': dic = {} nbStudent = int(input()) for i in range(0,nbStudent): line = input() arr = line.split() marks = list(map(float,arr[1:])) dic[arr[0]] = marks name = input() calcGrade(name,dic)
def fill_line(nb_p, nb_s): a = [] for i in range(nb_s): a.append(' ') for i in range(nb_p): a.append('#') return a def print_(arr): for i in arr: for a in i: print(a, end='') print() if __name__ == '__main__': nb_stair_f = int(input()) arr = [] nb_stair = nb_stair_f while nb_stair > 0: p = nb_stair_f - nb_stair arr.insert(0, fill_line(nb_stair, p)) nb_stair -= 1 print_(arr)
stack=[] top=None def addbooks(b): stack.append(b) top=len(stack)-1 def removebooks(): if len(stack)==0: return None else: book=stack.pop() return book top=len(stack)-1 def isempty(): if stack==[]: return True def display(): top=len(stack)-1 print(stack[top],"<--") for a in range(top-1,-1,-1): print(stack[a]) while True: print("") print("|||||||||||||||||||\\\\\\\\\\\||||||||||||||||||") print("Enter 1 to add a book details.") print("Enter 2 to delete book details.") print("Enter 3 to display book details.") print("Enter 4 to quit.") print("||||||||||||||||||||\\\\\\\\\\\|||||||||||||||||||") print("") print("____________________________________") op=int(input("Enter your option::::: ")) print("____________________________________") if op ==1: i=int(input("Enter the book id:::: ")) n=input("Enter the book name:::: ") w=input("Enter the author::: ") x=[i,n,w] addbooks(x) print("Book added!!!") if op==2: if isempty(): print("It's EMPTY..") else: removebooks() print("Book removed!!!") if op==3: if isempty(): print("It's EMPTY..") else: display() if op==4: print("Thankyou!!!") break
def facto(n): fact=1 for i in range(1,n+1): fact=fact*i return fact print("...Factorial of a nuber...") n=int(input("Enter the nuber :")) print("The factorial is",facto(n))
import unittest import math #importing the required maths libraries import numpy as np from math import factorial operation = int(raw_input("Please select a Function: \n 1: Addition \n 2: Subtraction \n 3: Multiplication \n 4: Division \n 5: Exponents \n 6: Fahrenheit-Celcius \n 7: Factorials \n 8: Square Root \n 9: Combination \n 10: nth root\n:")) x = int(raw_input('Please enter your first number: ')) if(operation ==1 or operation == 3 or operation == 3 or operation == 4 or operation == 5 or operation == 9 or operation == 10): #as some functions only require the input of 1 number y = int(raw_input('Please enter your second number: ')) #Creating a class containing 10 functions class Calculator(object): @staticmethod #With staticmethods, neither self (the object instance) # nor cls (the class) is implicitly passed as the first argument. They behave # like plain functions except that you can call them from an instance or the class: def addition(x, y): sum = x + y return sum @staticmethod def divide(x, y): if y == 0: return 'NaN' else: divd = float(x) / float(y) return divd @staticmethod def exponent(x, y): exp = x ** y return exp @staticmethod def multiply(x, y): mult = x * y return mult @staticmethod def subtraction(x, y): sub = x - y return sub @staticmethod def nth_root(x, y): nroot = (x ** (1.0/y)) return nroot @staticmethod def fahrenheit_to_celsius(x): cel = float((x - 32.0) * float(5.0 / 9.0)) return cel @staticmethod def factorial(x): num = 1 while x >= 1: num = num * x x = x - 1 return num @staticmethod def calculate_combinations(x, y): return factorial(x) // factorial(y) // factorial(x - y) @staticmethod def square_root(x): sqr = math.sqrt(x) return sqr if (operation == 1): output1 = Calculator.addition(x,y) print(output1) elif(operation == 2): output2 = Calculator.subtraction(x,y) print(output2) elif(operation == 3): output3 = Calculator.multiply(x,y) print(output3) elif(operation == 4): output4 = Calculator.divide(x,y) print(output4) elif(operation == 5): output5 = Calculator.exponent(x,y) print(output5) elif(operation == 6): output6 = Calculator.fahrenheit_to_celsius(x) print(output6) elif(operation == 7): output7 = Calculator.factorial(x) print(output7) elif(operation == 8): output8 = Calculator.square_root(x) print(output8) elif(operation == 9): output9 = Calculator.calculate_combinations(x,y) print(output9) elif(operation == 10): output10 = Calculator.nth_root(x,y) print(output10)
while True: x = input("输入x:") y = input("输入y:") x = int(x) y = int(y) if (x == 0) & (y == 0): print("原点") elif x > 0: if y > 0: print("第一象限") elif y < 0: print("第二象限") elif y == 0: print("x轴") elif x < 0: if y > 0: print("第四象限") elif y < 0: print("第三象限") elif y == 0: print("x轴") elif x == 0: print("y轴")
import csv import numpy as np def averagenum(num): nsum = 0 for i in range(len(num)): nsum += int(num[i]) return nsum / len(num) with open("/Users/rockter/test.csv","r",encoding = 'utf-8') as csvfile: reader = csv.DictReader(csvfile) cxsj = [] xbsw = [] slx = [] for row in reader: cxsj.append(row['程序设计']) xbsw.append(row['细胞生物']) slx.append(row['生理学']) cxsj.sort() max_cxsj=cxsj[len(cxsj)-1] min_cxsj=cxsj[0] averagenum_cxsj=averagenum(cxsj) print("程序设计平均分为",averagenum_cxsj) print("程序设计分数最高为:",max_cxsj) print("程序设计分数最低为",min_cxsj) xbsw.sort() max_xbsw=xbsw[len(xbsw)-1] min_xbsw=xbsw[0] averagenum_xbsw=averagenum(xbsw) print("程序设计平均分为",averagenum_xbsw) print("程序设计分数最高为:",max_xbsw) print("程序设计分数最低为",min_xbsw) slx.sort() max_slx=slx[len(slx)-1] min_slx=slx[0] averagenum_slx=averagenum(slx) print("程序设计平均分为",averagenum_slx) print("程序设计分数最高为:",max_slx) print("程序设计分数最低为",min_slx)
import itertools def calling(cb): """Iterfunc which returns its input, but calling callback after every item. In particular, the returned iterator calls cb() after it has been asked for a next element, but before returning it. """ def iterfunc(iterator): for item in iterator: cb() yield item return iterfunc def coalescing(iterfunc): """Modifies an iterfunc to group elements output "because of" an input. In particular, given an iterfunc which takes some input, and given each item of the input, returns zero or more items of output, coalescing(iterfunc) returns the same items of output, but grouped by input item, such that its output is the same length as the input. For example: coalescing(mapping(f))(iterator) == [[f(x)] for x in iterator] coalescing(filtering(pred))(iterator) == [ [x] if pred(x) else [] for x in iterator] """ def coalesced(iterator): buf = [[]] def cb(): buf.append([]) for item in iterfunc(calling(cb)(iterator)): buf[-1].append(item) while len(buf) > 1: yield buf.pop(0) yield from buf return coalesced def interleaving(*iterfuncs): """Calls several iterfuncs alternately. Given several iterfuncs, interleaving returns an iterfunc which, given an iterator, returns an iterator which yields: - the outputs of the first iterfunc based on the first input - the outputs of the second iterfunc based on the first input - etc. - the same, repeated for the second input - etc. """ n = len(iterfuncs) def interleaved(iterator): wrapped_iters = [ coalescing(f)(itercopy) for f, itercopy in zip( iterfuncs, itertools.tee(iterator, n))] while wrapped_iters: for i, it in enumerate(wrapped_iters): try: yield from next(it) except StopIteration: wrapped_iters[i] = None wrapped_iters = list(filter(None, wrapped_iters)) return interleaved def mapping(f): def iterfunc(iterator): for i in iterator: yield f(i) return iterfunc def filtering(pred): def iterfunc(iterator): for i in iterator: if pred(i): yield i return iterfunc def main(): expected = [0, 0, -1, -2, 2, -3, -4, 4, -5, -6, 6, -7, -8, 8, -9] actual = list(interleaving( mapping(lambda x: -x), filtering(lambda x: x % 2 == 0) )(iter(range(10)))) if actual == expected: print("ok") else: print("not ok: %s" % actual) if __name__ == '__main__': main()