text
stringlengths
37
1.41M
""" Exercise 5, question 2 This program is using generators to execute the 'napa' function and using it to print a list of all the prime dividers of the inserted N. """ def primeList(n): return [i for i in range(2, n + 1) if all([True if i % j != 0 else False for j in range(2, i - 1)])] def primeFactors(N): pl = primeList(N) return (i for i in pl if N % 1 == 0)
""" Exercise 2, question 4 This program is checking if the number that was given is a palindrome or not and prints out the matching message. """ def isPolindrome(num): if num[0] == '-': # if it's a negative number it cuts the sigh out num = num[1:] if num == num[::-1]: return True else: return False def f(): num = input("Enter a number: ") N = isPolindrome(num) if N: print("It is a palindrome!!") else: print("It is not a palindrome.")
""" Exercise 1, question 8 """ """import random #r = random.randint(3, 9) #print(r) r = int(input("Enter N numbers in the range 3 - 9: ")) nums = [] for i in range(r): nums.append(random.randint(1, 9)) nums = tuple(nums) print(nums)""" #e1q5 - all functions as asked plus recursive (for the test) def T(l): s = [] for i in range(len(l)): if type(l[i]) == tuple: s = s + list(l[i]) return s def RT(l): if l == []: return [] else: if type(l[-1]) == tuple: return RT(l[:-1]) + list(l[-1]) else: return RT(l[:-1]) def L(l): s = () for i in range(len(l)): if type(l[i]) == list: s = s + tuple(l[i]) return s def RL(l): if l == []: return () else: if type(l[-1]) == list: return RL(l[:-1]) + tuple(l[-1]) else: return RL(l[:-1]) def S(l): s = [] for i in range(len(l)): if type(l[i]) == str: s = s + list(l[i]) return s def RS(l): if l == []: return [] else: if type(l[-1]) == str: return RS(l[:-1]) + list(l[-1]) else: return RS(l[:-1]) def N(l): s = [] for i in range(len(l)): if isinstance(l[i], (int, float)): s = s + [l[i]] return s def RN(l): if l == []: return [] else: if isinstance(l[-1], (int, float)): return RN(l[:-1]) + [l[-1]] else: return RN(l[:-1]) print(N([1, 2, 'a', (11,2,'b'), [22,'c'], (33,), ['d'], 'e'])) print(RN([1, 2, 'a', (11,2,'b'), [22,'c'], (33,), ['d'], 'e']))
import os def check_dir(dir_name: str) -> str: input_video_path = dir_name if not os.path.isdir(input_video_path): os.mkdir(input_video_path) print(f'{dir_name} directory is created and now put a video in the directory') return False if len(os.listdir(input_video_path)) == 0: print(f'{dir_name} directory is empty!') return False return True
import random def answer(h, q): p = [] num = 2**h - 1 for x in q: p.append(find_parent(x, num, num)) return p def find_parent(value, high, num_values): # Check if at root of current subtree if (high == value): return -1 # Check if in right subtree, else left subtree if (value >= high - num_values//2): parent = find_parent(value, high - 1, num_values // 2) else: parent = find_parent(value, high - num_values//2 - 1, num_values//2) # Return label if label was returned, else return current root return parent if (parent != -1) else high print() ans = answer(3, [7, 3, 5, 1]) print(ans) print() ans = answer(5, [19, 14, 28]) print(ans) print() ans = answer(30, [19, 14, 28]) print(ans) print() ans = answer(30, random.sample(range(1000000000), 10000)) print(ans) print() ans = answer(30, [1] * 10000) print(ans)
import random import operator import itertools dice = ['AAEEGN', 'ELRTTY', 'AOOTTW', 'ABBJOO', 'EHRTVW', 'CIMOTU', 'DISTTY', 'EIOSST', 'DELRVY', 'ACHOPS', 'HIMNQU', 'EEINSU', 'EEGHNW', 'AFFKPS', 'HLNNRZ', 'DEILRX' ] possible_movements = [(0,-1), (-1, -1), (-1, 0),(-1,1), (0, 1), (1, 1), (1, 0), (1, -1)] 'opens dictionary and puts each word into words list' with open("dictionary.txt", "r") as f: s = f.read() dict_words = s.splitlines() 'generates letters from random roll of dice' def dice_roll(): letters = [] for di in dice: letters.append(di[random.randint(0,5)]) random.shuffle(letters) print(letters) return letters 'filters dictionary by all possible words given letter counts' def find_possible_words(letters): possible_words = [] for word in dict_words: truth_tester = 1 for letter in word: truth_tester = word.count(letter) <= letters.count(letter) * truth_tester if truth_tester == 1: possible_words.append(word) return possible_words 'gets coords for a word in list of letters, then generates all possible paths (whether legal or not)' def check_words(word, letters): raw_coords_path = [] for letter in word: raw_coords = [] locations = [i for i, x in enumerate(letters) if x == letter] for location in locations: raw_coords.append(location) raw_coords_path.append(raw_coords) #generates all possible paths for the word all_paths = list(itertools.product(*raw_coords_path)) for path in all_paths: if len(set(path)) != len(path): all_paths.remove(path) return all_paths 'generates coords in 4*4 grid given number in list' def generate_coordinates(location): coords = (location/4, location % 4) return coords 'checks if all moves in path legal' def check_for_legal_moves(all_paths): any_path_checker = 0 for num_path in range(len(all_paths)): path = [] one_path_checker = 1 for num_letter in range(len(all_paths[0])-1): path.append(all_paths[num_path][num_letter]) coord1 = generate_coordinates(all_paths[num_path][num_letter]) coord2 = generate_coordinates(all_paths[num_path][num_letter+1]) movement = tuple(map(operator.sub, coord1, coord2)) one_path_checker = one_path_checker * movement in possible_movements any_path_checker += one_path_checker return any_path_checker > 0 result = {} 'master function to roll dice and generate results' def roll_and_run(): all_legal_words = [] score = 0 letters_available = dice_roll() possible_words = find_possible_words(letters_available) for word in possible_words: paths = check_words(word, letters_available) word_is_legal = check_for_legal_moves(paths) if word_is_legal: all_legal_words.append(word) score += len(word)-2 result['Words'] = all_legal_words result['Score'] = score return result print(roll_and_run())
#!/usr/bin/python3 """ Test for rectangle.py """ import unittest from models import base, rectangle import pep8 import json class TestRectMethods(unittest.TestCase): """rect tests""" def test_inherits(self): """test rectangle.Rectangle""" pass def test_no_args(self): with self.assertRaises(TypeError): rectangle.Rectangle() def test_one_arg(self): with self.assertRaises(TypeError): rectangle.Rectangle(1) def test_two_args(self): r1 = rectangle.Rectangle(10, 2) r2 = rectangle.Rectangle(2, 10) self.assertEqual(r1.id, r2.id - 1) def test_three_args(self): r1 = rectangle.Rectangle(2, 2, 4) r2 = rectangle.Rectangle(4, 4, 2) self.assertEqual(r1.id, r2.id - 1) def test_four_args(self): r1 = rectangle.Rectangle(1, 2, 3, 4) r2 = rectangle.Rectangle(4, 3, 2, 1) self.assertEqual(r1.id, r2.id - 1) def test_five_args(self): self.assertEqual(7, rectangle.Rectangle(10, 2, 0, 0, 7).id) def test_more_than_five_args(self): with self.assertRaises(TypeError): rectangle.Rectangle(1, 2, 3, 4, 5, 6) def test_width_private(self): with self.assertRaises(AttributeError): print(rectangle.Rectangle(5, 5, 0, 0, 1).__width) def test_height_private(self): with self.assertRaises(AttributeError): print(rectangle.Rectangle(5, 5, 0, 0, 1).__height) def test_x_private(self): with self.assertRaises(AttributeError): print(rectangle.Rectangle(5, 5, 0, 0, 1).__x) def test_y_private(self): with self.assertRaises(AttributeError): print(rectangle.Rectangle(5, 5, 0, 0, 1).__y) def test_constructor(self): """test rectangle.Rectangle""" rect = rectangle.Rectangle(5, 3, 7, 2, 99) self.assertEqual(rect.width, 5) self.assertEqual(rect.height, 3) self.assertEqual(rect.x, 7) self.assertEqual(rect.y, 2) self.assertEqual(rect.id, 99) def test_validator(self): """test rectangle.Rectangle""" pass def test_area(self): """test rectangle.Rectangle""" # small area r = rectangle.Rectangle(10, 2, 0, 0, 0) self.assertEqual(20, r.area()) # large area r = rectangle.Rectangle(999999999999999, 999999999999999999, 0, 0, 1) self.assertEqual(999999999999998999000000000000001, r.area()) # extra area r = rectangle.Rectangle(2, 10, 1, 1, 1) r.width = 7 r.height = 14 self.assertEqual(98, r.area()) def test_update_args(self): """test rectangle.Rectangle""" rect = rectangle.Rectangle(5, 5) # check for function self.assertTrue('update' in dir(rect)) # test id update rect.update(89) self.assertEqual(rect.id, 89) # test width update rect.update(89, 2) self.assertEqual(rect.width, 2) # test height upadte rect.update(89, 2, 3) self.assertEqual(rect.height, 3) # test x update rect.update(89, 2, 3, 4) self.assertEqual(rect.x, 4) # test y update rect.update(89, 2, 3, 4, 2) self.assertEqual(rect.y, 2) def test_update_kwargs(self): """test rectangle.Rectangle""" rect = rectangle.Rectangle(1, 1, 0, 0, 1) # test id update rect.update(id=89) self.assertEqual(rect.id, 89) # test width update rect.update(width=10) self.assertEqual(rect.width, 10) # test height update rect.update(height=10) self.assertEqual(rect.height, 10) # test x update rect.update(x=5) self.assertEqual(rect.x, 5) # test y update rect.update(y=5) self.assertEqual(rect.y, 5) def test_to_dict(self): """test rectangle.Rectangle""" pass def test_pep8_conformance(self): """load_from_file Docstring Test""" print("test_test_pep8_conformance") pep8style = pep8.StyleGuide(quiet=True) result = pep8style.check_files(['models/rectangle.py']) self.assertEqual(result.total_errors, 0) if __name__ == '__main__': unittest.main()
#!/usr/bin/python3 def weight_average(my_list=[]): if my_list == []: return 0 i = 0 j = 0 for x in my_list: i += x[0] * x[1] j += x[1] i = i / j return i
#!/usr/bin/python3 """ my_list """ class MyList(list): """ sub class of list """ def print_sorted(self): """ public instance of sorted list """ new = self[:] new.sort() print(new)
# Create a calculator c = 50 h = 30 # use this formula Q = square root lf [(2*c*d)/h] # find d import math x = [] y = [i for i in input('Give me a number: ').split(',')] for d in y: x.append(str(int(round(math.sqrt(2*c*float(d)/h))))) print(','.join(x)) # the join method is for str so we need to conver our integer answer to a str to use the join method # PEMDAS... # Please # Excuse # My # Dear # Aunt # Sally
# Create an array of 5 integers and display array items, access them via index from array import * array_num = array('i', [1,3,5,7,9]) # Any numbers work for i in array_num: print(i) print('Access first three items individuals') print(array_num[0]) print(array_num[1]) print(array_num[2]) # Append a new item to end of array print('Starting array ', array_num) array_num.append(11) # Adds number 11 print('new array: ', array_num) # reverse the order print(array_num[::-1]) # insert a new value before the number 3 print(array_num) array_num.insert(1,4) # I want the number 4 at index of 2 print(array_num) # Remove an item via index array_num.pop(3) # default is last item, otherwise add index #(3) is index location print(array_num) # Remove the first occurrence of an element new_array = array('i', [1,3,5,7,3,9,3,11]) print('new array: ', new_array) new_array.remove(3) # Integer not index print(new_array) # convert an array into a list print(type(new_array)) x = new_array.tolist() print(type(x))
""" Program: modelview.py Author: Chad Lister Date: 01/31/2021 This program defines the view for the PFEvaluatorModel class. DS Chapter # 7 Project # 4: add the ^ operator to the expressions processed by the expression evaluator of the case study. """ from scanner import Scanner from model import * def main(): """ The main function. """ # Main display loop. while True: # String variable. st = "" sourceStr = input("\nEnter an expression: ") if sourceStr == "": break scanner = Scanner(sourceStr) while scanner.hasNext(): st += str(scanner.next()) print("\nPrefix expression is", st) # String variables. temp2 = "" temp = "" temp3 = "" # Divide string into digits and operators. for i in range(len(st)): c = st[i] b = c.isdigit() # Add to digit string. if b == True: temp += c # Add to operator string and pad digit string. else: temp2 = " " + c + " " + temp2 temp += " " # Add digit and operator string. temp3 = temp + temp2 print("\nPostfix expression is", temp3) # Make PFEvaluatorModel and pass string to evaluate. m = PFEvaluatorModel() r = m.evaluate(temp3) print("\nEvaluates to: ", r) main()
""" Program: patron.py Author: Chad Lister Date: 01/10/2021 This program defines the Patron class and defines the interface used in a library class. """ class Patron(): """ This class represents a library patron. """ MAX_BOOK_COUNT = 3 def __init__(self, name, bookCount, bookList): """ Constructor. """ self._name = name self._bookCount = bookCount self._bookList = bookList def __str__(self): """ Returns the string values for patrons. """ result = "\n\tName: " + self._name + "\n\tBook Count: " + str(self._bookCount) return result def getName(self): """ Returns the users name. """ return self._name def getBookCount(self): """ Returns the number of books currently checked out. """ return self._bookCount def getBookList(self): """ Returns the book list currently held by the user. """ return self._bookList def checkCount(self, count): """ Checks if max count has been reached. """ if count > Patron.MAX_BOOK_COUNT: return False else: return True def addToList(self, title): """ Adds a book to the list. """ self._bookList.append(title) return self._bookList def addToCount(self): self._bookCount += 1 return self._bookCount
""" Program: testfunction.py Author: Chad Lister Date: 12/23/2020 This program tests the printAll function with tracing. 1) The input is: a sequence 2) The output is: a reducing sequence and tracing for sequence argument """ def printAll(seq): i = 1 last = len(seq) if seq: print(seq[0]) print(seq[i : last], "remaining sequence argument") printAll(seq[1 : ]) def main(): printAll("123456789") printAll(("6", "5", "4", "3", "2", "1")) main()
""" Program: new_decryption.py Author: Chad Lister Date: 12/18/2020 this program inverses the enryption from Chapter # 4 Project # 6 1. Input is: encryptedString 2. Computation is : if it's not blank split it into substrings shift substring 1 right convert shifted string from binary to decimal get character for decimal - 1 add character to decrypted String """ # get user input encryptedString = str(input("Please enter the encrypted string: ")) # initialize variables c = 0 count = 0 word = 0 stringLen = 0 digit = "" index = 0 bit = "" #ordNumber = 0 temp = "" #char = "" encChar = "" tempString = "" shiftedString = "" convertedString = "" decryptedString = "" finalString = "" # if it's blank error if len(encryptedString) == 0: print("Error.") # else split elif len(encryptedString) > 0: digitList = encryptedString.split() count = len(digitList) # for digits in list for digit in digitList: stringLen = len(digit) temp = digit[stringLen - 1] c += 1 # shift right for index in range(len(digit) - 1): tempString += digit[index] index += 1 shiftedString = temp + tempString temp = "" tempString = "" # convert shifted string decimal = 0 exponent = len(shiftedString) - 1 for bit in shiftedString: decimal = decimal + int(bit) * 2 ** exponent exponent -= 1 # get character of number - 1 ordNumber = decimal - 1 encChar = chr(ordNumber) # add character to decrypted #decryptedString += encChar + " " decryptedString += encChar encChar = "" shiftedString = "" finalString += decryptedString decryptedString = "" #if c < count: #finalString = finalString + " " + decryptedString #decryptedString = decryptedString + " " #print(decryptedString) #elif c == count: #finalString += decryptedString print(finalString)
""" Program: myprogram.py Author: Chad Lister Computes the area of a square or rectangle. 1. Significant constants: None. 2. The inputs are: width height 3. Computations: area = width * height 4. The output is: The area of the square or rectangle """ # Request the inputs width = int(input("Enter the width: ")) height = int(input("Enter the height: ")) # Compute the area area = width * height # Display the area print("The area is ", area, " square units.")
import sqlite3 class Schema: def __init__(self): self.conn = sqlite3.connect('todo.db') #self.create_user_table() self.create_to_do_table() self.conn = sqlite3.connect('userinformation.db') self.create_user_table() # Why are we calling user table before to_do table # what happens if we swap them? def create_to_do_table(self): query = """ CREATE TABLE IF NOT EXISTS "Todo" ( id INTEGER PRIMARY KEY, Title TEXT, Description TEXT, _is_done boolean, _is_deleted boolean, CreatedOn Date DEFAULT CURRENT_DATE, DueDate Date, emailid VARCHAR(320) ); """ self.conn.cursor().execute(query) self.conn.commit() def create_user_table(self): query = """ CREATE TABLE IF NOT EXISTS "UserInformation" ( emailid VARCHAR(320) PRIMARY KEY, password VARCHAR(320) ); """ self.conn.cursor().execute(query) self.conn.commit() class ToDoModel: def __init__(self): self.conn = sqlite3.connect('todo.db') def create(self, text, description): TABLENAME = "Todo" query = f'insert into {TABLENAME} ' \ f'(Title, Description) ' \ f'values ("{text}","{description}")' self.conn.cursor().execute(query) self.conn.commit() return "sucess" def get_alldata(self): TABLENAME = "Todo" query = f'select * FROM {TABLENAME}' result = self.conn.cursor().execute(query) self.conn.commit() return result.fetchall() # Similarly add functions to select, delete and update todo class User: def __init__(self): self.conn = sqlite3.connect('userinformation.db') def create(self,email,password): TABLENAME = "UserInformation" query = f'insert into {TABLENAME} ' \ f'(emailid, password) ' \ f'values ("{email}","{password}")' self.conn.cursor().execute(query) self.conn.commit()
# Stephen Randall # 11/15/17 # Folder: Unit9Project File: compare.py # This is a card game that compares two players cards who ever has the greatest card wins. Uses two classes card.py and # deck.py import card import deck new_card = card.Card(1, "Hearts",) new_deck = deck.Deck() new_deck.shuffle() print("======DONE SHUFFLE======") def comparecards(firstcard, secondcard): """ Compares the two cards it is given. If player one wins returns a value of 1 if player two wins returns a value of 2 :param firstcard: Gets the first card that it's going to compare to the second card :param secondcard: Gets the second card that it's going to compare to the first card. :return: Returns either 1 or 2 to tell the playgame function who won and who to give the points to. """ print("================") if firstcard.rank > secondcard.rank: return 1 elif secondcard.rank > firstcard.rank: return 2 else: if firstcard.suit > secondcard.suit: return 1 elif secondcard.suit > firstcard.suit: return 2 def playgame(playeronecards, playertwocards): """ Takes the return of comparecards and gives the points to the winner of the compare. Prints results. :param playeronecards: Gets player one's deck of cards. :param playertwocards: Gets player two's deck of cards. """ play_question = input("Are you ready to play? (y/n)") if play_question == "y": playeronescore = 0 # Sets Player one score to zero playertwoscore = 0 # Sets Player two score to zero for x in range(len(playeronecards)): who_won = comparecards(playeronecards[x], playertwocards[x]) # Assigns the return value from function # comparecards to a variable "who_won" if who_won == 1: print("Player One has won!") playeronescore = playeronescore + 1 # Adds a point to the player one score if player one wins elif who_won == 2: print("Player Two has won!") playertwoscore = playertwoscore + 1 # Adds a point to the player two score if player two wins else: print("It was a tie.") print(playeronescore, playertwoscore) print("Player one card:", playeronecards[x]) print("Player two card:", playertwocards[x]) if playeronescore > playertwoscore: print("Player one won the game! Player one had:", playeronescore, "points!") elif playertwoscore > playeronescore: print("Player two won the game! Player two had:", playertwoscore, "points!") else: print("Player one score:", playeronescore) print("Player two score:", playertwoscore) print("It was a tie.") else: print("Bye! Have a nice day.") def main(): playeronecards = [] playertwocards = [] for x in range(5): playeronecards.append(new_deck.dealacard()) playertwocards.append(new_deck.dealacard()) playgame(playeronecards, playertwocards) main()
#Logical Operator ; And use num1 = 20 num2 = 10 num3 = 80 if num1 > num2 and num1 > num3: print(num1) elif num2 > num1 and num2 > num3: print(num2) else: print(num3)
def main(): with open("input_day_3") as f: lines = f.readlines() codes = map(code_parser, lines) locations = list(map(location_calculator, codes)) intersections = [] c = 0 for i in locations[0]: c += 1 if c % 1000 == 0: print(c) if i in locations[1]: intersections.append(i) distance = find_manhatten_min(intersections) print("result") print(distance) def find_manhatten_min(intersections): values = map(lambda i: abs(i[0]) + abs(i[1]), intersections) values_less_zero = filter(lambda x: x != 0, values) min_intersection = min(values_less_zero) return min_intersection def location_calculator(codes): x = 0 y = 0 locations = [] for (c, d) in codes: if c == 'U': locations = locations + [(x, y + o) for o in range(d)] y = y + d elif c == 'D': locations = locations + [(x, y - o) for o in range(d)] y = y - d elif c == 'R': locations = locations + [(x + o, y) for o in range(d)] x = x + d elif c == 'L': locations = locations + [(x - o, y) for o in range(d)] x = x - d else: raise Exception("invalid direction code") return locations def code_parser(codes): list_codes = codes.split(",") split_codes = list(map(lambda x: (x[0], int(x[1:])), list_codes)) return split_codes def test_data1(): # test data # distance 159 val1_1 = code_parser("R75,D30,R83,U83,L12,D49,R71,U7,L72") val1_2 = code_parser("U62,R66,U55,R34,D71,R55,D58,R83") locs_11 = location_calculator(val1_1) locs_12 = location_calculator(val1_2) intersections = filter(lambda x: x in locs_12, locs_11) distance = find_manhatten_min(intersections) print(distance) def test_data2(): # distance 135 val2_1 = code_parser("R98,U47,R26,D63,R33,U87,L62,D20,R33,U53,R51") val2_2 = code_parser("U98,R91,D20,R16,D67,R40,U7,R15,U6,R7") locs_21 = location_calculator(val2_1) locs_22 = location_calculator(val2_2) intersections = filter(lambda x: x in locs_22, locs_21) distance = find_manhatten_min(intersections) print(distance) if __name__ == "__main__": test_data1() test_data2() main()
# import only standard Python 3 libraries here. """Implement all the TODOs""" # input: positive integer x # output: True or False def isDivBySeven(x): print(x) # do not remove this line """ TODO: finish implementing the function as described on the HW1 handout.""" if x<10: return True if x==7 or x==0 else False else: return isDivBySeven((x-21*int(str(x)[-1]))//10) # input: positive integer x # output: True or False def isPrime(x): """ TODO: finish implementing the function as described on the HW1 handout.""" for i in range(2, int(x**0.5)+1): if x %i ==0: return False return True if __name__ == '__main__': '''Nothing below this line will be executed by the autograder --- use this space to test your code!''' # i dont need test
valid = 0 list = [] while valid<5: x = int(input("Podaj liczbe: ")) list.append(x) valid= valid+1 for i in list: print(i)
# Purpose: Ask user what the month and day is and print it on the screen. # Ask user for month month = raw_input("Please enter the current month (January, February etc.): ") # Ask user for the day day = raw_input("Please enter the day (1, 2,...31): ") # Concatenate month and day and print on screen # Important to include spaces print("Today is " + month + " " + day + ".")
from collections import defaultdict from typing import List """ Given a non-empty array of integers, every element appears twice except for one. Find that single one. Note: Your algorithm should have a linear runtime complexity. Example 1: Input: [2,2,1] Output: 1 Example 2: Input: [4,1,2,1,2] Output: 4 """ def single_number(input_data: List[int]) -> int: hash_map = defaultdict(int) for elem in input_data: hash_map[elem] += 1 for key, value in hash_map.items(): if value == 1: return key def single_number_math(input_date: List[int]) -> int: return 2 * sum(set(input_date)) - sum(input_date)
def create_dictionary(list1,list2): dictionary = {} for i in range((len(list1))): dictionary[list1[i]] = list2[i] return dictionary list1 = list(input("Enter the words: ").strip().split()) list2 = list(map(int,input("Enter the numbers: ").strip().split())) create_dictionary(list1,list2) def my_dictionary(list1,list2): dict1 = create_dictionary(list1,list2) a = int(input('Enter the integer: ')) index = 0 for k,v in dict1.items(): if a == v: return index index+=1 my_dictionary(list1,list2)
class DataType(object): def __init__(self): self.type = 'generic' self.description = '' def compare_data_objects(self, other): """ Used to compare two data types """ return self.type == other.type def __eq__(self, other): if type(other) is str: return self.type == other else: if type(self) is not type(other): return False else: return self.compare_data_objects(other) def __str__(self): return '<data type: ' + self.type + self.description + '>' class IntDataType(DataType): def __init__(self, auto_increment=False): super(IntDataType, self).__init__() self.type = 'int' self.auto_increment=auto_increment class FloatDataType(DataType): def __init__(self): super(FloatDataType, self).__init__() self.type = 'float' class StringDataType(DataType): def __init__(self, fixed_length=True, length=255): """ :param fixed_length: should the string be of fixed lenght or variable length? :param length: the maximum length if not fixed, otherwise the exact length if it is fixed """ super(StringDataType, self).__init__() self.type = 'string' self.fixed_length = fixed_length self.length = length self.description = ', fixed=' + str(fixed_length) + ', length=' + str(length) def compare_data_objects(self, other): return self.fixed_length == other.fixed_length and self.length == other.length class BoolDataType(DataType): def __init__(self): super(BoolDataType, self).__init__() self.type = 'bool'
class Column(object): def __init__(self, column_name, column_type, primary_key=False): """ Describes a column in a table :param column_name: the name of the column :param column_type: a DataType object representing the type of the column """ self.name = column_name self.type = column_type self.primary_key = primary_key self.table = None def get_table_name(self): """ Returns the name of this column's table """ if self.table is None: return None else: return self.table.name def __str__(self): table_name = '<None>' if self.get_table_name() is not None: table_name = self.get_table_name() return '<column: table=' + table_name + ', name=' + self.name + ', type=' + str(self.type) + '>'
"""Integration tests for Parser""" import os from unittest import TestCase from parser import Parser from sample_data import test_case_data from validation import field_validators DATA_FILE = 'test.csv' JSON_FILE = 'test.json' class ParserTestCase(TestCase): """Test read file function""" def setUp(self): # create a test.csv file with valid and invalid entries with open(DATA_FILE, 'w+') as f: [f.write(_format+'\n') for _format in test_case_data['valid_entries']] [f.write(_format+'\n') for _format in test_case_data['invalid_entries']] # create a list of valid formats formats = [f.split(',') for f in test_case_data['valid_formats']] self.parser = Parser(DATA_FILE, field_validators, formats) def test_is_entry_formatted(self): """Can check if a entry is of a valid format?""" valid_formats = test_case_data.get('valid_formats') for i, valid_entry in enumerate(test_case_data.get('valid_entries')): entry = [value.strip() for value in valid_entry.split(',')] format_fields = valid_formats[i].split(',') valid = self.parser._is_entry_formatted(entry, format_fields) self.assertTrue(valid, f'{entry} is not of a valid format') # fails with invalid entries for invalid_entry in test_case_data.get('invalid_entries'): entry = [value.strip() for value in invalid_entry.split(',')] for f in valid_formats: format_fields = f.split(',') entry_dict = self.parser._is_entry_formatted(entry, format_fields) self.assertFalse(entry_dict, f'{entry} is not of a valid format') def test_match_entry_to_format(self): """Can match an entry to a format?""" # matches valid entries with valid formats for valid_entry in test_case_data.get('valid_entries'): entry = [e.strip() for e in valid_entry.split(',')] entry_dict = self.parser._match_entry_to_format(entry) self.assertTrue(entry_dict, f'{entry} is not of a valid format') # fails with invalid entries for invalid_entry in test_case_data.get('invalid_entries'): entry = [e.strip() for e in invalid_entry.split(',')] entry_dict = self.parser._match_entry_to_format(entry) self.assertFalse(entry_dict, f'{entry} is not of a valid format') def test_parse_field(self): """Can parse a single field into a dictionary?""" # parses valid fields field = self.parser._parse_field('fullname', 'John Doe') self.assertEqual(field, {'firstname': 'John', 'lastname': 'Doe'}) field = self.parser._parse_field('phone_hyphenated', '(703)-742-0996') self.assertEqual(field, {'phonenumber': '703-742-0996'}) field = self.parser._parse_field('phone_spaced', '703 742 0996') self.assertEqual(field, {'phonenumber': '703-742-0996'}) field = self.parser._parse_field('firstname', 'Billy Bob') self.assertEqual(field, {'firstname': 'Billy Bob'}) # returns empty dict for invalid fields field = self.parser._parse_field('age', 44) self.assertEqual(field, {}) field = self.parser._parse_field('nickname', 'hackerman') self.assertEqual(field, {}) def test_parse(self): """Can parse a csv file with valid and invalid rows?""" results = self.parser.parse() self.assertEqual(results, test_case_data['parse_output']) def test_to_json(self): """Can output a valid JSON string that is sorted and indented two spaces""" self.parser.parse() json_string = self.parser.to_json() self.assertTrue(isinstance(json_string, str)) def test_json_to_file(self): """Can write valid JSON to a file that is sorted and indented two spaces""" self.parser.parse() self.parser.json_to_file(JSON_FILE) json_string = self.parser.to_json() with open(JSON_FILE) as f: json_file_string = f.read() self.assertEqual(json_string, json_file_string) def tearDown(self): try: os.remove(DATA_FILE) os.remove(JSON_FILE) except FileNotFoundError: pass return super().tearDown()
# -*- coding: utf-8 -*- """ Created on Sat Mar 6 11:43:47 2021 @author: anand """ # The algorithm starts at 3 cur_x =5 # Learning Rate rate = 0.1 # This tells us when to stop the algorithm precision = 0.5 previous_step_size = 1 # Maximum number of iterations max_iters = 1000000 # iteration counter iters = 0 # Gradient of our function df = lambda x: 2*(x+5) while previous_step_size > precision and iters < max_iters: prev_x = cur_x # Gradient Descent cur_x = cur_x - rate * df(prev_x) previous_step_size = abs (cur_x - prev_x) iters = iters + 1 print(f"Iteration{iters} \nX value is {cur_x}") print(f"The local minimum occurs at {cur_x}") # scipy.optimize.minimize() can be used to calculate complex functions
def main(): series = int(input()) a=0 b=1 for i in range(series): print(a, end= " ") a,b=b,a+b main()
""" https://leetcode.com/problems/different-ways-to-add-parentheses/ """ from typing import List class Solution: def diffWaysToCompute(self, inputs: str) -> List[int]: output = [] for i, s in enumerate(inputs): if s in ["+", "-", "*"]: str_1 = inputs[:i] str_2 = inputs[i + 1:] print(str_1) list_str_1 = self.diffWaysToCompute(str_1) list_str_2 = self.diffWaysToCompute(str_2) print(list_str_1, list_str_2) for s_1 in list_str_1: for s_2 in list_str_2: if s == "+": output.append(int(s_1) + int(s_2)) elif s == "-": output.append(int(s_1) - int(s_2)) else: output.append(int(s_1) * int(s_2)) if not len(output): output.append(int(inputs)) return output if __name__ == "__main__": sol = Solution() print(sol.diffWaysToCompute(inputs = "21*3-4*5"))
def isSymbol(name): x = 0 symbol = "~`!@#$%^&*()_-+={}[]:>;',</?*-+" for i in name: if i in symbol: x += 1 if x > 0: return True if x == 0: return False def isNum(name): x = 0 symbol = "1234567890" for i in name: if i in symbol: x += 1 if x > 0: return True if x == 0: return False def isAlph(name): x = 0 symbol = "qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM" for i in name: if i in symbol: x += 1 if x > 0: return True if x == 0: return False def Fnames(First): BF = isAlph(First) if len(First) > 1 and BF: return True def Lnames(Last): BL = isAlph(Last) if len(Last) > 1 and BL: return True def ZIP(Zip): if isNum(Zip): return True def EmpID(ID): if isAlph(ID[0:2]) and ID[2] == '-' and isNum(ID[3:5]): return True First = input("Please enter your first name? ") Last = input("Please enter your last name? ") Zip = input("Please enter your zip code? ") ID = input("Please enter your ID? ") if Fnames(First) != True: print(f"{First} is not a name. It is too short.") if Lnames(Last) != True: print(f"{Last} is not a name. It is too short. ") if ZIP(Zip) != True: print("The Zip is not a numeric number") if EmpID(ID) != True: print(f"{ID} is not a valid ID")
def getKey(item): return item[0] filename = 'ee41.txt' txt = open(filename) content = txt.readlines() content = [x.strip() for x in content] Map = sorted(content, key=getKey) print("Total number of names: ", len(Map)) for i in Map: print(i)
gen = {'men' : 0.73, 'women' : 0.66} A = 12*float(input("How many drinks have you had? "))*.06 r = gen[input(str("What is your gender? "))] w = float(input("What is your body weight?" )) H = float(input("How many hours has it been since your last drink? ")) BAC = round(A*(5.14/w)*r-(.015*H),2) print(f"Your BAC is {BAC}") if BAC > .08: print("It is not legal for you to drive ") else: print("It is legal for you to drive ")
import random as r N, List = [], [] while True: if N != '': N = input("Enter a name? ") List.append(N) if N == '': List.remove(N) break Winner = r.randint(0,len(List)) print(f"The 1st winner is {List[Winner]}") del List[Winner] Winner = r.randint(0,len(List)) print(f"The 2nd winner is {List[Winner]}")
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Dec 4 20:42:54 2017 @author: christophernovitsky """ from babel.numbers import format_currency while True: try: P = float(input("Enter principle? ")) r = float(input("Enter the intrest rate? ")) t = int(input("Enter the number of years? " )) n = float(input("Number of time a year intrest compound? ")) break except ValueError: print("Enter a number") for i in range(1,t+1): A = P*(1+((r/100)/n))**(n*float(i)) print("Year " + str(i) + ": " + format_currency(A, 'USD', locale='en_US'))
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sat Dec 2 18:57:36 2017 @author: christophernovitsky """ x = input(" What us the quotes? ") y = input(" Who said it?") print(f'{y} says, "{x}"')
def setup_puzzle(): # Return a valid sudoku puzzle to solve. Temporarily hardcoded, # but this board can be modified and should still be solveable for any "easy" solveable board board = [ [None, None, 3, None, None, None, 1, 6, None], [None, None, None, 6, 4, None, None, 5, 2], [None, 5, None, 1, 2, 3, None, None, None], [3, None, 5, None, None, 2, 8, None, 9], [None, 9, None, 3, None, 5, None, 1, None], [8, None, 6, 9, None, None, 5, None, 3], [None, None, None, 8, 1, 9, None, 3, None], [5, 8, None, None, 3, 4, None, None, None], [None, 3, 2, None, None, None, 4, None, None] ] return board def get_square_bounds(index): # For a given value return the min and max bounds of the sudoku square # Every row/col is divied into three squares bounded by [0, 2], [3, 5] and [6, 9] if index <= 2: return [0, 1, 2] elif index <= 5: return [3, 4, 5] else: return [6, 7, 8] def get_numbers_in_row(puzzle, row): # Return all numbers in row, removing None values from list return [num for num in puzzle[row] if num is not None] #return puzzle[row] def get_numbers_in_column(puzzle, index): # Search each row at a given index (to traverse a column) and return all the non-None values column_values = [] for row in puzzle: column_values.append(row[index]) return [num for num in column_values if num is not None] def get_numbers_in_square(puzzle, row, col): # Return list of all numbers in current square for which the intersection of row and col resides existing_values = [] row_bounds, col_bounds = get_square_bounds(row), get_square_bounds(col) for row_index in row_bounds: for col_index in col_bounds: existing_values.append(puzzle[row_index][col_index]) return [num for num in existing_values if num is not None] def valid_placements(puzzle, row, col): # For a given row and column index in the current puzzle, return all valid placements row_allowed = set(ALLOWED_VALUES) - set(get_numbers_in_row(puzzle, row)) col_allowed = set(ALLOWED_VALUES) - set(get_numbers_in_column(puzzle, col)) sq_allowed = set(ALLOWED_VALUES) - set(get_numbers_in_square(puzzle, row, col)) mutually_valid = list(set.intersection(row_allowed, col_allowed, sq_allowed)) return mutually_valid def none_values_on_board(puzzle): # Count how many None values are currenty on the board none_count = 0 for row in puzzle: for index in row: if index is None: none_count += 1 return none_count def validate_final_solution(puzzle, iterations): # Quick validation to ensure solution obeys none_count = 0 for row in puzzle: for value in row: if value == None: none_count += 1 for row in puzzle: print row if none_count == 0: print "\nSolved Sudoku in %s iterations!\n" %(iterations) else: print "Could not proceed after %s iterations :(" %(iterations) if __name__ == "__main__": ALLOWED_VALUES = [1, 2, 3, 4, 5, 6, 7, 8, 9] puzzle = setup_puzzle() iterations = 0 change_made = True while change_made: if none_values_on_board(puzzle) == 0: break change_made = False iterations += 1 row_index = -1 for row in puzzle: row_index += 1 col_index = -1 for col in row: col_index += 1 if puzzle[row_index][col_index] is None: possible_numbers = valid_placements(puzzle, row_index, col_index) if len(possible_numbers) == 1: puzzle[row_index][col_index] = possible_numbers[0] change_made = True else: change_made = True validate_final_solution(puzzle, iterations)
cube = lambda x: pow(x, 3) # complete the lambda function def fibonacci(n): y = 2 s = [] if y >= 2: s.append(0) s.append(1) for y in range(2, n + 1): s.append(s[y - 2] + s[y - 1]) return s[0:n] if __name__ == '__main__': n = int(input()) print(list(map(cube, fibonacci(n))))
""" Input;: 7 UK China USA France New Zealand UK France 7 is the number of countries as input. Ans: 5 """ #Solution 2 is better because it does not check the whole list to find the count. def count_country1(no,inp): s = [] for x in inp: if x not in s: s.append(x) print(len(s)) def count_country2(no,inp): res = [] res = list(set(inp)) print(len(res)) if __name__ == '__main__': no = input() n = int(no) inp = [] for i in range(0, n): inp.append(input()) count_country2(n,inp)
class theaterMovies: def movies(): show1 = 1 show2 = 2 show3 = 3 show4 = 4 print(' ') print('Nite Striker is 1, Day Breaker is 2, Lethal Dragon is 3 and Man Cave is 4') print(' ') customer = int(input('please enter your movie of choice: ')) while(True): if(customer == show1 or customer == show2): print(' ') print('thank you your show is in theatre 1 and 2 please pick your seats') break elif(customer == show3 or customer == show4): print(' ') print('thank you your show is in theatre 3 and 4 please pick your seats') break else: print(' ') print('error') print(' ') customer = int(input('please enter your movie of choice: ')) movies()
for i in range(101): if i%7==0 or i%10==7 or i//10==7: continue else: print(i)
import re from itertools import permutations def clean_name(n): return re.sub("[\W_]+", '', n).lower() def is_palindrome(n): return n == n[::-1] Dwarves = ["Gimli", "Fili", "Ilif", "Ilmig", "Mark"] dwarves = [clean_name(d) for d in Dwarves] # clean input for d in dwarves: # check input if dwarves.count(d) != 1: raise Exception('Duplicate name not supported: '+d) for i in range(1, len(dwarves)+1): # all lengths for sequence in permutations(dwarves, i): # all orders if is_palindrome("".join(sequence)): print " ".join([Dwarves[dwarves.index(d)] for d in sequence])
# defining the string_alternative function def string_alternative(ip): return ip[::2] # defining the main function def main(): word = input("Enter the word:") result = string_alternative(word) print("Result:", result) if __name__ == "__main__": main()
string = input('Enter the string:') sub = string[0:2] + string[3] + string[5] print(sub[::-1])
# This Python file uses the following encoding: utf-8 ## # (C) 2007, 2008, 2013, 2015, 2016 Muthiah Annamalai <ezhillang@gmail.com> # (C) 2013 msathia <msathia@gmail.com> ## # This file is dual licensed - originally GPL v3 from Ezhil, and # then as part of open-tamil package in MIT license. ## # Licensed under GPL Version 3 from sys import version from copy import copy import re import operator PYTHON3 = version > '3' del version if PYTHON3: import functools # 323 def to_unicode_repr(_letter): """ helpful in situations where browser/app may recognize Unicode encoding in the \u0b8e type syntax but not actual unicode glyph/code-point""" # Python 2-3 compatible return u"u'" + u"".join([u"\\u%04x" % ord(l) for l in _letter]) + u"'" def letters_to_py(_letters): """ return list of letters e.g. uyir_letters as a Python list """ return u"[u'" + u"',u'".join(_letters) + u"']" # List of letters you can use uyir_letters = [u"අ", u"ආ", u"ඇ", u"ඈ", u"ඉ", u"ඊ", u"උ", u"ඌ", u"x", u"x", u"x", u"x", u"එ", u"ඒ", u"ඓ", u"ඔ", u"ඕ", u"ඔෟ", u"අං", u"අඃ"] ayudha_letter = u"ං" mei_letters = [u"ක්", u"ඛ්", u"ග්", u"ඝ්", u"ඩ්", u"ඟ්", u"ච්", u"ඡ්", u"ජ්", u"ඣ්", u"ඤ්", u"ට්", u"ඨ්", u"ඪ්", u"ණ්", u"ඬ්", u"ත්", u"ථ්", u"ද්", u"ධ්", u"න්", u"ඳ්", u"ප්", u"ඵ්", u"බ්", u"භ්", u"ම්", u"ඹ්", u"ය්", u"ර්", u"ල්", u"ව්", u"ශ්", u"ෂ්", u"ස්", u"හ්", u"ළ්", u"ෆ්"] accent_symbols = [u"", u"ා", u"ැ", u"ෑ", u"ි", u"ී", u"ු", u"ූ", u"ෘ", u"ෘෘ", u"ෟ", u"ෟෟ", u"ෙ", u"ේ", u"ෛ", u"ො", u"ෝ", u"ෞ"] pulli_symbols = [u"්"] agaram_letters = [u"ක", u"ඛ", u"ග", u"ඝ", u"ඩ", u"ඟ", u"ච", u"ඡ", u"ජ", u"ඣ", u"ඤ", u"ට", u"ඨ", u"ඪ", u"ණ", u"ඬ", u"ත", u"ථ", u"ද", u"ධ", u"න", u"ඳ", u"ප", u"ඵ", u"බ", u"භ", u"ම", u"ඹ", u"ය", u"ර", u"ල", u"ව", u"ශ", u"ෂ", u"ස", u"හ", u"ළ", u"ෆ"] sanskrit_letters = [u"ஶ", u"ஜ", u"ஷ", u"ஸ", u"ஹ", u"க்ஷ"] sanskrit_mei_letters = [u"ஶ்", u"ஜ்", u"ஷ்", u"ஸ்", u"ஹ்", u"க்ஷ்"] grantha_mei_letters = copy(mei_letters) grantha_mei_letters.extend(sanskrit_mei_letters) grantha_agaram_letters = copy(agaram_letters) grantha_agaram_letters.extend(sanskrit_letters) uyirmei_letters = [ u"ක", u"කා", u"කැ", u"කෑ", u"කි", u"කී", u"කු", u"කූ", u"කෘ", u"කෲ", u"කෟ", u"කෟෟ", u"කෙ", u"කේ", u"කෛ", u"කො", u"කෝ", u"කෞ", u"ඛ", u"ඛා", u"ඛැ", u"ඛෑ", u"ඛි", u"ඛී", u"ඛු", u"ඛූ", u"ඛෘ", u"ඛෘෘ", u"ඛෟ", u"ඛෟෟ", u"ඛෙ", u"ඛේ", u"ඛෛ", u"ඛො", u"ඛෝ", u"ඛෞ", u"ග", u"ගා", u"ගැ", u"ගෑ", u"ගි", u"ගී", u"ගු", u"ගූ", u"ගෘ", u"ගෘෘ", u"ගෟ", u"ගෟෟ", u"ගෙ", u"ගේ", u"ගෛ", u"ගො", u"ගෝ", u"ගෞ", u"ඝ", u"ඝා", u"ඝැ", u"ඝෑ", u"ඝි", u"ඝී", u"ඝු", u"ඝූ", u"ඝෘ", u"ඝෘෘ", u"ඝෟ", u"ඝෟෟ", u"ඝෙ", u"ඝේ", u"ඝෛ", u"ගො", u"ඝෝ", u"ඝෞ", u"ඞ", u"ඞා", u"ඞැ", u"ඞෑ", u"ඞි", u"ඞී", u"ඞු", u"ඞූ", u"ඞෘ", u"ඞෲ", u"ඞෟ", u"ඞෟෟ", u"ඞෙ", u"ඞේ", u"ඞෙෙ", u"ඞො", u"ඞෝ", u"ඝෞ", u"ඟ", u"ඟා", u"ඟැ", u"ඟෑ", u"ඟි", u"ඟී", u"ඟු", u"ඟූ", u"ඟෘ", u"ඟෘෘ", u"ඟෟ", u"ඟෟෟ", u"ඟෙ", u"ඟේ", u"ඟෛ", u"ඟො", u"ඟෝ", u"ඟෞ", u"ච", u"චා", u"චැ", u"චෑ", u"චි", u"චී", u"චු", u"චූ", u"චෘ", u"චෘෘ", u"චෟ", u"චෟෟ", u"චෙ", u"චේ", u"චෛ", u"චො", u"චෝ", u"චෞ", u"ඡ", u"ඡා", u"ඡැ", u"ඡෑ", u"ඡි", u"ඡී", u"ඡු", u"ඡූ", u"ඡෘ", u"ඡෘෘ", u"ඡෟ", u"ඡෟෟ", u"ඡෙ", u"ඡේ", u"ඡෛ", u"ඡො", u"ඡෝ", u"ඡෞ", u"ජ", u"ජා", u"ජැ", u"ජෑ", u"ජි", u"ජී", u"ජු", u"ජූ", u"ජෘ", u"ජෘෘ", u"ජෟ", u"ජෟෟ", u"ජෙ", u"ජේ", u"ජෛ", u"ජො", u"ජෝ", u"ජෞ", u"ඣ", u"ඣා", u"ඣැ", u"ඣෑ", u"ඣි", u"ඣී", u"ඣු", u"ඣූ", u"ඣෘ", u"ඣෘෘ", u"ඣෟ", u"ඣෟෟ", u"ඣෙ", u"ඣේ", u"ඣෛ", u"ඣො", u"ඣෝ", u"ඣෞ", u"ඤ", u"ඤා", u"ඤැ", u"ඤෑ", u"ඤි", u"ඤී", u"ඤු", u"ඤූ", u"ඤෘ", u"ඤෘෘ", u"ඤෟ", u"ඤෟෟ", u"ඤෙ", u"ඤේ", u"ඤෛ", u"ඤො", u"ඤෝ", u"ඤෞ", u"ට", u"ටා", u"ටැ", u"ටෑ", u"ටි", u"ටී", u"ටු", u"ටූ", u"ටෘ", u"ටෘෘ", u"ටෟ", u"ටෟෟ", u"ටෙ", u"ටේ", u"ටෛ", u"ටො", u"ටෝ", u"ටෞ", u"ඨ", u"ඨා", u"ඨැ", u"ඨෑ", u"ඨි", u"ඨී", u"ඨු", u"ඨූ", u"ඨෘ", u"ඨෘෘ", u"ඨෟ", u"ඨෟෟ", u"ඨෙ", u"ඨේ", u"ඨෛ", u"ඨො", u"ඨෝ", u"ඨෞ", u"ඪ", u"ඪා", u"ඪැ", u"ඪෑ", u"ඪි", u"ඪී", u"ඪු", u"ඪූ", u"ඪෘ", u"ඪෘෘ", u"ඪෟ", u"ඪෟෟ", u"ඪෙ", u"ඪේ", u"ඪෛ", u"ඪො", u"ඪෝ", u"ඪෞ", u"ණ", u"ණා", u"ණැ", u"ණෑ", u"ණි", u"ණී", u"ණු", u"ණූ", u"ණෘ", u"ණෘෘ", u"ණෟ", u"ණෟෟ", u"ණෙ", u"ණේ", u"ණෛ", u"ණො", u"ණෝ", u"ණෞ", u"ඬ", u"ඬා", u"ඬැ", u"ඬෑ", u"ඬි", u"ඬී", u"ඬු", u"ඬූ", u"ඬෘ", u"ඬෘෘ", u"ඬෟ", u"ඬෟෟ", u"ඬෙ", u"ඬේ", u"ඬෛ", u"ඬො", u"ඬෝ", u"ඬෞ", u"ත", u"තා", u"තැ", u"තෑ", u"ති", u"තී", u"තු", u"තූ", u"තෘ", u"තෘෘ", u"තෟ", u"තෟෟ", u"තෙ", u"තේ", u"තෛ", u"තො", u"තෝ", u"තෞ", u"ථ", u"ථා", u"ථැ", u"ථෑ", u"ථි", u"ථී", u"ථු", u"ථූ", u"ථෘ", u"ථෘෘ", u"ථෟ", u"ථෟෟ", u"ථෙ", u"ථේ", u"ථෛ", u"ථො", u"ථෝ", u"ථෞ", u"ද", u"දා", u"දැ", u"දෑ", u"දි", u"දී", u"දු", u"දූ", u"දෘ", u"දෘෘ", u"දෟ", u"දෟෟ", u"දෙ", u"දේ", u"දෛ", u"දො", u"දෝ", u"දෞ", u"ධ", u"ධා", u"ධැ", u"ධෑ", u"ධි", u"ධී", u"ධු", u"ධූ", u"ධෘ", u"ධෘෘ", u"ධෟ", u"ධෟෟ", u"ධෙ", u"ධේ", u"ධෛ", u"ධො", u"ධෝ", u"ධෞ", u"න", u"නා", u"නැ", u"නෑ", u"නි", u"නී", u"නු", u"නූ", u"නෘ", u"නෘෘ", u"නෟ", u"නෟෟ", u"නෙ", u"නේ", u"නෛ", u"නො", u"නෝ", u"නෞ", u"ඳ", u"ඳා", u"ඳැ", u"ඳෑ", u"ඳි", u"ඳී", u"ඳු", u"ඳූ", u"ඳෘ", u"ඳෘෘ", u"ඳෟ", u"ඳෟෟ", u"ඳෙ", u"ඳේ", u"ඳෛ", u"ඳො", u"ඳෝ", u"ඳෞ", u"ප", u"පා", u"පැ", u"පෑ", u"පි", u"පී", u"පු", u"පූ", u"පෘ", u"පෘෘ", u"පෟ", u"පෟෟ", u"පෙ", u"පේ", u"පෛ", u"පො", u"පෝ", u"පෞ", u"ඵ", u"ඵා", u"ඵැ", u"ඵෑ", u"ඵි", u"ඵී", u"ඵු", u"ඵූ", u"ඵෘ", u"ඵෘෘ", u"ඵෟ", u"ඵෟෟ", u"ඵෙ", u"ඵේ", u"ඵෛ", u"ඵො", u"ඵෝ", u"ඵෞ", u"බ", u"බා", u"බැ", u"බෑ", u"බි", u"බී", u"බු", u"බූ", u"බෘ", u"බෘෘ", u"බෟ", u"බෟෟ", u"බෙ", u"බේ", u"බෛ", u"බො", u"බෝ", u"පෞ", u"භ", u"භා", u"භැ", u"භෑ", u"භි", u"භී", u"භු", u"භූ", u"භෘ", u"භෘෘ", u"භෟ", u"භෟෟ", u"භෙ", u"භේ", u"භෛ", u"භො", u"භෝ", u"භෞ", u"ම", u"මා", u"මැ", u"මෑ", u"මි", u"මී", u"මු", u"මූ", u"මෘ", u"මෘෘ", u"මෟ", u"මෟෟ", u"මෙ", u"මේ", u"මෛ", u"මො", u"මෝ", u"මෞ", u"ඹ", u"ඹා", u"ඹැ", u"ඹෑ", u"ඹි", u"ඹී", u"ඹු", u"ඹූ", u"ඹෘ", u"ඹෘෘ", u"ඹෟ", u"ඹෟෟ", u"ඹෙ", u"ඹේ", u"ඹෛ", u"ඹො", u"ඹෝ", u"ඹෞ", u"ය", u"යා", u"යැ", u"යෑ", u"යි", u"යී", u"යු", u"යූ", u"යෘ", u"යෘෘ", u"යෟ", u"යෟෟ", u"යෙ", u"යේ", u"යෛ", u"යො", u"යෝ", u"යෞ", u"ර", u"රා", u"රැ", u"රෑ", u"රි", u"රී", u"රු", u"රූ", u"රෘ", u"රෘෘ", u"රෟ", u"රෟෟ", u"රෙ", u"රේ", u"රෛ", u"රො", u"රෝ", u"රෞ", u"ල", u"ලා", u"ලැ", u"ලෑ", u"ලි", u"ලී", u"ලු", u"ලූ", u"ලෘ", u"ලෘෘ", u"ලෟ", u"ලෟෟ", u"ලෙ", u"ලේ", u"ලෛ", u"ලො", u"ලෝ", u"ලෞ", u"ව", u"වා", u"වැ", u"වෑ", u"වි", u"වී", u"වු", u"වූ", u"වෘ", u"වෘෘ", u"වෟ", u"වෟෟ", u"වෙ", u"වේ", u"වෛ", u"වො", u"වෝ", u"වෞ", u"ශ", u"ශා", u"ශැ", u"ශෑ", u"ශි", u"ශී", u"ශු", u"ශූ", u"ශෘ", u"ශෘෘ", u"ශෟ", u"ශෟෟ", u"ශෙ", u"ශේ", u"ශෛ", u"ශො", u"ශෝ", u"ශෞ", u"ෂ", u"ෂා", u"ෂැ", u"ෂෑ", u"ෂි", u"ෂී", u"ෂු", u"ෂූ", u"ෂෘ", u"ෂෘෘ", u"ෂෟ", u"ෂෟෟ", u"ෂෙ", u"ෂේ", u"ෂෛ", u"ෂො", u"ෂෝ", u"ෂෞ", u"ස", u"සා", u"සැ", u"සෑ", u"සි", u"සී", u"සු", u"සූ", u"සෘ", u"සෘෘ", u"සෟ", u"සෟෟ", u"සෙ", u"සේ", u"සෛ", u"සො", u"සෝ", u"සෞ", u"හ", u"හා", u"හැ", u"හෑ", u"හි", u"හී", u"හු", u"හූ", u"හෘ", u"හෘෘ", u"හෟ", u"හෟෟ", u"හෙ", u"හේ", u"හෛ", u"හො", u"හෝ", u"හෞ", u"ළ", u"ළා", u"ළැ", u"ළෑ", u"ළි", u"ළී", u"ළු", u"ළූ", u"ළෘ", u"ළෘෘ", u"ළෟ", u"ළෟෟ", u"ළෙ", u"ළේ", u"ළෛ", u"ළො", u"ළෝ", u"ළෞ", u"ෆ", u"ෆා", u"ෆැ", u"ෆෑ", u"ෆි", u"ෆී", u"ෆු", u"ෆූ", u"ෆෘ", u"ෆෘෘ", u"ෆෟ", u"ෆෟෟ", u"ෆෙ", u"ෆේ", u"ෆෛ", u"ෆො", u"ෆෝ", u"ෆෞ" ] # constants TA_UYIR_LEN = len(uyir_letters) TA_MEI_LEN = len(mei_letters) TA_AGARAM_LEN = len(agaram_letters) TA_UYIRMEI_LEN = len(uyirmei_letters) # Ref: https://en.wikipedia.org/wiki/Tamil_numerals # tamil digits : Apart from the numerals (0-9), Tamil also has numerals for 10, 100 and 1000. tamil_digit_1to10 = [u"௦", u"௧", u"௨", u"௩", u"௪", u"௫", u"௬", u"௭", u"௮", u"௯", u"௰"] tamil_digit_100 = u"௱" tamil_digit_1000 = u"௲" tamil_digits = [(num, digit) for num, digit in zip(range(0, 11), tamil_digit_1to10)] tamil_digits.extend([(100, tamil_digit_100), (1000, tamil_digit_1000)]) # tamil symbols _day = u"௳" _month = u"௴" _year = u"௵" _debit = u"௶" _credit = u"௷" _rupee = u"௹" _numeral = u"௺" _sri = u"\u0bb6\u0bcd\u0bb0\u0bc0" # SRI - ஶ்ரீ _ksha = u"\u0b95\u0bcd\u0bb7" # KSHA - க்ஷ _ksh = u"\u0b95\u0bcd\u0bb7\u0bcd" # KSH - க்ஷ் tamil_symbols = [_day, _month, _year, _debit, _credit, _rupee, _numeral, _sri, _ksha, _ksh] # total tamil letters in use, including sanskrit letters tamil_letters = uyir_letters + uyirmei_letters + \ agaram_letters + mei_letters + [ayudha_letter] # grantha_uyirmei_letters = copy(tamil_letters[tamil_letters.index(u"கா") - 1:]) grantha_uyirmei_letters = copy(uyirmei_letters) # length of the definitions def uyir_len(): return TA_UYIR_LEN # 12 def mei_len(): return TA_MEI_LEN # 18 def agaram_len(): return TA_AGARAM_LEN # 18 def uyirmei_len(): return TA_UYIRMEI_LEN # 216 def tamil_len(): return len(tamil_letters) # access the letters def uyir(idx): assert (idx >= 0 and idx < uyir_len()) return uyir_letters[idx] def agaram(idx): assert (idx >= 0 and idx < agaram_len()) return agaram_letters[idx] def mei(idx): assert (idx >= 0 and idx < mei_len()) return mei_letters[idx] def uyirmei(idx): assert(idx >= 0 and idx < uyirmei_len()) return uyirmei_letters[idx] def mei_to_agaram(in_syllable): if in_syllable in grantha_mei_letters: mei_pos = grantha_mei_letters.index(in_syllable) agaram_a_pos = 0 syllable = uyirmei_constructed(mei_pos, agaram_a_pos) return syllable return in_syllable def uyirmei_constructed(mei_idx, uyir_idx): """ construct uyirmei letter give mei index and uyir index """ idx, idy = mei_idx, uyir_idx assert (idy >= 0 and idy < uyir_len()) assert (idx >= 0 and idx < 6 + mei_len()) return grantha_agaram_letters[mei_idx] + accent_symbols[uyir_idx] def tamil(idx): """ retrieve Tamil letter at canonical index from array utf8.tamil_letters """ assert (idx >= 0 and idx < tamil_len()) return tamil_letters[idx] # companion function to @tamil() def getidx(letter): for itr in range(0, tamil_len()): if tamil_letters[itr] == letter: return itr raise Exception("Cannot find letter in Tamil arichuvadi") # useful part of the API: def istamil_prefix(word): """ check if the given word has a tamil prefix. Returns either a True/False flag """ for letter in tamil_letters: if (word.find(letter) == 0): return True return False if not PYTHON3: def is_tamil_unicode_predicate( x): return x >= unichr(2946) and x <= unichr(3066) else: def is_tamil_unicode_predicate(x): return x >= chr(2946) and x <= chr(3066) def is_tamil_unicode(sequence): # Ref: languagetool-office-extension/src/main/java/org/languagetool/openoffice/TamilDetector.java if type(sequence) is list: return list(map(is_tamil_unicode_predicate, sequence)) if len(sequence) > 1: return list(map(is_tamil_unicode_predicate, get_letters(sequence))) return is_tamil_unicode_predicate(sequence) def all_tamil(word_in): """ predicate checks if all letters of the input word are Tamil letters """ if isinstance(word_in, list): word = word_in else: word = get_letters(word_in) return all([(letter in tamil_letters and letter != 'x') for letter in word]) def has_tamil(word): """check if the word has any occurance of any tamil letter """ # list comprehension is not necessary - we bail at earliest for letters in tamil_letters: if (word.find(letters) >= 0): return True return False def istamil(tchar): """ check if the letter tchar is prefix of any of tamil-letter. It suggests we have a tamil identifier""" if (tchar in tamil_letters): return True return False def istamil_alnum(tchar): """ check if the character is alphanumeric, or tamil. This saves time from running through istamil() check. """ return (tchar.isalnum() or istamil(tchar)) def reverse_word(word): """ reverse a Tamil word according to letters not unicode-points """ op = get_letters(word) op.reverse() return u"".join(op) # find out if the letters like, "பொ" are written in canonical "ப + ொ"" graphemes then # return True. If they are written like "ப + ெ + ா" then return False on first occurrence def is_normalized(text): # print(text[0],text[1],text[2],text[-1],text[-2]) TLEN, idx = len(text), 1 kaal = u"ா" Laa = u"ள" sinna_kombu, periya_kombu = u"ெ", u"ே" kombugal = [sinna_kombu, periya_kombu] # predicate measures if the normalization is violated def predicate(last_letter, prev_letter): if ((kaal == last_letter) and (prev_letter in kombugal)): return True if ((Laa == last_letter) and (prev_letter == sinna_kombu)): return True return False if TLEN < 2: return True elif TLEN == 2: if predicate(text[-1], text[-2]): return False return True idx = TLEN a = text[idx - 2] b = text[idx - 1] while (idx >= 0): if predicate(b, a): return False b = a idx = idx - 1 if idx >= 0: a = text[idx] return True def _make_set(args): args = list(filter(lambda x: x != '\u200d', args)) if PYTHON3: return frozenset(args) return set(args) grantha_agaram_set = _make_set(grantha_agaram_letters) accent_symbol_set = _make_set(accent_symbols) # accent_symbol_set_p = _make_set(accent_symbols_p) uyir_letter_set = _make_set(uyir_letters) # Split a tamil-unicode stream into # tamil characters (individuals). def get_letters(word): """ splits the word into a character-list of tamil/english characters present in the stream """ word = word.strip() word = word.replace('.', '') # print(word) ta_letters = list() not_empty = False WLEN, idx = len(word), 0 while (idx < WLEN): c = word[idx] # print(idx,hex(ord(c)),len(ta_letters)) if c in uyir_letter_set or c == ayudha_letter: ta_letters.append(c) not_empty = True elif c in grantha_agaram_set: ta_letters.append(c) not_empty = True elif c in accent_symbol_set: if not not_empty: # odd situation ta_letters.append(c) not_empty = True else: # print("Merge/accent") ta_letters[-1] = ta_letters[-1] + c # print(ta_letters[-1]) elif c == pulli_symbols[0]: ta_letters[-1] += c else: if ord(c) < 256 or not (is_tamil_unicode(c)): ta_letters.append(c) else: if not_empty: # print("Merge/??") ta_letters[-1] += c else: ta_letters.append(c) not_empty = True idx = idx + 1 return list(filter(lambda x: x != '\u200d', ta_letters)) _all_symbols = copy(accent_symbols) _all_symbols.extend(pulli_symbols) all_symbol_set = _make_set(_all_symbols) # same as get_letters but use as iterable def get_letters_iterable(word): """ splits the word into a character-list of tamil/english characters present in the stream """ WLEN, idx = len(word), 0 while (idx < WLEN): c = word[idx] # print(idx,hex(ord(c)),len(ta_letters)) if c in uyir_letter_set or c == ayudha_letter: idx = idx + 1 yield c elif c in grantha_agaram_set: if idx + 1 < WLEN and word[idx + 1] in all_symbol_set: c2 = word[idx + 1] idx = idx + 2 yield (c + c2) else: idx = idx + 1 yield c else: idx = idx + 1 yield c return grantha_uyirmei_splits = {} for _uyir_idx in range(0, 18): for _mei_idx, _mei in enumerate(grantha_mei_letters): _uyirmei = uyirmei_constructed(_mei_idx, _uyir_idx) grantha_uyirmei_splits[_uyirmei] = [_mei, uyir_letters[_uyir_idx]] def get_letters_elementary_iterable(word): for letter in get_letters_iterable(word): letter_parts = grantha_uyirmei_splits.get(letter, None) if letter_parts: yield letter_parts[0] yield letter_parts[1] else: yield letter return def get_letters_elementary(word): rval = [] word = word.strip() word = word.replace('.', '') for letter in get_letters(word): letter_parts = grantha_uyirmei_splits.get(letter, None) if letter_parts: rval.append(letter_parts[0]) rval.append(letter_parts[1]) else: rval.append(letter) return rval def get_words(letters, tamil_only=False): return [word for word in get_words_iterable(letters, tamil_only)] def get_words_iterable(letters, tamil_only=False): """ given a list of UTF-8 letters section them into words, grouping them at spaces """ # correct algorithm for get-tamil-words buf = [] for idx, let in enumerate(letters): if not let.isspace(): if istamil(let) or (not tamil_only): buf.append(let) else: if len(buf) > 0: yield u"".join(buf) buf = [] if len(buf) > 0: yield u"".join(buf) def get_tamil_words(letters): """ reverse a Tamil word according to letters, not unicode-points """ if not isinstance(letters, list): raise Exception( "metehod needs to be used with list generated from 'tamil.utf8.get_letters(...)'") return [word for word in get_words_iterable(letters, tamil_only=True)] if PYTHON3: def cmp(x, y): if x == y: return 0 if x > y: return 1 return -1 # answer if word_a ranks ahead of, or at same level, as word_b in a Tamil dictionary order... # for use with Python : if a > 0 def compare_words_lexicographic(word_a, word_b): """ compare words in Tamil lexicographic order """ # sanity check for words to be all Tamil if (not all_tamil(word_a)) or (not all_tamil(word_b)): # print("## ") # print(word_a) # print(word_b) # print("Both operands need to be Tamil words") pass La = len(word_a) Lb = len(word_b) all_TA_letters = u"".join(tamil_letters) for itr in range(0, min(La, Lb)): pos1 = all_TA_letters.find(word_a[itr]) pos2 = all_TA_letters.find(word_b[itr]) if pos1 != pos2: # print not( pos1 > pos2), pos1, pos2 return cmp(pos1, pos2) # result depends on if La is shorter than Lb, or 0 if La == Lb i.e. cmp return cmp(La, Lb) # return a list of ordered-pairs containing positions # that are common in word_a, and word_b; e.g. # தேடுக x தடங்கல் -> one common letter க [(2,3)] # சொல் x தேடுக -> no common letters [] def word_intersection(word_a, word_b): """ return a list of tuples where word_a, word_b intersect """ positions = [] word_a_letters = get_letters(word_a) word_b_letters = get_letters(word_b) for idx, wa in enumerate(word_a_letters): for idy, wb in enumerate(word_b_letters): if (wa == wb): positions.append((idx, idy)) return positions def unicode_normalize(cplxchar): Laa = u"ள" kaal = u"ா" sinna_kombu_a = u"ெ" periya_kombu_aa = u"ே" sinna_kombu_o = u"ொ" periya_kombu_oo = u"ோ" kombu_ak = u"ௌ" lcplx = len(cplxchar) if lcplx >= 3 and cplxchar[-1] == Laa: if cplxchar[-2] == sinna_kombu_a: return (cplxchar[:-2] + kombu_ak) if lcplx >= 2 and cplxchar[-1] == kaal: if cplxchar[-2] == sinna_kombu_a: return (cplxchar[:-2] + sinna_kombu_o) if cplxchar[-2] == periya_kombu_aa: return (cplxchar[:-2] + periya_kombu_oo) # no-op return cplxchar def splitMeiUyir(uyirmei_char): """ This function split uyirmei compound character into mei + uyir characters and returns in tuple. Input : It must be unicode tamil char. Written By : Arulalan.T Date : 22.09.2014 """ if not isinstance(uyirmei_char, PYTHON3 and str or unicode): raise ValueError("Passed input letter '%s' must be unicode, \ not just string" % uyirmei_char) if uyirmei_char in mei_letters or uyirmei_char in uyir_letters or uyirmei_char in ayudha_letter: return uyirmei_char if uyirmei_char not in grantha_uyirmei_letters: if not is_normalized(uyirmei_char): norm_char = unicode_normalize(uyirmei_char) rval = splitMeiUyir(norm_char) return rval raise ValueError( "Passed input letter '%s' is not tamil letter" % uyirmei_char) idx = grantha_uyirmei_letters.index(uyirmei_char) uyiridx = idx % 12 meiidx = int((idx - uyiridx) / 12) return (grantha_mei_letters[meiidx], uyir_letters[uyiridx]) # end of def splitMeiUyir(uyirmei_char): def joinMeiUyir(mei_char, uyir_char): """ This function join mei character and uyir character, and retuns as compound uyirmei unicode character. Inputs: mei_char : It must be unicode tamil mei char. uyir_char : It must be unicode tamil uyir char. Written By : Arulalan.T Date : 22.09.2014 """ if not isinstance(mei_char, PYTHON3 and str or unicode): raise ValueError("Passed input mei character '%s' must be unicode, \ not just string" % mei_char) if not isinstance(uyir_char, PYTHON3 and str or unicode): raise ValueError("Passed input uyir character '%s' must be unicode, \ not just string" % uyir_char) if mei_char not in grantha_mei_letters: raise ValueError("Passed input character '%s' is not a" "tamil mei character" % mei_char) if uyir_char not in uyir_letters: raise ValueError("Passed input character '%s' is not a" "tamil uyir character" % uyir_char) uyiridx = uyir_letters.index(uyir_char) meiidx = grantha_mei_letters.index(mei_char) # calculate uyirmei index uyirmeiidx = meiidx * 18 + uyiridx return grantha_uyirmei_letters[uyirmeiidx] def print_tamil_words(tatext, use_frequencies=False): taletters = get_letters(tatext) # for word in re.split(u"\s+",tatext): # print(u"-> ",word) # tamil words only frequency = {} for pos, word in enumerate(get_tamil_words(taletters)): frequency[word] = 1 + frequency.get(word, 0) # for key in frequency.keys(): # print(u"%s : %s"%(frequency[key],key)) # sort words by descending order of occurence for l in sorted(frequency.iteritems(), key=operator.itemgetter(1)): if use_frequencies: print(u"%d -> %s" % (l[1], l[0])) else: print(u"%s" % l[0]) def tamil_sorted(list_data): if PYTHON3: asorted = sorted(list_data, key=functools.cmp_to_key( compare_words_lexicographic)) else: asorted = sorted(list_data, cmp=compare_words_lexicographic) return asorted # Tamil Letters # அ ஆ இ ஈ உ ஊ எ ஏ ஐ ஒ ஓ ஔ ஃ # க் ச் ட் த் ப் ற் ஞ் ங் ண் ந் ம் ன் ய் ர் ல் வ் ழ் ள் ஜ் ஷ் ஸ் ஹ் # க ச ட த ப ற ஞ ங ண ந ம ன ய ர ல வ ழ ள ஜ ஷ ஸ ஹ # க கா கி கீ கு கூ கெ கே கை கௌ # ச சா சி சீ சு சூ செ சே சை சொ சோ சௌ # ட டா டி டீ டு டூ டெ டே டை டொ டோ டௌ # த தா தி தீ து தூ தெ தே தை தொ தோ தௌ # ப பா பி பீ பு பூ பெ பே பை பொ போ பௌ # ற றா றி றீ று றூ றெ றே றை றொ றோ றௌ # ஞ ஞா ஞி ஞீ ஞு ஞூ ஞெ ஞே ஞை ஞொ ஞோ ஞௌ # ங ஙா ஙி ஙீ ஙு ஙூ ஙெ ஙே ஙை ஙொ ஙோ ஙௌ # ண ணா ணி ணீ ணு ணூ ணெ ணே ணை ணொ ணோ ணௌ # ந நா நி நீ நு நூ நெ நே நை நொ நோ நௌ # ம மா மி மீ மு மூ மெ மே மை மொ மோ மௌ # ன னா னி னீ னு னூ னெ னே னை னொ னோ னௌ # ய யா யி யீ யு யூ யெ யே யை யொ யோ யௌ # ர ரா ரி ரீ ரு ரூ ரெ ரே ரை ரொ ரோ ரௌ # ல லா லி லீ லு லூ லெ லே லை லொ லோ லௌ # வ வா வி வீ வு வூ வெ வே வை வொ வோ வௌ # ழ ழா ழி ழீ ழு ழூ ழெ ழே ழை ழொ ழோ ழௌ # ள ளா ளி ளீ ளு ளூ ளெ ளே ளை ளொ ளோ ளௌ # ஶ ஶா ஶி ஶீ ஶு ஶூ ஶெ ஶே ஶை ஶொ ஶோ ஶௌ # ஜ ஜா ஜி ஜீ ஜு ஜூ ஜெ ஜே ஜை ஜொ ஜோ ஜௌ # ஷ ஷா ஷி ஷீ ஷு ஷூ ஷெ ஷே ஷை ஷொ ஷோ ஷௌ # ஸ ஸா ஸி ஸீ ஸு ஸூ ஸெ ஸே ஸை ஸொ ஸோ ஸௌ # ஹ ஹா ஹி ஹீ ஹு ஹூ ஹெ ஹே ஹை ஹொ ஹோ ஹௌ # க்ஷ க்ஷா க்ஷி க்ஷீ க்ஷு க்ஷூ க்ஷெ க்ஷே க்ஷை க்ஷொ க்ஷோ க்ஷௌ
""" Insertion sort is the method to sort an array. In insertion sort we divide an array into two parts: sorted part and unsorted part. Every time we select the first value from the unsorted part and find its position in sorted part and place it there. """ def insertion_sort(arr): # Insertion sort is composed of two loops # One is outer loop and second is inner loop # I'll use for loop as an outer loop and # while loop as an inner loop for i in range(1, len(arr)): value = arr[i] # Inner loop j = i while (j > 0 and arr[j-1] > value): arr[j] = arr[j-1] j = j - 1 arr[j] = value # Test the code array = [30, 44, 67, 5, 8, 9, 53] # Let sort this array insertion_sort(array) # Insertion sort did in-place sort print(array)
# Recurrent Neural Networks # Part 1 - Data Preprocessing import math import matplotlib.pyplot as plt import numpy as np import pandas as pd from keras.layers import LSTM, Dense, Dropout from keras.models import Sequential from sklearn.metrics import mean_squared_error from sklearn.preprocessing import MinMaxScaler # Importing the training set dataset_train = pd.read_csv('data/Google_Stock_Price_Train.csv') # Separate training set training_set = dataset_train.iloc[:, 1:2].values # Feature Scaling to optimize the process sc = MinMaxScaler(feature_range = (0, 1)) training_set_scaled = sc.fit_transform(training_set) # Creating a data structure with 60 timesteps and 1 output # This means that RNN will use 60 timestamp backward to learn the trend and # use 1 output to make prediction X_train = [] y_train = [] for i in range(60, 1258): X_train.append(training_set_scaled[i-60:i, 0]) y_train.append(training_set_scaled[i, 0]) # X_train contains first 60th values of time series # y_train contains points from time t+1 and forward # This for loop seems like taking first difference but not for # whole data but only for 60 point. so slicing window equal to 60 X_train, y_train = np.array(X_train), np.array(y_train) # Reshaping X_train = np.reshape(X_train, (X_train.shape[0], X_train.shape[1], 1)) # Part 2 - Building the RNN # Initializing the RNN regressor = Sequential() # Adding the first LSTM layer and some Dropout regularization regressor.add(LSTM(units = 50, return_sequences = True, input_shape = (X_train.shape[1], 1))) # "units" argument is the number of the LSTMs themselves # or the number of memory units you want to have in LSTM # Moreover, units=50 gives us high dimensionality # in order to catch the price trend more accurately # "return_sequence" argument is set to True because we build stacked # LSTM and adding extra layers # "input_shape" argument is the shape of our dataset X_train regressor.add(Dropout(0.2)) # Dropout rate is the rate at which we drop or ignore layers in LSTM # This means that 10 neurons will be ignored at each iteration # Adding a second LSTM layer and some Dropout regularization regressor.add(LSTM(units = 50, return_sequences = True)) regressor.add(Dropout(0.2)) # Adding a third LSTM layer and some Dropout regularization regressor.add(LSTM(units = 50, return_sequences = True)) regressor.add(Dropout(0.2)) # Adding a fourth LSTM layer and some Dropout regularization regressor.add(LSTM(units = 50)) regressor.add(Dropout(0.2)) # Adding the output layer # This is classic fully connected layer # units here is the price of stock at time t+1 regressor.add(Dense(units = 1)) # Compiling the RNN # As we have regression problem here, we use mean squared error regressor.compile(optimizer = 'adam', loss = 'mean_squared_error') # Fitting the RNN to the Training Set regressor.fit(X_train, y_train, epochs = 100, batch_size = 32) # Part 3 - Making the predictions and visualizing the results # Getting the real stock price of 2017 dataset_test = pd.read_csv('data/Google_Stock_Price_Test.csv') # This is ground truth or real price of stock in January real_stock_price = dataset_test.iloc[:, 1:2].values # Getting the predicted stock price of 2017 # Conatenate training and test set # Concatenation is necessary in order to get 60 previous inputs # for each day of January 2017 or our test data set # We have to concatenate original data frames not scaled ones dataset_total = pd.concat((dataset_train['Open'], dataset_test['Open']), axis = 0) # Load 60 previous day # Lower bound will be january 3rd, 2017 minus 60 # Upper bound is 60 previous days before this last day of january 2017 # or last index of whole dataset or dataset_total inputs = dataset_total[len(dataset_total) - len(dataset_test) - 60:].values # Reshape and scale inputs inputs = inputs.reshape(-1,1) inputs = sc.transform(inputs) # With this loop we'll get 60 previous inputs for each of the # stock prices of January 2017 which contains 20 days X_test = [] for i in range(60, 80): X_test.append(inputs[i-60:i, 0]) X_test = np.array(X_test) X_test = np.reshape(X_test, (X_test.shape[0], X_test.shape[1], 1)) predicted_stock_price = regressor.predict(X_test) predicted_stock_price = sc.inverse_transform(predicted_stock_price) # Evaluate the model # We need to calculate RMSE # This RMSE is in absolute terms rmse = math.sqrt(mean_squared_error(real_stock_price, predicted_stock_price)) # We need to divide RMSE by the range of stock price during January 2017 range_stock_price = real_stock_price.max() - real_stock_price.min() # This is RELATIVE ERROR relative_rmse = rmse / range_stock_price # Visualizing the results plt.plot(real_stock_price, color = 'red', label = 'Real Google Stock Price') plt.plot(predicted_stock_price, color = 'blue', label = 'Predicted Google Stock Price') plt.title('Google Stock Price Prediction') plt.xlabel('Time') plt.ylabel('Google Stock Price') plt.grid() plt.legend() plt.show()
""" Tree is a type of nonlinear data stricture, where data is connected to each other in hierarchy. Every container of data is called node. Top node is called root node, and nodes at the end of tree are called leaf nodes. "Binary Search Tree is a type of data structure which have at most two children. It cannot have more than two children. Every node of the tree has to have at most 2 child. This is BST In BST, smaller nodes are at the left of root node and bigger nodes are at the right side of root node. This procedure is repeated for every sub tree, until we find appropriate place for new node. """ class Node: # Constructor def __init__(self,value): # value parameter is data we want to store self.value = value self.left = None # At the start we have no left node self.right = None # At the start we have no right node def insert(root,node): # Insert is recursive function if root is None: # Base condition root = node return root if node.value < root.value: root.left = insert(root.left, node) if node.value > root.value: root.right = insert(root.right, node) return root def pre_order_traversal(root): """ Pre-Order traversal. In pre-order traversal, print the root first, after that print left child and than right child. This pattern has to be true for all subtree. """ if root: # Check if root is empty, and then print left and then right node print(root.value) pre_order_traversal(root.left) pre_order_traversal(root.right) def in_order_traversal(root): """ In-Order traversal prints left child first, then root and then right child. This pattern has to be true for all subtree. """ if root: in_order_traversal(root.left) print(root.value) in_order_traversal(root.right) def post_order_traversal(root): """ Post-Order traversal prints left node first, then right node and then root node. This pattern repeats for every subtree. """ if root: post_order_traversal(root.left) post_order_traversal(root.right) print(root.value) def get_minimum_value_node(root): """ Get the node with the minimum value. The minimum value node is always left most in the BST """ if root: while root.left is not None: root = root.left return root def get_maximum_value_node(root): """ Get the node with the maximum value The maximum value node is always right most in the BST """ if root: while root.right is not None: root = root.right return root """ When we want to delete node in BST, there are three possibilities. First possibility is to delete node which is leaf node and has no any child. Second possibility is to delete node which has one child. When we do this kind of deletion, child node of deleted root node will take it's parent's place. Third possibility is to delete node which has both child, left node and right node. In this case we have to find the node which will take deleted node's position, so that BST maintain it's order. """ def delete_node(root,value): if root is None: # Base condition return root # We need to find value in our BST if value < root.value: root.left = delete_node(root.left, value) elif value > root.value: root.right = delete_node(root.right, value) # else part will only go when the value will be found else: if root.left is None: # First possibility temp = root.right root = None return temp elif root.right is None: # Second possibility temp = root.left root = None return temp else: # Third possibility temp = get_minimum_value_node(root.right) root.value = temp.value root.right = delete_node(root.right, temp.value) return root """ Test our class of BST """ # Initialize Node class and set initial value root = Node(50) # Insert new node insert(root, Node(10)) insert(root, Node(2)) insert(root, Node(80)) insert(root, Node(15)) insert(root, Node(60)) insert(root, Node(90)) # Pre-order traversal pre_order_traversal(root) # In-order traversal in_order_traversal(root) # Post-order traversal post_order_traversal(root) # Get minimum value node get_minimum_value_node(root).value # .value gives actual value of a node # Get maximum value node get_maximum_value_node(root).value # Delete main root node delete_node(root,50) # Post-order traversal to see the new BST values post_order_traversal(root) # # Resource # http://interactivepython.org/lpomz/courselib/static/pythonds/Trees/SearchTreeImplementation.html
""" Breadth First Search """ class Node: def __init__(self, name): self.name = name self.adjacencyList = [] self.visited = False self.predecessor = None class Breadth_First_Search: def bfs(self, startNode): queue = [] queue.append(startNode) startNode.visited = True # Breadth First Search is implemented by using Queue while queue: actualNode = queue.pop(0) print('%s ' % actualNode.name) for n in actualNode.adjacencyList: if not n.visited: n.visited = True queue.append(n) # Test the algorithm # insert nodes node1 = Node("A") node2 = Node("B") node3 = Node("C") node4 = Node("D") node5 = Node("E") # Define neighbor nodes.node1 has children node2 and node3 node1.adjacencyList.append(node2) node1.adjacencyList.append(node3) node2.adjacencyList.append(node4) node4.adjacencyList.append(node5) bfs = Breadth_First_Search() bfs.bfs(node1)
""" K-Means """ import matplotlib.pyplot as plt import numpy as np import pandas as pd from sklearn.cluster import KMeans # Import the dataset dataset = pd.read_csv('data/Mall_Customers.csv') # Create independent variable X = dataset.iloc[:, [3,4]].values # Using the Elbow Method to find the optimal number of clusters # We have to write for loop, to loop inside ten clusters and plot the result # create empty list wcss = [] for i in range(1, 11): kmeans = KMeans(n_clusters = i, init = 'k-means++', max_iter = 300, n_init = 10, random_state = 0) # we create k-means object we some parameters # n_cluster is the number of cluster or our iterator # init is to avoid random initialization trap # max_iter means maximum number of iterations to find final clusters # n_init is number of times the algorithm, will be run with different initial centroids kmeans.fit(X) # Fit the model to the dataset wcss.append(kmeans.inertia_) # computes wcss or inertia # Plot the result of loop # The plot show that 5 cluster will be optimal plt.plot(range(1, 11), wcss) plt.title('The Elbow Method') plt.xlabel('Number of Clusters') plt.ylabel('Wcss') plt.show() # Now let apply k-means to the dataset # Create new k-means object kmeans = KMeans(n_clusters = 5, init = 'k-means++', max_iter=300, n_init=10, random_state=0) # Make "prediction" which client belongs to which cluster y_kmeans = kmeans.fit_predict(X) # Visualize the clusters along with data points plt.scatter(X[y_kmeans == 0, 0], X[y_kmeans == 0, 1], s=100, c='red', label='Careful') plt.scatter(X[y_kmeans == 1, 0], X[y_kmeans == 1, 1], s=100, c='blue', label='Standard') plt.scatter(X[y_kmeans == 2, 0], X[y_kmeans == 2, 1], s=100, c='green', label='Target') plt.scatter(X[y_kmeans == 3, 0], X[y_kmeans == 3, 1], s=100, c='cyan', label='Careless') plt.scatter(X[y_kmeans == 4, 0], X[y_kmeans == 4, 1], s=100, c='magenta', label='Sensible') plt.scatter(kmeans.cluster_centers_[:,0], kmeans.cluster_centers_[:,1], s=300, c='yellow', label='Centroids') plt.title('Clusters of clients') plt.xlabel('Annual Income (k$)') plt.ylabel('Spending score (1-100)') plt.legend() plt.show()
""" simple Linear Regression with Gradient Descent """ import pandas as pd # Open dataset df = pd.read_csv('data/data.csv') # Convert Pandas DataFrame into List df = df.values """ In our case Y = b + m*X where, m is slope and b is intercept To find best estimates for slope and intercept we need to define cost function or error function. In our case it's C(b,m) = 1/N * sum[y - y_hat]^2 """ # Function computes error for a line given points def cost_fun(b,m,points): totalError = 0 for i in range(len(points)): # iteration goes through each point for independent and dependent variables x = points[i, 0] y = points[i, 1] totalError = totalError + (y - (m*x + b)) ** 2 return totalError / float(len(points)) # To check the function put any values for b and m and also put your df cost_fun(1.2,1.3,df) """ To run Gradient Descent we need first order derivatives of our cost function with respect to slope and intersept Taking derivative gives us: d/dm = 2/N * sum[-x(y - (m*x + b))] d/db = 2/N * sum[-(y - (m*x + b))] """ # Function computes the direction of Gradient for any initial guess. # b_current and m_current are our initial guess for gradients # what we put in our gradient function def gradient(b_currnet, m_current, points, learningRate): # b_gradient and m_gradient will adjust for each iteration b_gradient = 0 m_gradient = 0 N = float(len(points)) # Calculate the new value of gradient for i in range(0, len(points)): x = points[i,0] y = points[i,1] b_gradient = b_gradient + (-(2/N) * (y - ((m_current * x) + b_currnet))) m_gradient = m_gradient + (-(2/N) * x * (y -(m_current * x) + b_currnet)) # These are adjusted new estimates # Learning Rate is step size for gradient iteration new_b = b_currnet - (learningRate * b_gradient) new_m = m_current - (learningRate * m_gradient) return [new_b, new_m] # Function gives new estimates for b and m adjusted by the value of gradient gradient(0,-1,df, 0.001) # We need to run our gradient function for number of iteration to # obtain optimal values for estimates def gradient_runner(points, starting_b, starting_m, learning_rate, num_iterations): b = starting_b m = starting_m for i in range(num_iterations): b, m = gradient(b, m, df, learning_rate) return [b,m] # If Learning Rate is 0.001 or more (0.01, 0.1) function does not work due to # division by zero gradient_runner(df,0,-1,0.0001,2000) # Function does all the above steps all together def run(): points = df learning_rate = 0.000005 # Initial guesses for b and m initial_b = 0 initial_m = 0 num_iterations = 1000 print("Starting Gradient Descent at b = {0}, m = {1}, error = {2}".format(initial_b, initial_m, cost_fun(initial_b, initial_m, points))) [b, m] = gradient_runner(points, initial_b, initial_m, learning_rate, num_iterations) print("After {0} iterations b = {1}, m = {2}, error = {3}".format(num_iterations, b, m, cost_fun(b, m, points))) # To tune the parameters change them only inside run() function if __name__ == '__main__': run()
# Tip calculator # Ask for meal price # Ask how waiter was #suggested tip based on service #choose tip #calculate tip # Extra: total meal cost # Extra: Ask for weekly budget and subtract from budget # Welcome print("Welcome to the X Tip Calculator!") input("How was your meal?") print("Wonderful! Now let's calculate how much your tip will be.") # Tip Suggestion based on waiter rating def suggestion(meal, service): # Service recommendation if service < 5: print("Sorry to hear that!") suggest = "10%" + " or 15%" elif 5 <= service < 8: print("Awesome") suggest = "15%" + " or 20%" else: print("Awesome!") suggest = "15%" + " or 20%" # while print(f"Based on your input, we suggest a tip of {suggest}") # Tip Calculation def tip_amount(meal, percent): if percent.isdigit() == True: tip = meal * (float(percent)/100) else: percent = percent[:-1] tip = round(meal * (float(percent)/100), 2) return tip # Total Tip Amount and Meal Price def meal_price(meal, percent): print(f"Your tip amount is: ${tip_amount(meal, percent)}") total = meal + tip_amount(meal, percent) print(f"Your total meal price is: ${total}") # Inputs meal = float(input("What was the total price of your meal (including tax)?")) service = int(input("Great! How would you rate your service from 1 to 10? (10 being highest)")) suggestion(meal, service) percent = (input("What percent tip would you like to give? (Enter non-decimal number)")) meal_price(meal, percent)
def remove(arr): pass def print_gray_code(arr1, arr2): print(arr1, arr2) if len(arr2) > 1: arr2 = arr2[1:] arr1 += arr2[:1] arr1, arr2 = print_gray_code(arr1, arr2) elif arr2[0] == 1: print_gray_code([], arr1 + [0]) elif arr2[0] == 0: return arr1, arr2 else: return arr1, [0] return arr1, arr2 if __name__ == '__main__': arr = [1, 1, 1, 1] a = print_gray_code([], arr) print(a)
# This script uses the Montecarlo method to find the # [approximated] area under a curve (definite integral) import math import random import time import numpy as np import scipy.integrate as integrate import matplotlib.pyplot as plt def montecarlo_iterative_integration(fun, a, b, num_puntos=1000): # To keep track of time tic = time.time() #HALLAMOS M M = 0 for i in np.arange(a, b, (b-a)/num_puntos): aux = fun(i) if aux > M : M = aux print("\n__Integral (iterative)__") print("Máximum: ", M) #QUEDA DEFINIDO EL CUADRADO ENTRE A-B Y 0-M #LANZAMOS PUNTOS ALEATORIOS DENTRO DEL CUADRADO nDebajo = 0 for i in range(num_puntos): x = random.uniform(a, b) y = random.uniform(0, M) if fun(x)>y : nDebajo+=1 print("Points under curve: ", nDebajo) print("Total points: ", num_puntos) I = (nDebajo/num_puntos)*(b-a)*M print ("Montecarlo integral: ", I) toc = time.time() print("time: ", 1000*(toc - tic)) return 1000*(toc - tic) def montecarlo_vectorized_integration(fun, a, b, num_puntos=1000): # To keep track of time tic = time.time() # Vectors with uniformly distributed points vectorX = np.random.uniform(low = a, high = b, size =(num_puntos)) vectorizedFun = np.vectorize(fun) funResults = vectorizedFun(vectorX) M = funResults.max() vectorY = np.random.uniform(low = 0, high = M, size =(num_puntos)) print("\n__Integral (vectorized)__") print("Máximum: ", M) # Points under the curve nDebajo = np.greater(funResults, vectorY).sum() print("Points under curve: ", nDebajo) print("Total points: ", num_puntos) # Value of the integral (Montecarlo approximation) I = (nDebajo/num_puntos)*(b-a)*M print ("Montecarlo integral: ", I) toc = time.time() print("Time: ", 1000*(toc - tic)) return 1000*(toc - tic) iterativeArray = [] vectorizedArray = [] iValues = [] # Compare both methods (iterative and vectorized) performance when using # increasingly larger number of points for i in range(1, 1000000, 100000): iterativeArray.append(montecarlo_iterative_integration(math.sin, 0, math.pi, i)) vectorizedArray.append(montecarlo_vectorized_integration(math.sin, 0, math.pi, i)) iValues.append(i) # Show and save the results plt.figure() plt.scatter(iValues, iterativeArray, color='red', label="Iterative") plt.scatter(iValues, vectorizedArray, color='blue', label="Vectorized") plt.ylabel('Time comparison') plt.legend() plt.savefig("time_comparison.png") plt.show() print("\nReal integral value: ", integrate.quad(math.sin, 0, math.pi)[0], "\n")
# coding: utf-8 # In[5]: get_ipython().magic(u'matplotlib inline') import numpy as np import matplotlib.pyplot as plt x=[30,30,70,70,100] a=20 b=70 plt.xlabel('EJE X') plt.title('FUNCION HOMBRO') plt.grid() def f(x,a,b): if (x<a): ans=0 if (x>=a)&(x<b): ans=(x-a)/(b-a) if (x>=b): ans=1 return ans fun_vect = np.vectorize(f) func=fun_vect(x,a,b) print func plt.axis([x[0], x[-1], 0, 2]) plt.plot(x,fun_vect(x,a,b)) # In[ ]:
from abc import ABC from abc import abstractmethod from gamestatus import Gamestatus import random from numpy import random class Challenge (ABC): def __init__(self, victim, challenged_card, n_players, players, deck): self.victim = victim self.challenged_card = challenged_card self.n_players = n_players self.players = players self.deck = deck def challenge(self): attackers = [] y_n = input('someone whats to challenge this action?(yes/no)') if y_n == 'yes': for i in range(self.n_players): if self.players[i] != self.victim: print(i+1, '.-', self.players[i].name) attacker1 = (int(input()))-1 attackers.append(attacker1) y_n = input('someone else whats to challenge this action?(yes/no)') if y_n == 'yes': for i in range(self.n_players): if self.players[i] != self.victim: print(i+1, '.-', self.players[i].name) attacker2 = (int(input()))-1 attackers.append(attacker2) if self.n_players == 4 and y_n == 'yes': y_n = input('someone else whats to challenge this action?(yes/no)') if y_n == 'yes': for i in range(self.n_players): if self.players[i] != self.victim: print(i+1, '.-', self.players[i].name) attacker3 = (int(input()))-1 attackers.append(attacker3) attacker = random.choice(attackers) print(self.players[attacker].name, 'is challenging') if self.challenged_card == self.victim.cards[0] or self.challenged_card == self.victim.cards[1]: print(self.players[attacker].name, 'lose the challenge') print(self.players[attacker].name, 'chose a card to reval!') print('1.-', self.players[attacker].playing_cards[0]) print('2.-', self.players[attacker].playing_cards[1]) choosen_card = int(input())-1 Gamestatus.Change_gamestatus(Gamestatus(self.players[attacker], self.players, self.n_players), self.players[attacker], choosen_card) return False else: print(self.victim.name, 'lose the challenge') print(self.victim.name, 'chose a card to reval!') print('1.-', self.victim.playing_cards[0]) print('2.-', self.victim.playing_cards[1]) choosen_card = int(input())-1 Gamestatus.Change_gamestatus(Gamestatus(self.players[attacker], self.players, self.n_players), self.victim, choosen_card) return 'attacker' elif y_n == 'no': return False
#code created by NamanNimmo Gera #12:42pm, April 10, 2019. from itertools import permutations #importing permutations :) perm = permutations([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) for count, item in enumerate(perm): #to find the millionth permutation if count == 999999: print(item)
#approach no. 2 for solving problem 33 import math frac=1.0 for b in range(1,10): for a in range(1,b): for c in range(1,10): if (a*10+b)/(b*10+c)==a/c: frac*=(a/c) print(math.ceil(1/frac))
## # Main function of the Python program. # ## # from math import pi # returns the area of a circle, given it's radius def area_of_circle(radius): area = 0 return area # Returns the distance travelled, given speed and time which are integer values (km/h and hours respectively) def distance_travelled(average_speed, time): distance=0 return distance # Returns the area and volume of a sphere, given its radius def surface_area_and_volume_of_sphere(radius): area=0 volume=0 return area, volume # The following code helps you to perform some basics tests for the above functions # It may not include all possible test cases to show that your code is totally correct. # # Test option is not available here, only Submit after Run. # When you submit, additional test cases may be performed. # r=10 print("<h4>-- Area of Circle --</h4>") area=area_of_circle(r) print("Area of radius is: ", area) print("<h4>-- Area and volume of sphere --</h4>") area,volume=surface_area_and_volume_of_sphere(r) print("Area and volume of sphere: ", area, volume) print("<h4>-- Distance travelled --</h4>") avg_speed=100 t=3 distance = distance_travelled(avg_speed, t) print("Distance travelled: ", distance)
import palmero plm = palmero.Palmero() def main(): plm.logo() print("\n0: Create test file") print("1: Encrypt File") print("2: Decrypt File") print("3: Generate Key") print("4: Help") next = input() if next == "0": with open('example.txt', 'w') as exm: exm.write("This is an example of a file to encrypt!\n1 2 3 4 \n|?<>:!@#$%^&*()|}{][]}") print("Created 'example.txt'") main() if next == "1": file = input("File to encrypt: ") passw = input("Password: ") try: plm.encrypt(file, passw) except FileNotFoundError: print("That file doesn't exist!") input() main() print("Encrypted!") input() main() if next == "2": file = input("File to decrypt: ") passw = input("Password: ") try: data = plm.decrypt(file, passw) except FileNotFoundError: print("That file doesn't exist!") input() main() except: print("Your password is incorrect!") input() main() print("Decrypted!\nData is: %s" % data) input() main() if next == "3": passw = input("Password: ") try: key = plm.keyGen(passw) except: print("There was an error!") input() main() print("Generated!\nThe key is %s" % key) input() main() if next == "4": helpx() main() def helpx(): print("Encrypt: Used to encrypt a file. Returns True if successful.\nParameters:\n") enchelp = { "file":"Specify the file to encrypt", "password":"The password used for encryption", "outname":"(Optional, Off by default) The name of the encrypted file", "delete_original":"(Optional, On by default) Delete the original file after encrypting" } for key,val in enchelp.items(): print("%s: %s" %(key, val)) print("\nDecrypt: Used to decrypt a file. Returns decrypted data.\nParameters:\n") dcrhelp = { "file":"Specify the file to decrypt", "password":"The password used for decryption", "outfile":"(Optional, Off by default) Save the decrypted data back to a file, named per the encrypted file name", "keyfile":"(Optional) Specify location of a decryption key, stored in a file." } for key,val in dcrhelp.items(): print("%s: %s" %(key, val)) print("\nGenerate Key: Used to generate a decryption key, so files can be decrypted on other computers. Returns key string that can be saved to a file.\nParameters:\n") gnkhelp = { "password":"The password used for decryption", "outfile":"(Optional, Off by default) Save the generated key to a file", } for key,val in gnkhelp.items(): print("%s: %s" %(key, val)) input() main()
""" Sample Controller File A Controller should be in charge of responding to a request. Load models to interact with the database and load views to render them to the client. Create a controller using this template """ from system.core.controller import * from flask import url_for class Books(Controller): def __init__(self, action): super(Books, self).__init__(action) """ This is an example of loading a model. Every controller has access to the load_model method. """ self.load_model('Book') self.db = self._app.db """ This is an example of a controller method that will load a view for the client """ def index(self): """ A loaded model is accessible through the models attribute self.models['WelcomeModel'].get_users() self.models['WelcomeModel'].add_message() # messages = self.models['WelcomeModel'].grab_messages() # user = self.models['WelcomeModel'].get_user() # to pass information on to a view it's the same as it was with Flask # return self.load_view('index.html', messages=messages, user=user) """ books=self.models['Book'].get_all_books() reviews=self.models['Book'].get_most_recent_books() return self.load_view('books.html', books=books, reviews=reviews) def add(self): authors_all=self.models['Book'].display_authors() print "authors_all returned: " + str(authors_all) return self.load_view('add_book.html', authors=authors_all) def add_review(self, book_id): print "we are in add_review", book_id #run a query to get 3 most recent reviews of that book three_reviews = self.models['Book'].get_book_reviews(book_id) title_author= self.models['Book'].get_book_title(book_id) return self.load_view('add_book_review.html', three_reviews=three_reviews, title_author=title_author[0]) def create_book(self): # print "Connor said this is"+ request.form['author_alt'] print "we are in create_book" if request.form['author_alt']: author=request.form['author_alt'] author_exists=False else: author=request.form['author'] author_exists = True # print "before book_info is assigned" # print request.form['title'] # print request.form['review'] # print request.form['ratings'] #print session['id'] # print author_exists data_info = { 'title' : request.form['title'], 'author':author, 'review':request.form['review'], 'ratings':request.form['rating'], 'user_id':session['id'], 'author_exists': author_exists } print "after book_info is assigned" # print book_info['author'] book_id=self.models['Book'].insert_book(data_info) # print "this is book_id", book_id url = "/books/"+str(book_id) return redirect(url) # return redirect("/books/", book_id) # return redirect(url_for('/books', book_id=book_id)) def create_new_review(self): print "we are create_new_review" data={ 'review':request.form['review'], 'ratings':request.form['ratings'], 'book_id':request.form['book_id'], 'user_id':session['id'] } self.models['Book'].insert_new_review(data) url = "/books/"+str(data['book_id']) return redirect(url)
#typeDynamic language """ commente chand khati khate dovom khate sevom """ #niaz be taine noe nist va noe var mitavanad taghir konad a = "sadegh" print(a) a = 10 print(a) #nahve neveshtane do khat code dar yek khat b = 15; b+=10 print(b) #anvae vars #number #string #list #tuple #dictionary #chand entesab hamzaman a,b,c = 1,2,"Reza" print(a,b,c) c = 50 print(c) a = b = c = 40 print(c) #reshteye chand khati text = """khate aval khate dovom khate sevom""" print(text) #elhaghe do reshte ba operatore + va , #agar az virgul estefade konim yek space beine reshte ha ezafe mishavad #ham chenin dar amalgare + amalvand ha bayad ba ham bekhanand masalan #reshte ra ba adad nemitavan jam kard (vali virgul in moshkelo nadare) grade = 14 print("Grade:" + str(grade)) print("Score:", grade) #amalgare * ham baraye reshteha darim print("Salam" * 3) int_number = 2500 long_number = 26545646465456456464 float_number = 105.25e+6 complex_number = 16.5e-4j #Operators #** -> tavan #// -> jazr print(3 ** 3) int_number = int("145") c1 = 14 + 5j c2 = complex(14, 5) print("c1==c2: ", c1==c2) print(max(4, 8, 52)) text2 = "Python strings is excellent!!!" print(text2[1]) print(text2[0:4]) print(text2[:4]) print(text2[4:]) print(len(text2)) print(text2.count(" ")) #tedade space ha tuye reshte ro barmigardune print("string" in text2) print("string" not in text2) print("Sadegh\nBagherzadeh") seperator = "," print("hamid%s reza%s mehdi" %(seperator, seperator)) text3 = "hamid be Madrese raft" print(text3.capitalize()) #harfe avale jomle bozorg va baghie kuchik print(text3.upper()) print(text3.split(" "))
#!/usr/bin/env python3 ''' This method checks if the number is a prime number or not ''' def IsPrime (n): # loop from 2 to n (exclusive) for i in range (2, n): # if n is divisible by i, then we dont have a prime number if (n % i == 0): return False # if we get here, the number is prime return True ''' This method returns the sum of the first x number of prime numbers, where x = limit ''' def Prime (limit): # declare variables count, result = 0, 0 # we will start at 2, because 0 & 1 are not primes i = 2 # while the count is less than the limit while (count < limit): # check if current number is a prime if (IsPrime (i)): # if prime, then add to result result += i # increment the number of primes count += 1 # go to the next number i+=1 # return the sum of limit number of primes return result # print to stdout the sum of the first 1000 prime numbers print (Prime(1000))
friend_name = "Eric" print("Hello, " + friend_name + ". It's good to see you again.") print(friend_name.upper()) print(friend_name.lower()) print(friend_name.title()) famous_person = "Caesar" quote = "'E tu, Brutus.'" print(famous_person + " once said, " + quote) whitespace_name = " Diana Arruda " print(whitespace_name.lstrip()) print(whitespace_name.rstrip()) print(whitespace_name.strip())
users = ['admin', 'diana', 'jeff', 'molly'] if users == []: print("We need to find some users!") else: for user in users: if user == 'admin': print("Hello admin, would you like to see a status report?") else: print("Welcome, " + user.title() + ".") current_users = ['diana', 'jeff', 'Molly', 'phi', 'sigma'] new_users= ['phi', 'Sigma', 'clover', 'k', 'dio'] for user in new_users: if user.lower() in current_users: print("Sorry, that username is taken! Try a new username.") else: print(user.title() + ", that username is available!") numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9] for number in numbers: if number == 1: print(str(number) + "st") elif number == 2: print(str(number) + "nd") elif number == 3: print(str(number) + "rd") elif number == 4: print(str(number) + "th") elif number == 5: print(str(number) + "th") elif number == 6: print(str(number) + "th") elif number == 7: print(str(number) + "th") elif number == 8: print(str(number) + "th") elif number == 9: print(str(number) + "th")
''' Dane są trzy zbiory: A, B i C. Napisz algorytm, który powie, czy istnieje taka trójka a, b, c z odpowiednio A, B, i C, że a + b = c. Nie wolno korzystać ze słowników! ''' # ALGORYTM : ''' Sortujemy A i B, i dla każdego elementu C, przeprowadzamy szukanie idąc dwoma wskaźnikami: jednym z początku A, drugim z końca B. w zależności od tego, czy suma elementów wskazywanych przez wskaźniki w A i B jest większa lub mniejsza niż element z C, to przesuwamy odpowiedni wskaźnik. Jak natrafimy na równą sumę, to kończymy. Inne podejście polega na posortowaniu C i dla każdej pary z A i B szukamy sumy binarnie. Złożoności (dla wielkości tablic odpowiednio a, b i c) : -pierwsze podejście: O(alog(a) + blog(b) + c(a+b)) -drugie podejście: O(clog(c) + a*b*log(c)) = O(log(c) * (a*b + c)) ''' # podejście 1 def equal_1(A,B,C): A=sorted(A) B=sorted(B) for num in C: a=0 b=len(B)-1 while(a<len(A) and b>=0): if A[a]+B[b]<num : a+=1 elif A[a]+B[b]>num : b-=1 else: print(A[a],"+",B[b],"=",num) return True return False # podejście 2 def binSearch(tab,val): p=0 k=len(tab)-1 while(p<=k): s=(p+k)//2 if(tab[s]==val): return True elif(tab[s]>val): k=s-1 else: p=s+1 return False def equal_2(A,B,C): C=sorted(C) for a in A: for b in B: if binSearch(C,a+b): print(a,"+",b) return True return False
''' Dany jest graf nieskierowany G oraz dwa jego wierzchołki s i t. Proszę zaproponować algorytm, który sprawdza czy istnieje taka krawędź, po usunięciu której długość najkrótszej ścieżki z s do t (lub taka ścieżka przestaje istnieć). ''' # ALGORYTM: ''' Obliczamy ilość najkrótszych ścieżek między s i t przy użyciu BFSa. Budujemy graf najkrótszych ścieżek i jeżeli jest w nim jakiś most, to znaczy, że istnieje psująca ścieżka. ''' from collections import deque class graph: def __init__(self,size): self.m=[[0]*size for i in range(size)] # macierz sasiedztwa self.size=size def add_edge(self,v,u): self.m[v][u]=1 self.m[u][v]=1 def printG(self): for row in self.m: print(row) def BFS(g,s,t): # przekazujemy startowy wiercholek q=deque() number=len(g.m) # tworzymy pomocnicza tablice czy odwiedzony visited=[False]*number # tablica na rodzicow parents=[[None]for _ in range(number)] # tablica na najkrotsza sciezke od s do v dist=[0]*number # tablica na liczbę ścieżek z s do v paths=[0]*number paths[s]=1 q.appendleft(s) visited[s]=True while(len(q)!=0): u=q.pop() #przegladamy wszystkie wierzcholki polaczone z u for i in range(number): if len(q)==0 : q=deque() # jezeli istnieje nieodwiedzona krawedz if g.m[u][i]==1 : # jeśli nieodwiedzony, to tyle samo ścieżek ile ten, z którego przyszliśmy if visited[i]==False : parents[i]=[u] visited[i]=True dist[i]=dist[u]+1 paths[i]=paths[u] q.appendleft(i) # jeśli odwiedzony, to sprawdzamy czy ścieżka z aktualnego wierzchołka jest tej samej # długości co dotychczas najkrótsza, jeśli tak to zwiększamy liczbę ścieżek o ścieżki do aktualnego else: if dist[i] == dist[u]+1: paths[i] += paths[u] parents[i].append(u) # zwracamy ilość najkrótszych ścieżek do t i ich długość return parents,dist[t],paths[t] time=0 def find_bridge(g): visited=[False]*g.size parents=[None]*g.size entry=[None]*g.size low=[None]*g.size def DFSvisit(u): global time time+=1 entry[u]=time low[u]=time visited[u]=True for i in range(1,len(g.arr[u])) : ngh=g.arr[u][i] if not visited[ngh] : parents[ngh]=u visited[ngh]=True DFSvisit(ngh) # przy powrocie rekurencji (gdy już odwiedzimy wszystkie # dzieci) sprawdzamy czy niżej była jakaś krawędź wsteczna low[u]=min(low[u],low[ngh]) elif visited[ngh] and parents[u] != ngh : # krawędź wsteczna do ngh, który już został odwiedzony low[u]=min(low[u],entry[ngh]) for v in range(g.size): if not visited[g.arr[v][0]] : DFSvisit(g.arr[v][0]) bridges=[] for i in range(g.size) : if entry[i] == low[i] and parents[i] is not None: # mamy most bridges.append((parents[i],i)) #print("b",bridges) return len(bridges) >= 1 class Graph: def __init__(self,size): self.size=size self.arr=[[i] for i in range(size)] def add_edge(self,v,u): self.arr[v].append(u) def printG(self): print("\n") for i in self.arr: for j in i: print(j,end=" ") print("\n") # zamiana sposobu reprezentacji grafu z macierzy na listy def matrix_to_lists(g): new=Graph(g.size) for i in range(g.size): for j in range(g.size): if i<j and g.m[i][j] != 0: new.add_edge(i,j) new.add_edge(j,i) return new def path_spoilage(g,s,t): parents,dist,paths=BFS(g,s,t) # tablica parentów, długość ścieżki, liczba ścieżek new_graph=graph(g.size) idx=0 # którego z parentów biorę while idx < paths: current=t # aktualny wierzchołek for _ in range(dist): # jeśli mamy na tyle parentów, to bierzemy # ten o indeksie idx, jeśli nie, to ostatniego if idx < len(parents[current]): prev=parents[current][idx] else: prev=parents[current][-1] new_graph.add_edge(current,prev) current=prev idx += 1 new_g=matrix_to_lists(new_graph) new_g.printG() # jeżeli w grafie najkrótszych ścieżek jest jakikolwiek most, to zwracamy True return find_bridge(new_g)
''' Podaj algorytm, który mając na wejściu niezrównoważone drzewo BST przekształca je w drzewa dające się pokolorować jako czerwono-czarne. ''' # ALGORYTM ''' rekurencyjnie wpisujemy do tablicy wartości inorder O(n), następnie z posortowanej tablicy łatwo możemy zrobić zbalansowane drzewo, biorąc jako roota medianę. Drzewo, które otrzymamy jest idealnie zrównoważone, dzięki temu na pewno jest czerwono-czarne. ''' class Node: def __init__(self,key,value): self.key=key self.value=value self.parent=None self.left=None self.right=None def insert(root,key,value): prev=None while root is not None : if key > root.key : prev=root root=root.right else: prev=root root=root.left if key < prev.key : prev.left=Node(key,value) prev.left.parent=prev else: prev.right=Node(key,value) prev.right.parent=prev def func(root): arr=[] # dostajemy klucze z drzewa (niezbalansowanego) w porządku posortowanym def inorder_to_array(root,arr): if root is not None: inorder_to_array(root.left,arr) arr.append(root.key) inorder_to_array(root.right,arr) return arr array=inorder_to_array(root,arr) print(array) # za każdym razem jako roota danego poddrzewa wybieramy środkową wartość z tablicy def build_balanced_tree(arr): if not arr: return middle=len(arr)//2 root=Node(arr[middle],1) root.left=build_balanced_tree(arr[:middle]) root.right=build_balanced_tree(arr[middle+1:]) return root return build_balanced_tree(array)
'''Mamy daną tablicę stringów, gdzie suma długości wszystkich stringów daje n. Napisz algorytm, który posortuje tę tablicę w czasie O(n).(Najpierw po dlugosciach, potem leksykograficznie) Można założyć, że stringi składają się wyłącznie z małych liter alfabetu łacińskiego.''' #z elementow tablicy robie krotki (dlugosc elementu,wartosc) def makeTuples(arr): for i in range(len(arr)): arr[i]=(len(arr[i]),arr[i]) return arr #sortowanie stringow: #ord() – funkcja ord() zwraca liczbę przypisaną do znaku w ASCII #sortuje wzgledem i-tej pozycji def countingSort(arr,i): letters=ord('z')-ord('a')+1 #ilosc liter od a do z wlacznie count=[0]*letters output=[0]*len(arr) for string in arr: #kazdy string po kolei count[ord(string[i])-ord('a')]+=1 # zerowy el. tablicy count to 'a' itd, wiec i-ta litera stringa ma indeks ord()=ord('a') for j in range(1,len(count)): # tworze cumulative sum count[j]+=count[j-1] for p in range(len(arr)-1,-1,-1): # p to indeksy tablicy wejsciowej arr (od konca) count[ord(arr[p][i])-ord('a')]-=1 output[count[ord(arr[p][i])-ord('a')]]=arr[p] for i in range(len(arr)): arr[i]=output[i] def radixSort(bucket): #sortuje stringi jednakowej dlugosci bedace w bucketach for i in range(len(bucket[0])-1,-1,-1): countingSort(bucket,i) #najpierw bucket sort po dlugosciach stringow def bucketSort(arr): Max=0 #max dlugosc stringa for i in range(len(arr)): if arr[i][0]>Max: Max=arr[i][0] #robimy Max+1 bucketow, w kazdym stringi jednakowej dlugosci buckets=[[] for i in range(Max+1)] for i in range(len(arr)): buckets[arr[i][0]].append(arr[i][1]) ctr=0 for bucket in buckets: print(ctr," ",bucket) ctr+=1 if len(bucket)!=0: radixSort(bucket) output=[] for bucket in buckets: output.extend(bucket) return output
'''Masz daną tablicę zawierającą n (n >= 11) liczb naturalnych w zakresie [0, k]. Zamieniono 10 liczb z tej tablicy na losowe liczby spoza tego zakresu (np. dużo większe lub ujemne). Napisz algorytm, który posortuje tablicę w czasie O(n).''' ''' Dzielimy tablicę na dwie - te "psujące" 10 elementów i te posortowane (pamiętamy o tym, żeby nie zmienić kolejności!). Sortujemy tę 10-elementową tablicę (czymkolwiek, bo to czas stały) i je scalamy w czasie O(n). ''' def sort(arr,k): #przekazuje zakres [0,k] #10 elementow jest spoza zakresu, reszta w [0,k] , dziele wiec na dwie tablice normal=[] out_of_range=[] for i in range(len(arr)): if arr[i]>=0 and arr[i]<=k : normal.append(arr[i]) else: out_of_range.append(arr[i]) print(normal) # te 10 el sortuje obojetnie jak: out_of_range=sorted(out_of_range) print(out_of_range) def merge(normal,out_of_range): #laczenie posortowanych tablicy w 0(n), ale wymaga dodatkowej pamieci output=[0]*(len(normal)+len(out_of_range)) idx=0 # tam wstawiamy idx_n=0 # w normal idx_o=0 # w out_of_range while(idx_n<len(normal) and idx_o<len(out_of_range)): if normal[idx_n] <= out_of_range[idx_o] : output[idx]=normal[idx_n] idx_n+=1 idx+=1 else: output[idx]=out_of_range[idx_o] idx_o+=1 idx+=1 #dopelniamy pozostale while idx_n<len(normal) : output[idx]=normal[idx_n] idx+=1 idx_n+=1 while idx_o<len(out_of_range): output[idx]=out_of_range[idx_o] idx+=1 idx_o+=1 return output a=merge(normal,out_of_range) return a arr=[2,12,2,88,40,6,34,6,6,7,45,8,9] a=sort(arr,9) # [0,9], zmienione 5 wartosci print(a)
''' implementacja kolejki priorytetowej min jako kopiec ''' # w 0 komorce przechowuje rozmiar kopca def size(k): return k[0] # przy heapify zakladam ze drzewa zaczepione w synach sa naprawione, tylko el. i moze byc mniejszy, # chce sprawic y ta wartosc splynela w dol i wszystko od i w dol bylo posortowane # naprawia kopiec, O(logn) def heapify(k,i): left = 2 * i right = 2 * i + 1 Min = i if left <= size(k) and k[left] < k[Min] : Min=left if right <= size(k) and k[right] < k[Min] : Min=right # Min to najmniejszy ze sprawdzanej trojki if Min != i : # jezeli kolejnosc jest zla k[i],k[Min] = k[Min],k[i] heapify(k,Min) # wywoluje to samo dla zmienianego elementu i sprawdzam jego dzieci def buildHeap(k): # O(n) for i in range(size(k)//2, 0, -1): # bo zaczynam od rodzica ostatniego dziecka(o indeksie i) heapify(k,i) # dostaje odpowiedni kopiec min return k # funkcja getmin zwraca najmniejszy element kopca min i naprawia go def getmin(k): # O(logn) res=k[1] k[1]=k[size(k)] k[0]=k[0]-1 #rozmiar zmniejszam o 1 heapify(k,1) return res # wstawia element o wartosci x do kopca i naprawia go def insert(k,x): # O(logn) # powiekszam kopiec o 1 k[0]+=1 k[size(k)]=x i=size(k) # musze teraz sprawdzic czy nowy element nie zaburza kopca, jesli tak, to zamieniam z rodzicem while i > 1 and k[i] < k[i//2] : # gdzie i//2 to rodzic i-tego elementu k[i], k[i//2] = k[i//2], k[i] i = i // 2 # przykładowe użycie arr = [None]*10 arr[0] = 0 buildHeap(arr) insert(arr,1) insert(arr,5) insert(arr,6) insert(arr,10) insert(arr,-2) print(arr) print(getmin(arr))
''' Zaimplementuj funkcję average_score(arr, n, lowest, highest). Funkcja ta przyjmuje na wejściu tablicę n liczb rzeczywistych (ich rozkład nie jest znany, ale wszystkie są parami różne) i zwraca średnią wartość podanych liczb po odrzuceniu lowest najmniejszych oraz highest największych. Zaimplementowana funkcja powinna być możliwie jak najszybsza. Oszacuj jej złożoność czasową (oraz bardzo krótko uzasadnić to oszacowanie). ''' ''' złożoność: O(n) Z użyciem algorytmu median of medians szybko dowiemy się, jakie elementy są brzegowe Musimy 2 razy wywołać tę funkcję i przejść liniowo bo tablicy ''' from random import randint # wyszukiwanie i-tego co do kolejnosci elementu (w szczegolnosci mediany) O(n) def med_of_med(arr,i): # lista list 5 elementowych, zawierajaca kolejne elementy wejsciowej tablicy lists=[arr[j:j+5] for j in range(0,len(arr),5)] # tworze liste zawierajaca mediane kazdej z 5-el. list medians=[sorted(List)[len(List)//2] for List in lists] #szukam pivota mediany median w zaleznosci jak dluga jest lista 'medians' if len(medians) <= 5 : pivot=sorted(medians)[len(medians)//2] else: # rekurencyjnie szukam mediany listy 'medians' pivot=med_of_med(medians,len(medians)//2) #podzial na mniejsze i wieksze elementy od pivota low=[i for i in arr if i<pivot] high=[i for i in arr if i>pivot] x=len(low) #element x-ty (o indeksie x-1) to pivot, na lewo sa mniejsze, na prawo wieksze, wiec spr po ktore stronie lezy szukany i-ty element if i<x : return med_of_med(low,i) # na lewo mamy x-1 elementow elif i>x: return med_of_med(high, i-x-1) # na prawo mamy x-k elementow else: return pivot def average_score(arr, n, lowest, highest) : # szukam liczby ktora po posortowaniu tablicy bedzie na pozycji lowest - elementy na lewo od niej odrzucamy, # a takze liczby na pozycji len(arr)-1-highest (elementy na prawo od tego indeksu odrzucamy) low=med_of_med(arr,lowest) high=med_of_med(arr,len(arr)-1-highest) print(low,high) sum=0 for el in arr: if el >= low and el <= high : sum+=el number=len(arr)-lowest-highest # ilosc liczb, ktore bierzemy pod uwage average=sum/number return average
''' Operacja intersection otrzymuje na wejściu dwa zbiory zrealizowane jako tablice asocjacyjne i zwraca ich liczbę elementów, które występują w obu. Proszę zaimplementować tę operację dla tablic asocjacyjnych realizowanych jako: 1. drzewa BST ''' # ALGORYTM: ''' Przechodzimy in-order oba drzewa, dostajemy 2 posortowane tablice, następnie liczymy powtarzające się elementy. ''' class Node: def __init__(self,key,value): self.key=key self.value=value self.parent=None self.left=None self.right=None def insert(root,key,value): prev=None while root is not None : if key > root.key : prev=root root=root.right else: prev=root root=root.left if key < prev.key : prev.left=Node(key,value) prev.left.parent=prev else: prev.right=Node(key,value) prev.right.parent=prev def inorder(root,arr): if root is not None: inorder(root.left,arr) arr.append(root.key) inorder(root.right,arr) def intersection(root1,root2): arr1=[] arr2=[] inorder(root1,arr1) inorder(root2,arr2) print(arr1) print(arr2) # szukamy części wspólnych obu tablic i=j=0 common=0 # liczba wspólnych elementów while(i<len(arr1) and j<len(arr2)): if arr1[i]==arr2[j]: common+=1 i+=1 j+=1 elif arr1[i]<arr2[j]: i+=1 else: j+=1 return common
''' Rozważmy drzewa BST, które dodatkowo w każdym węźle zawierają pole z liczbą węzłów w danym poddrzewie. Proszę opisać jak w takim drzewie wykonywaćnastępujące operacje: 1. znalezienie i-go co do wielkości elementu, 2. wyznaczenie, którym co do wielkości w drzewie jest zadany węzeł ''' class Node: def __init__(self,key,value): self.key=key self.value=value self.parent=None self.left=None self.right=None self.right_size=0 self.left_size=0 # przy wstawianiu aktualizuję rozmiar prawego i lewego poddrzewa def insert(root,key,value): prev=None while root is not None : if key > root.key : root.right_size+=1 prev=root root=root.right else: root.left_size+=1 prev=root root=root.left if key < prev.key : prev.left=Node(key,value) prev.left.parent=prev else: prev.right=Node(key,value) prev.right.parent=prev def find(root,key): while root is not None : if root.key==key : return root elif key > root.key : root=root.right else: root=root.left return None ##################################################################################################### ##################################################################################################### # k-ty element def find_kth(root,k): while(root is not None): if k == root.left_size+1 : return root elif k <= root.left_size: # szukamy w lewym poddrzewie root=root.left else: # szukamy w prawym poddrzewie k-=root.left_size+1 root=root.right return None # który co do wielkości def get_index(root,key): node=find(root,key) idx=1 # wszystko co w lewym poddrzewie, jest mniejsze idx+=node.left_size # jeśli jestem lewym synem, to idę dalej, a jeśli prawym to dodaję rozmiar lewego rodzica+1 while(node.parent is not None): if node.parent.right is not None and node.parent.right.key==node.key: idx += node.parent.left_size+1 node=node.parent return idx
# -*- coding: utf-8 -*- """ Started 07/11/2018 This script connects to the Department of Business, Environment, and Industrial Strategy (DBEIS) website, downloads the carbon factors in the 'flat file' format, and saves the factors in a SQLite3 file. If the 'flat file' format is not available, the script looks for the advanced file which contains all the data required. Carbon factors publishing started in 2002, and the year can be changed in the URL for the 2018 factors to get the appropiate year. The SQLite database has separate tables for each year, and the columns are defined in the sqlDumpFlatFile function @author: adam.rees """ import requests import sqlite3 import xlrd import sys import time import os import logging from bs4 import BeautifulSoup import wget try: now = time.strftime("%c") Now = time.localtime() logging.basicConfig(filename=os.path.join("DBEISCFLog.log"), level=logging.INFO) logging.info(f'\nDate and Time:\n {now}' '\n-------------------------------\n') except Exception as e: # pragma: no cover logging.critical("Error with the set-up of the logging function" "Sys.exit(1), try/except block line 30-40\n" f"Error: {e}\n") sys.exit(1) class CarbonFactors(object): """ This class which will contain the year, url, and carbon factors Each instance of the class will have its own table within the SQLite database """ def __init__(self,year): #Provide the year and return a class instance #Set up the variables here try: int(year) if 2014 <= year <= Now[0]+1: pass else: raise ValueError("Input string was not a valid year") except ValueError: raise ValueError("Input string was not a valid number") self.year = year self.pageurl = (f"https://www.gov.uk/government/publications/" f"greenhouse-gas-reporting-conversion-factors-{year}") self.downloadLink = "None" self.fileType = "" self.DownloadInfo = "" #Now we check if the URL exists, currently we print the result" self.UrlCheckResponse = self.urlCheck(self.pageurl) if self.UrlCheckResponse == True: if sys.platform == "win32": # pragma: no cover import winshell logging.debug("I am working on a Windows machine!\n") self.downloadDir = os.path.join(winshell.personal_folder(), "CF Downloads") else: logging.debug("I am working on a Linux based system" f"(Sys.platform = {sys.platform})\n") self.downloadDir = os.path.expanduser('~/CF Downloads') self.DownloadLocation = os.path.join(self.downloadDir, f'{self.year} - ' 'Carbon Factors.xls') self.database = os.path.join(self.downloadDir,'Database.db') #Lets Fetch the CarbonFactor URL now with the FetchCF function self.FetchCFLink() self.downloadFile() self.sqlCreateTable(self.database) try: self.sqlDumpFlatFile(self.database) except Exception as e: # pragma: no cover print("Exception raised" f"\nThrown Error: {e}\n") else: print(f"No Download found for {self.year}\n") logging.critical(f"No Download found for {self.year}\n") return #Create a log entry for the class instance logging.info("Instance of class created:\n" f"Year: {self.year}\n" f"Downloads Page URL: {self.pageurl}\n" f"URL Check Result: {self.UrlCheckResponse}\n" f"Factors Download Link: {self.downloadLink}\n" "Created table within database with name: " f"{self.tableName}\n" f"Year: {self.year} has been downloaded and assimilated " "into the database\n") def urlCheck(self, pageurl): #This function retrives the head of the url and checks the status code request = requests.head(pageurl) if request.status_code == 200: return True else: return False def FetchCFLink(self): """ This function provides a downloads webpage from where the carbon factors can be downloaded and returns self.downloadLink """ request = requests.get(self.pageurl) soup = BeautifulSoup(request.text,"lxml") URLPrepend = 'https://www.gov.uk' linkList = [] links = soup.select("a[href*=uploads]") for link in links: linkList.append(link.get('href')) try: self.DownloadInfo = self.linkTypeFunc(linkList) self.downloadLink = ''.join([self.DownloadInfo]) except Exception as e: logging.critical(f"\nError: {e}\n") self.downloadLink = "https://theuselessweb.com/" def linkTypeFunc(self,listLinks): """ This subfunction is called from the FetchCF function and accepts a list of urls from the webpage. The function will then look for a flat file first, then an advanced file, and finally an old style advanced file. This subfunction returns the downloadLink and fileType variable to the FetchCF function. """ substringFlatFile = "Flat" substringFlatFile2 = "flat" for entry in listLinks: if (entry.find(substringFlatFile) != -1 or entry.find(substringFlatFile2) != -1): Flatfile = entry return Flatfile def downloadFile(self): ''' This function takes the download link generated in the FetchCF function and attempts to download the file to the path indicated in the DownloadLocation variable (which contains the name of the file linked to the year in question) ''' try: fo = open(self.DownloadLocation, 'r') fo.close() except FileNotFoundError: try: os.makedirs(self.downloadDir,exist_ok=True) wget.download(self.downloadLink,self.DownloadLocation) except Exception as e: # pragma: no cover print(f"ERROR WITH DOWNLOAD: {e}\n") def sqlCreateTable(self,database): ''' This function creates the sqlite table within the db, and nothing more ''' conn = sqlite3.connect(database) c = conn.cursor() Year = str(self.year) self.tableName = f"Year_{Year}" try: table_sql = f"""CREATE TABLE {self.tableName} ( id integer PRIMARY KEY, Scope text NOT NULL, Level_1 text NOT NULL, Level_2 text NOT NULL, Level_3 text NOT NULL, Level_4 text NOT NULL, ColumnText text NOT NULL, UOM text NOT NULL, GHG text NOT NULL, GHG_Conversion_Factor real NOT NULL)""" c.execute(table_sql) conn.commit() conn.close() except sqlite3.Error as e: # pragma: no cover logging.debug("Error when creating table named: " f"{self.tableName}.\nError: {e}") def sqlDumpFlatFile(self,database): """ wb = Workbook ws = Worksheet d = Dictionary of values to be written to the SQL file (row by row) hd = Dictionary of heading row values conn = Connection to the SQLite object c = Cursor for the SQLite object """ wb = xlrd.open_workbook(self.DownloadLocation) ws = wb.sheet_by_name("Factors by Category") hd = {} conn = sqlite3.connect(database) c = conn.cursor() """ Lets set out the columns that we want with the variable headings 'hdX' """ hd1 = "Scope" hd2 = "Level 1" hd3 = "Level 2" hd4 = "Level 3" hd5 = "Level 4" hd6 = "Column Text" hd7 = "UOM" hd8 = "GHG" hd9 = "Factor" """ Lets clear the table before we write to it to avoid duplicate information """ try: c.execute(f"DELETE FROM {self.tableName}") logging.debug("Deleted table data") except Exception as e: # pragma: no cover logging.info("Deleting data threw an exception, continuing," " It propably means that the database hasn't been" f" created yet. Error: {e}") pass """ Now lets scan the excel file for our data and write it to the sqlite database """ HeaderRow = 0 for row in range(0,10): for col in range(0,ws.ncols): if ws.cell(row,col).value == "Scope": HeaderRow = row ValuesRow = HeaderRow + 1 for col in range(0,ws.ncols): if ws.cell(HeaderRow,col).value == hd1: hd['hd1'] = col if ws.cell(HeaderRow,col).value.find(hd2) != -1: hd['hd2'] = col if ws.cell(HeaderRow,col).value.find(hd3) != -1: hd['hd3'] = col if ws.cell(HeaderRow,col).value.find(hd4) != -1: hd['hd4'] = col if ws.cell(HeaderRow,col).value.find(hd5) != -1: hd['hd5'] = col if ws.cell(HeaderRow,col).value.find(hd6) != -1: hd['hd6'] = col if ws.cell(HeaderRow,col).value == hd7: hd['hd7'] = col if ws.cell(HeaderRow,col).value == hd8: hd['hd8'] = col if ws.cell(HeaderRow,col).value.find(hd9) != -1: hd['hd9'] = col else: pass try: for row in range(ValuesRow,ws.nrows): d = [] for dT,col in hd.items(): if ws.cell(row,col).value == "N/A": d.append(0) else: d.append(ws.cell(row,col).value) insert_sql = f"""INSERT INTO {self.tableName} (Scope, Level_1, Level_2, Level_3, Level_4, Columntext, UOM, GHG, GHG_Conversion_Factor) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)""" c.execute(insert_sql, d) conn.commit() conn.close() except Exception as e: # pragma: no cover conn.rollback() raise RuntimeError("An Error occured in the sqlDumpFlatFile " f"function. Error: {e}") """ Definition of the instances for testing From 2014 onwards we have flat files, and before that advanced... """ if __name__ == "__main__": # pragma: no cover start = time.time() count = 0 for i in range(2014,Now[0]+1): try: CarbonFactors(i) count = count + 1 except Exception as e: logging.debug(f"Error: {e}") pass end = time.time() print(f"Completed, I ran {count} operations. It took" f" {round(end-start,2)} seconds.")
# https://projecteuler.net/problem=2 # Each new term in the Fibonacci sequence is generated by adding # the previous two terms. By starting with 1 and 2, the first 10 # terms will be: # 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ... # By considering the terms in the Fibonacci sequence whose values # do not exceed four million, find the sum of the even-valued terms. def fib(numOfTerms): fib = 0 evensum = 0 i = 0 m = 1 n = 2 seq = [m,n] while fib < numOfTerms: if n % 2 == 0: evensum = evensum + n fib = m + n m = n n = fib seq.append(fib) i = i + 1 print evensum print seq # Solution #2 def fib2(numOfTerms): a, b = 1, 1 sequence = [a] for i in range(numOfTerms-1): a,b = b, a+b sequence.append(b) print sequence print sum(i for i in sequence if i % 2 == 0) #straight jacket, for mission critical code.
def is_acceptable_password(password): if len(password) > 6: return True else: return False def is_acceptable_password(password: str) -> bool: return len(password) > 6 is_acceptable_password = lambda password: len(password) > 6
from typing import List from functools import reduce import operator def solve (data: List[str], right: int, down: int) -> int: position = 0 row = 0 result = 0 width = len(data[0]) while True: try: if data[row][position] == '#': result += 1 row += down position = (position + right) % width except IndexError: return result def main() -> None: with open('input', 'r') as fh: data = [line.rstrip() for line in fh] print(f"Part one: {solve(data, 3, 1)}") modes = [(1,1), (3,1), (5,1), (7,1), (1,2)] solution = reduce(operator.mul, [solve(data, *mode) for mode in modes]) print(f'Part two: {solution}') if __name__ == '__main__': main()
#!/usr/bin/env python from datetime import datetime, timedelta class IntervalTimer(object): """ Timer which triggers each time the specified number of seconds has passed. """ def __init__(self, name, interval, startTriggered=False): self.__name = name self.__isTime = startTriggered self.__nextTime = None self.__interval = interval def isTime(self, now=None): "Return True if another interval has passed" if not self.__isTime: secsLeft = self.timeLeft(now) if secsLeft <= 0.0: self.__isTime = True return self.__isTime def reset(self): "Reset timer for the next interval" self.__nextTime = datetime.now() self.__isTime = False def timeLeft(self, now=None): if self.__isTime: return 0.0 if now is None: now = datetime.now() if self.__nextTime is None: self.__nextTime = now dt = now - self.__nextTime secs = dt.seconds + (dt.microseconds * 0.000001) return self.__interval - secs
prime_numbers = [] for i in range(1, 100): #if prime_numbers == []: # prime_numbers.append(i) count = 0 if i % i == 0: count += 1 for x in prime_numbers: if i % x == 0 : count += 1 if count <= 2 and i != 1: prime_numbers.append(i) print(f"Prime number list: {prime_numbers}")
from tkinter import * window = Tk() window.title("Mile to Km Converter") window.config(padx=50, pady=50) # window.minsize(width=300, height=100) def action(): x = float(entry.get()) y = x * 1.609 label_3.config(text=str(y)) button = Button(text="Calculate", command=action) button.grid(row=2, column=1) entry = Entry(width=10) entry.insert(END, string="0") entry.grid(row=0, column=1) label_1 = Label(text="Miles") label_1.grid(row=0, column=2) label_2 = Label(text="is equal to") label_2.grid(row=1, column=0) label_3 = Label(text="0") label_3.grid(row=1, column=1) label_4 = Label(text="Km") label_4.grid(row=1, column=2) window.mainloop()
# fiz buzz game game = [] for i in range(1,101): game.append(i) if i % 3 == 0 and i % 5 == 0: game[i-1] = "FizzBuzz" elif i % 3 == 0: game[i -1] ="Fizz" elif i % 5 == 0: game[i - 1] = "Buzz" print(game[i-1])
def sort012(a,arr_size): lo = 0 hi = arr_size - 1 mid = 0 while mid <= hi: if a[mid] == 0: a[lo], a[mid] = a[mid], a[lo] lo = lo + 1 mid = mid + 1 elif a[mid] == 1: mid = mid + 1 else: a[mid], a[hi] = a[hi], a[mid] hi = hi - 1 return a; def printArray(a): for k in a: print(k," ",end=""); arr = [int(x) for x in input().split()] arr_size = len(arr) arr = sort012(arr, arr_size) printArray(arr)
def countSetBits(n): count = 0 while (n): n &= (n - 1) count += 1 return count n = int(input()); print(countSetBits(n))
n=int(input()) n = list(str(n)) if n == sorted(n, reverse = True): print("Not possible") else: for i in range(len(n)-1, -1, -1): if(n[i-1] < n[i]): n[i:len(n)] = sorted(n[i:len(n)]) break for j in range(i, len(n)): if(n[i-1] < n[j]): n[i-1], n[j] = n[j], n[i-1] break print(int("".join(n)))
#safe to say, maður byrjar alltaf í 1,1. þannig það fyrsta sem hægt verður að gera er að fara norður, ekkert annað x = 1 y = 1 while True: if x == 1 and y == 1: print("You can travel: (N)orth.") elif x == 1 and y == 2: print("You can travel: (N)orth or (E)ast or (S)outh.") elif x == 2 and y == 2: print("You can travel: (S)outh or (W)est.") elif x == 2 and y == 1: print("You can travel: (N)orth.") elif x == 1 and y == 3: print("You can travel: (E)ast or (S)outh.") elif x == 2 and y == 3: print("You can travel: (E)ast or (W)est.") elif x == 3 and y == 3: print("You can travel: (S)outh or (W)est.") elif x == 3 and y == 2: print("You can travel: (N)orth or (S)outh.") elif x == 3 and y == 1: print("Victory!") break while True: d = input("Direction: ").lower() if d == "n": if y == 3 or (x == 2 and y == 2): print("Not a valid direction!") else: y += 1 break elif d == "e": #skoða allstaðar þar sem þu getur eki farið austur if (y == 1 or x == 3) or (x == 2 and y == 2): print("Not a valid direction!") else: x += 1 break elif d == "s": if y == 1 or (x == 2 and y == 3): print("Not a valid direction!") else: y -= 1 break elif d == "w": if (x == 1 or y == 1) or (x==3 and y==2): print("Not a valid direction!") else: x -= 1 break
# encoding: utf-8 # module System.Numerics calls itself Numerics # from System.Numerics.Vectors, Version=4.1.4.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a # by generator 1.145 # no doc # no imports # functions def Vector(*args, **kwargs): # real signature unknown """ Provides a collection of static convenience methods for creating, manipulating, combining, and converting generic vectors. """ pass # classes class Matrix3x2(object, IEquatable[Matrix3x2]): """ Represents a 3x2 matrix. Matrix3x2(m11: Single, m12: Single, m21: Single, m22: Single, m31: Single, m32: Single) """ @staticmethod def Add(value1, value2): """ Add(value1: Matrix3x2, value2: Matrix3x2) -> Matrix3x2 Adds each element in one matrix with its corresponding element in a second matrix. value1: The first matrix. value2: The second matrix. Returns: The matrix that contains the summed values of value1value1 and value2value2. """ pass @staticmethod def CreateRotation(radians, centerPoint=None): """ CreateRotation(radians: Single) -> Matrix3x2 Creates a rotation matrix using the given rotation in radians. radians: The amount of rotation, in radians. Returns: The rotation matrix. CreateRotation(radians: Single, centerPoint: Vector2) -> Matrix3x2 Creates a rotation matrix using the specified rotation in radians and a center point. radians: The amount of rotation, in radians. centerPoint: The center point. Returns: The rotation matrix. """ pass @staticmethod def CreateScale(*__args): """ CreateScale(xScale: Single, yScale: Single) -> Matrix3x2 Creates a scaling matrix from the specified X and Y components. xScale: The value to scale by on the X axis. yScale: The value to scale by on the Y axis. Returns: The scaling matrix. CreateScale(xScale: Single, yScale: Single, centerPoint: Vector2) -> Matrix3x2 Creates a scaling matrix that is offset by a given center point. xScale: The value to scale by on the X axis. yScale: The value to scale by on the Y axis. centerPoint: The center point. Returns: The scaling matrix. CreateScale(scales: Vector2) -> Matrix3x2 Creates a scaling matrix from the specified vector scale. scales: The scale to use. Returns: The scaling matrix. CreateScale(scales: Vector2, centerPoint: Vector2) -> Matrix3x2 Creates a scaling matrix from the specified vector scale with an offset from the specified center point. scales: The scale to use. centerPoint: The center offset. Returns: The scaling matrix. CreateScale(scale: Single) -> Matrix3x2 Creates a scaling matrix that scales uniformly with the given scale. scale: The uniform scale to use. Returns: The scaling matrix. CreateScale(scale: Single, centerPoint: Vector2) -> Matrix3x2 Creates a scaling matrix that scales uniformly with the specified scale with an offset from the specified center. scale: The uniform scale to use. centerPoint: The center offset. Returns: The scaling matrix. """ pass @staticmethod def CreateSkew(radiansX, radiansY, centerPoint=None): """ CreateSkew(radiansX: Single, radiansY: Single) -> Matrix3x2 Creates a skew matrix from the specified angles in radians. radiansX: The X angle, in radians. radiansY: The Y angle, in radians. Returns: The skew matrix. CreateSkew(radiansX: Single, radiansY: Single, centerPoint: Vector2) -> Matrix3x2 Creates a skew matrix from the specified angles in radians and a center point. radiansX: The X angle, in radians. radiansY: The Y angle, in radians. centerPoint: The center point. Returns: The skew matrix. """ pass @staticmethod def CreateTranslation(*__args): """ CreateTranslation(position: Vector2) -> Matrix3x2 Creates a translation matrix from the specified 2-dimensional vector. position: The translation position. Returns: The translation matrix. CreateTranslation(xPosition: Single, yPosition: Single) -> Matrix3x2 Creates a translation matrix from the specified X and Y components. xPosition: The X position. yPosition: The Y position. Returns: The translation matrix. """ pass def Equals(self, *__args): """ Equals(self: Matrix3x2, other: Matrix3x2) -> bool Returns a value that indicates whether this instance and another 3x2 matrix are equal. other: The other matrix. Returns: true if the two matrices are equal; otherwise, false. Equals(self: Matrix3x2, obj: object) -> bool Returns a value that indicates whether this instance and a specified object are equal. obj: The object to compare with the current instance. Returns: true if the current instance and objobj are equal; otherwise, false. If objobj is null, the method returns false. """ pass def GetDeterminant(self): """ GetDeterminant(self: Matrix3x2) -> Single Calculates the determinant for this matrix. Returns: The determinant. """ pass def GetHashCode(self): """ GetHashCode(self: Matrix3x2) -> int Returns the hash code for this instance. Returns: The hash code. """ pass @staticmethod def Invert(matrix, result): """ Invert(matrix: Matrix3x2) -> (bool, Matrix3x2) Inverts the specified matrix. The return value indicates whether the operation succeeded. matrix: The matrix to invert. Returns: true if matrixmatrix was converted successfully; otherwise, false. """ pass @staticmethod def Lerp(matrix1, matrix2, amount): """ Lerp(matrix1: Matrix3x2, matrix2: Matrix3x2, amount: Single) -> Matrix3x2 Performs a linear interpolation from one matrix to a second matrix based on a value that specifies the weighting of the second matrix. matrix1: The first matrix. matrix2: The second matrix. amount: The relative weighting of matrix2. Returns: The interpolated matrix. """ pass @staticmethod def Multiply(value1, value2): """ Multiply(value1: Matrix3x2, value2: Matrix3x2) -> Matrix3x2 Returns the matrix that results from multiplying two matrices together. value1: The first matrix. value2: The second matrix. Returns: The product matrix. Multiply(value1: Matrix3x2, value2: Single) -> Matrix3x2 Returns the matrix that results from scaling all the elements of a specified matrix by a scalar factor. value1: The matrix to scale. value2: The scaling value to use. Returns: The scaled matrix. """ pass @staticmethod def Negate(value): """ Negate(value: Matrix3x2) -> Matrix3x2 Negates the specified matrix by multiplying all its values by -1. value: The matrix to negate. Returns: The negated matrix. """ pass @staticmethod def Subtract(value1, value2): """ Subtract(value1: Matrix3x2, value2: Matrix3x2) -> Matrix3x2 Subtracts each element in a second matrix from its corresponding element in a first matrix. value1: The first matrix. value2: The second matrix. Returns: The matrix containing the values that result from subtracting each element in value2value2 from its corresponding element in value1value1. """ pass def ToString(self): """ ToString(self: Matrix3x2) -> str Returns a string that represents this matrix. Returns: The string representation of this matrix. """ pass def __add__(self, *args): #cannot find CLR method """ x.__add__(y) <==> x+y """ pass def __eq__(self, *args): #cannot find CLR method """ x.__eq__(y) <==> x==y """ pass def __init__(self, *args): #cannot find CLR method """ x.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signature """ pass def __mul__(self, *args): #cannot find CLR method """ x.__mul__(y) <==> x*yx.__mul__(y) <==> x*y """ pass def __neg__(self, *args): #cannot find CLR method """ x.__neg__() <==> -x """ pass @staticmethod # known case of __new__ def __new__(self, m11, m12, m21, m22, m31, m32): """ __new__(cls: type, m11: Single, m12: Single, m21: Single, m22: Single, m31: Single, m32: Single) __new__[Matrix3x2]() -> Matrix3x2 """ pass def __ne__(self, *args): #cannot find CLR method pass def __radd__(self, *args): #cannot find CLR method """ __radd__(value1: Matrix3x2, value2: Matrix3x2) -> Matrix3x2 Adds each element in one matrix with its corresponding element in a second matrix. value1: The first matrix. value2: The second matrix. Returns: The matrix that contains the summed values. """ pass def __repr__(self, *args): #cannot find CLR method """ __repr__(self: object) -> str """ pass def __rmul__(self, *args): #cannot find CLR method """ __rmul__(value1: Matrix3x2, value2: Matrix3x2) -> Matrix3x2 Returns the matrix that results from multiplying two matrices together. value1: The first matrix. value2: The second matrix. Returns: The product matrix. """ pass def __rsub__(self, *args): #cannot find CLR method """ __rsub__(value1: Matrix3x2, value2: Matrix3x2) -> Matrix3x2 Subtracts each element in a second matrix from its corresponding element in a first matrix. value1: The first matrix. value2: The second matrix. Returns: The matrix containing the values that result from subtracting each element in value2value2 from its corresponding element in value1value1. """ pass def __str__(self, *args): #cannot find CLR method pass def __sub__(self, *args): #cannot find CLR method """ x.__sub__(y) <==> x-y """ pass IsIdentity = property(lambda self: object(), lambda self, v: None, lambda self: None) # default """Indicates whether the current matrix is the identity matrix. Get: IsIdentity(self: Matrix3x2) -> bool """ Translation = property(lambda self: object(), lambda self, v: None, lambda self: None) # default """Gets or sets the translation component of this matrix. Get: Translation(self: Matrix3x2) -> Vector2 Set: Translation(self: Matrix3x2) = value """ Identity = None M11 = None M12 = None M21 = None M22 = None M31 = None M32 = None class Matrix4x4(object, IEquatable[Matrix4x4]): """ Represents a 4x4 matrix. Matrix4x4(m11: Single, m12: Single, m13: Single, m14: Single, m21: Single, m22: Single, m23: Single, m24: Single, m31: Single, m32: Single, m33: Single, m34: Single, m41: Single, m42: Single, m43: Single, m44: Single) Matrix4x4(value: Matrix3x2) """ @staticmethod def Add(value1, value2): """ Add(value1: Matrix4x4, value2: Matrix4x4) -> Matrix4x4 Adds each element in one matrix with its corresponding element in a second matrix. value1: The first matrix. value2: The second matrix. Returns: The matrix that contains the summed values of value1value1 and value2value2. """ pass @staticmethod def CreateBillboard(objectPosition, cameraPosition, cameraUpVector, cameraForwardVector): """ CreateBillboard(objectPosition: Vector3, cameraPosition: Vector3, cameraUpVector: Vector3, cameraForwardVector: Vector3) -> Matrix4x4 Creates a spherical billboard that rotates around a specified object position. objectPosition: The position of the object that the billboard will rotate around. cameraPosition: The position of the camera. cameraUpVector: The up vector of the camera. cameraForwardVector: The forward vector of the camera. Returns: The created billboard. """ pass @staticmethod def CreateConstrainedBillboard(objectPosition, cameraPosition, rotateAxis, cameraForwardVector, objectForwardVector): """ CreateConstrainedBillboard(objectPosition: Vector3, cameraPosition: Vector3, rotateAxis: Vector3, cameraForwardVector: Vector3, objectForwardVector: Vector3) -> Matrix4x4 Creates a cylindrical billboard that rotates around a specified axis. objectPosition: The position of the object that the billboard will rotate around. cameraPosition: The position of the camera. rotateAxis: The axis to rotate the billboard around. cameraForwardVector: The forward vector of the camera. objectForwardVector: The forward vector of the object. Returns: The billboard matrix. """ pass @staticmethod def CreateFromAxisAngle(axis, angle): """ CreateFromAxisAngle(axis: Vector3, angle: Single) -> Matrix4x4 Creates a matrix that rotates around an arbitrary vector. axis: The axis to rotate around. angle: The angle to rotate around axis, in radians. Returns: The rotation matrix. """ pass @staticmethod def CreateFromQuaternion(quaternion): """ CreateFromQuaternion(quaternion: Quaternion) -> Matrix4x4 Creates a rotation matrix from the specified Quaternion rotation value. quaternion: The source Quaternion. Returns: The rotation matrix. """ pass @staticmethod def CreateFromYawPitchRoll(yaw, pitch, roll): """ CreateFromYawPitchRoll(yaw: Single, pitch: Single, roll: Single) -> Matrix4x4 Creates a rotation matrix from the specified yaw, pitch, and roll. yaw: The angle of rotation, in radians, around the Y axis. pitch: The angle of rotation, in radians, around the X axis. roll: The angle of rotation, in radians, around the Z axis. Returns: The rotation matrix. """ pass @staticmethod def CreateLookAt(cameraPosition, cameraTarget, cameraUpVector): """ CreateLookAt(cameraPosition: Vector3, cameraTarget: Vector3, cameraUpVector: Vector3) -> Matrix4x4 Creates a view matrix. cameraPosition: The position of the camera. cameraTarget: The target towards which the camera is pointing. cameraUpVector: The direction that is &quot;up&quot; from the camera&#39;s point of view. Returns: The view matrix. """ pass @staticmethod def CreateOrthographic(width, height, zNearPlane, zFarPlane): """ CreateOrthographic(width: Single, height: Single, zNearPlane: Single, zFarPlane: Single) -> Matrix4x4 Creates an orthographic perspective matrix from the given view volume dimensions. width: The width of the view volume. height: The height of the view volume. zNearPlane: The minimum Z-value of the view volume. zFarPlane: The maximum Z-value of the view volume. Returns: The orthographic projection matrix. """ pass @staticmethod def CreateOrthographicOffCenter(left, right, bottom, top, zNearPlane, zFarPlane): """ CreateOrthographicOffCenter(left: Single, right: Single, bottom: Single, top: Single, zNearPlane: Single, zFarPlane: Single) -> Matrix4x4 Creates a customized orthographic projection matrix. left: The minimum X-value of the view volume. right: The maximum X-value of the view volume. bottom: The minimum Y-value of the view volume. top: The maximum Y-value of the view volume. zNearPlane: The minimum Z-value of the view volume. zFarPlane: The maximum Z-value of the view volume. Returns: The orthographic projection matrix. """ pass @staticmethod def CreatePerspective(width, height, nearPlaneDistance, farPlaneDistance): """ CreatePerspective(width: Single, height: Single, nearPlaneDistance: Single, farPlaneDistance: Single) -> Matrix4x4 Creates a perspective projection matrix from the given view volume dimensions. width: The width of the view volume at the near view plane. height: The height of the view volume at the near view plane. nearPlaneDistance: The distance to the near view plane. farPlaneDistance: The distance to the far view plane. Returns: The perspective projection matrix. """ pass @staticmethod def CreatePerspectiveFieldOfView(fieldOfView, aspectRatio, nearPlaneDistance, farPlaneDistance): """ CreatePerspectiveFieldOfView(fieldOfView: Single, aspectRatio: Single, nearPlaneDistance: Single, farPlaneDistance: Single) -> Matrix4x4 Creates a perspective projection matrix based on a field of view, aspect ratio, and near and far view plane distances. fieldOfView: The field of view in the y direction, in radians. aspectRatio: The aspect ratio, defined as view space width divided by height. nearPlaneDistance: The distance to the near view plane. farPlaneDistance: The distance to the far view plane. Returns: The perspective projection matrix. """ pass @staticmethod def CreatePerspectiveOffCenter(left, right, bottom, top, nearPlaneDistance, farPlaneDistance): """ CreatePerspectiveOffCenter(left: Single, right: Single, bottom: Single, top: Single, nearPlaneDistance: Single, farPlaneDistance: Single) -> Matrix4x4 Creates a customized perspective projection matrix. left: The minimum x-value of the view volume at the near view plane. right: The maximum x-value of the view volume at the near view plane. bottom: The minimum y-value of the view volume at the near view plane. top: The maximum y-value of the view volume at the near view plane. nearPlaneDistance: The distance to the near view plane. farPlaneDistance: The distance to the far view plane. Returns: The perspective projection matrix. """ pass @staticmethod def CreateReflection(value): """ CreateReflection(value: Plane) -> Matrix4x4 Creates a matrix that reflects the coordinate system about a specified plane. value: The plane about which to create a reflection. Returns: A new matrix expressing the reflection. """ pass @staticmethod def CreateRotationX(radians, centerPoint=None): """ CreateRotationX(radians: Single) -> Matrix4x4 Creates a matrix for rotating points around the X axis. radians: The amount, in radians, by which to rotate around the X axis. Returns: The rotation matrix. CreateRotationX(radians: Single, centerPoint: Vector3) -> Matrix4x4 Creates a matrix for rotating points around the X axis from a center point. radians: The amount, in radians, by which to rotate around the X axis. centerPoint: The center point. Returns: The rotation matrix. """ pass @staticmethod def CreateRotationY(radians, centerPoint=None): """ CreateRotationY(radians: Single) -> Matrix4x4 Creates a matrix for rotating points around the Y axis. radians: The amount, in radians, by which to rotate around the Y-axis. Returns: The rotation matrix. CreateRotationY(radians: Single, centerPoint: Vector3) -> Matrix4x4 The amount, in radians, by which to rotate around the Y axis from a center point. radians: The amount, in radians, by which to rotate around the Y-axis. centerPoint: The center point. Returns: The rotation matrix. """ pass @staticmethod def CreateRotationZ(radians, centerPoint=None): """ CreateRotationZ(radians: Single) -> Matrix4x4 Creates a matrix for rotating points around the Z axis. radians: The amount, in radians, by which to rotate around the Z-axis. Returns: The rotation matrix. CreateRotationZ(radians: Single, centerPoint: Vector3) -> Matrix4x4 Creates a matrix for rotating points around the Z axis from a center point. radians: The amount, in radians, by which to rotate around the Z-axis. centerPoint: The center point. Returns: The rotation matrix. """ pass @staticmethod def CreateScale(*__args): """ CreateScale(xScale: Single, yScale: Single, zScale: Single) -> Matrix4x4 Creates a scaling matrix from the specified X, Y, and Z components. xScale: The value to scale by on the X axis. yScale: The value to scale by on the Y axis. zScale: The value to scale by on the Z axis. Returns: The scaling matrix. CreateScale(xScale: Single, yScale: Single, zScale: Single, centerPoint: Vector3) -> Matrix4x4 Creates a scaling matrix that is offset by a given center point. xScale: The value to scale by on the X axis. yScale: The value to scale by on the Y axis. zScale: The value to scale by on the Z axis. centerPoint: The center point. Returns: The scaling matrix. CreateScale(scales: Vector3) -> Matrix4x4 Creates a scaling matrix from the specified vector scale. scales: The scale to use. Returns: The scaling matrix. CreateScale(scales: Vector3, centerPoint: Vector3) -> Matrix4x4 Creates a scaling matrix with a center point. scales: The vector that contains the amount to scale on each axis. centerPoint: The center point. Returns: The scaling matrix. CreateScale(scale: Single) -> Matrix4x4 Creates a uniform scaling matrix that scale equally on each axis. scale: The uniform scaling factor. Returns: The scaling matrix. CreateScale(scale: Single, centerPoint: Vector3) -> Matrix4x4 Creates a uniform scaling matrix that scales equally on each axis with a center point. scale: The uniform scaling factor. centerPoint: The center point. Returns: The scaling matrix. """ pass @staticmethod def CreateShadow(lightDirection, plane): """ CreateShadow(lightDirection: Vector3, plane: Plane) -> Matrix4x4 Creates a matrix that flattens geometry into a specified plane as if casting a shadow from a specified light source. lightDirection: The direction from which the light that will cast the shadow is coming. plane: The plane onto which the new matrix should flatten geometry so as to cast a shadow. Returns: A new matrix that can be used to flatten geometry onto the specified plane from the specified direction. """ pass @staticmethod def CreateTranslation(*__args): """ CreateTranslation(position: Vector3) -> Matrix4x4 Creates a translation matrix from the specified 3-dimensional vector. position: The amount to translate in each axis. Returns: The translation matrix. CreateTranslation(xPosition: Single, yPosition: Single, zPosition: Single) -> Matrix4x4 Creates a translation matrix from the specified X, Y, and Z components. xPosition: The amount to translate on the X axis. yPosition: The amount to translate on the Y axis. zPosition: The amount to translate on the Z axis. Returns: The translation matrix. """ pass @staticmethod def CreateWorld(position, forward, up): """ CreateWorld(position: Vector3, forward: Vector3, up: Vector3) -> Matrix4x4 Creates a world matrix with the specified parameters. position: The position of the object. forward: The forward direction of the object. up: The upward direction of the object. Its value is usually [0, 1, 0]. Returns: The world matrix. """ pass @staticmethod def Decompose(matrix, scale, rotation, translation): """ Decompose(matrix: Matrix4x4) -> (bool, Vector3, Quaternion, Vector3) Attempts to extract the scale, translation, and rotation components from the given scale, rotation, or translation matrix. The return value indicates whether the operation succeeded. matrix: The source matrix. Returns: true if matrixmatrix was decomposed successfully; otherwise, false. """ pass def Equals(self, *__args): """ Equals(self: Matrix4x4, other: Matrix4x4) -> bool Returns a value that indicates whether this instance and another 4x4 matrix are equal. other: The other matrix. Returns: true if the two matrices are equal; otherwise, false. Equals(self: Matrix4x4, obj: object) -> bool Returns a value that indicates whether this instance and a specified object are equal. obj: The object to compare with the current instance. Returns: true if the current instance and objobj are equal; otherwise, false. If objobj is null, the method returns false. """ pass def GetDeterminant(self): """ GetDeterminant(self: Matrix4x4) -> Single Calculates the determinant of the current 4x4 matrix. Returns: The determinant. """ pass def GetHashCode(self): """ GetHashCode(self: Matrix4x4) -> int Returns the hash code for this instance. Returns: The hash code. """ pass @staticmethod def Invert(matrix, result): """ Invert(matrix: Matrix4x4) -> (bool, Matrix4x4) Inverts the specified matrix. The return value indicates whether the operation succeeded. matrix: The matrix to invert. Returns: true if matrixmatrix was converted successfully; otherwise, false. """ pass @staticmethod def Lerp(matrix1, matrix2, amount): """ Lerp(matrix1: Matrix4x4, matrix2: Matrix4x4, amount: Single) -> Matrix4x4 Performs a linear interpolation from one matrix to a second matrix based on a value that specifies the weighting of the second matrix. matrix1: The first matrix. matrix2: The second matrix. amount: The relative weighting of matrix2. Returns: The interpolated matrix. """ pass @staticmethod def Multiply(value1, value2): """ Multiply(value1: Matrix4x4, value2: Matrix4x4) -> Matrix4x4 Returns the matrix that results from multiplying two matrices together. value1: The first matrix. value2: The second matrix. Returns: The product matrix. Multiply(value1: Matrix4x4, value2: Single) -> Matrix4x4 Returns the matrix that results from scaling all the elements of a specified matrix by a scalar factor. value1: The matrix to scale. value2: The scaling value to use. Returns: The scaled matrix. """ pass @staticmethod def Negate(value): """ Negate(value: Matrix4x4) -> Matrix4x4 Negates the specified matrix by multiplying all its values by -1. value: The matrix to negate. Returns: The negated matrix. """ pass @staticmethod def Subtract(value1, value2): """ Subtract(value1: Matrix4x4, value2: Matrix4x4) -> Matrix4x4 Subtracts each element in a second matrix from its corresponding element in a first matrix. value1: The first matrix. value2: The second matrix. Returns: The matrix containing the values that result from subtracting each element in value2value2 from its corresponding element in value1value1. """ pass def ToString(self): """ ToString(self: Matrix4x4) -> str Returns a string that represents this matrix. Returns: The string representation of this matrix. """ pass @staticmethod def Transform(value, rotation): """ Transform(value: Matrix4x4, rotation: Quaternion) -> Matrix4x4 Transforms the specified matrix by applying the specified Quaternion rotation. value: The matrix to transform. rotation: The rotation t apply. Returns: The transformed matrix. """ pass @staticmethod def Transpose(matrix): """ Transpose(matrix: Matrix4x4) -> Matrix4x4 Transposes the rows and columns of a matrix. matrix: The matrix to transpose. Returns: The transposed matrix. """ pass def __add__(self, *args): #cannot find CLR method """ x.__add__(y) <==> x+y """ pass def __eq__(self, *args): #cannot find CLR method """ x.__eq__(y) <==> x==y """ pass def __init__(self, *args): #cannot find CLR method """ x.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signature """ pass def __mul__(self, *args): #cannot find CLR method """ x.__mul__(y) <==> x*yx.__mul__(y) <==> x*y """ pass def __neg__(self, *args): #cannot find CLR method """ x.__neg__() <==> -x """ pass @staticmethod # known case of __new__ def __new__(self, *__args): """ __new__(cls: type, m11: Single, m12: Single, m13: Single, m14: Single, m21: Single, m22: Single, m23: Single, m24: Single, m31: Single, m32: Single, m33: Single, m34: Single, m41: Single, m42: Single, m43: Single, m44: Single) __new__(cls: type, value: Matrix3x2) __new__[Matrix4x4]() -> Matrix4x4 """ pass def __ne__(self, *args): #cannot find CLR method pass def __radd__(self, *args): #cannot find CLR method """ __radd__(value1: Matrix4x4, value2: Matrix4x4) -> Matrix4x4 Adds each element in one matrix with its corresponding element in a second matrix. value1: The first matrix. value2: The second matrix. Returns: The matrix that contains the summed values. """ pass def __repr__(self, *args): #cannot find CLR method """ __repr__(self: object) -> str """ pass def __rmul__(self, *args): #cannot find CLR method """ __rmul__(value1: Matrix4x4, value2: Matrix4x4) -> Matrix4x4 Returns the matrix that results from multiplying two matrices together. value1: The first matrix. value2: The second matrix. Returns: The product matrix. """ pass def __rsub__(self, *args): #cannot find CLR method """ __rsub__(value1: Matrix4x4, value2: Matrix4x4) -> Matrix4x4 Subtracts each element in a second matrix from its corresponding element in a first matrix. value1: The first matrix. value2: The second matrix. Returns: The matrix containing the values that result from subtracting each element in value2value2 from its corresponding element in value1value1. """ pass def __str__(self, *args): #cannot find CLR method pass def __sub__(self, *args): #cannot find CLR method """ x.__sub__(y) <==> x-y """ pass IsIdentity = property(lambda self: object(), lambda self, v: None, lambda self: None) # default """Indicates whether the current matrix is the identity matrix. Get: IsIdentity(self: Matrix4x4) -> bool """ Translation = property(lambda self: object(), lambda self, v: None, lambda self: None) # default """Gets or sets the translation component of this matrix. Get: Translation(self: Matrix4x4) -> Vector3 Set: Translation(self: Matrix4x4) = value """ Identity = None M11 = None M12 = None M13 = None M14 = None M21 = None M22 = None M23 = None M24 = None M31 = None M32 = None M33 = None M34 = None M41 = None M42 = None M43 = None M44 = None class Plane(object, IEquatable[Plane]): """ Represents a three-dimensional plane. Plane(x: Single, y: Single, z: Single, d: Single) Plane(normal: Vector3, d: Single) Plane(value: Vector4) """ @staticmethod def CreateFromVertices(point1, point2, point3): """ CreateFromVertices(point1: Vector3, point2: Vector3, point3: Vector3) -> Plane Creates a System.Numerics.Plane object that contains three specified points. point1: The first point defining the plane. point2: The second point defining the plane. point3: The third point defining the plane. Returns: The plane containing the three points. """ pass @staticmethod def Dot(plane, value): """ Dot(plane: Plane, value: Vector4) -> Single Calculates the dot product of a plane and a 4-dimensional vector. plane: The plane. value: The four-dimensional vector. Returns: The dot product. """ pass @staticmethod def DotCoordinate(plane, value): """ DotCoordinate(plane: Plane, value: Vector3) -> Single Returns the dot product of a specified three-dimensional vector and the normal vector of this plane plus the distance (System.Numerics.Plane.D) value of the plane. plane: The plane. value: The 3-dimensional vector. Returns: The dot product. """ pass @staticmethod def DotNormal(plane, value): """ DotNormal(plane: Plane, value: Vector3) -> Single Returns the dot product of a specified three-dimensional vector and the System.Numerics.Plane.Normal vector of this plane. plane: The plane. value: The three-dimensional vector. Returns: The dot product. """ pass def Equals(self, *__args): """ Equals(self: Plane, other: Plane) -> bool Returns a value that indicates whether this instance and another plane object are equal. other: The other plane. Returns: true if the two planes are equal; otherwise, false. Equals(self: Plane, obj: object) -> bool Returns a value that indicates whether this instance and a specified object are equal. obj: The object to compare with the current instance. Returns: true if the current instance and objobj are equal; otherwise, false. If objobj is null, the method returns false. """ pass def GetHashCode(self): """ GetHashCode(self: Plane) -> int Returns the hash code for this instance. Returns: The hash code. """ pass @staticmethod def Normalize(value): """ Normalize(value: Plane) -> Plane Creates a new System.Numerics.Plane object whose normal vector is the source plane&#39;s normal vector normalized. value: The source plane. Returns: The normalized plane. """ pass def ToString(self): """ ToString(self: Plane) -> str Returns the string representation of this plane object. Returns: A string that represents this stem.Numerics.Plane object. """ pass @staticmethod def Transform(plane, *__args): """ Transform(plane: Plane, matrix: Matrix4x4) -> Plane Transforms a normalized plane by a 4x4 matrix. plane: The normalized plane to transform. matrix: The transformation matrix to apply to plane. Returns: The transformed plane. Transform(plane: Plane, rotation: Quaternion) -> Plane Transforms a normalized plane by a Quaternion rotation. plane: The normalized plane to transform. rotation: The Quaternion rotation to apply to the plane. Returns: A new plane that results from applying the Quaternion rotation. """ pass def __eq__(self, *args): #cannot find CLR method """ x.__eq__(y) <==> x==y """ pass def __init__(self, *args): #cannot find CLR method """ x.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signature """ pass @staticmethod # known case of __new__ def __new__(self, *__args): """ __new__(cls: type, x: Single, y: Single, z: Single, d: Single) __new__(cls: type, normal: Vector3, d: Single) __new__(cls: type, value: Vector4) __new__[Plane]() -> Plane """ pass def __ne__(self, *args): #cannot find CLR method pass def __repr__(self, *args): #cannot find CLR method """ __repr__(self: object) -> str """ pass def __str__(self, *args): #cannot find CLR method pass D = None Normal = None class Quaternion(object, IEquatable[Quaternion]): """ Represents a vector that is used to encode three-dimensional physical rotations. Quaternion(x: Single, y: Single, z: Single, w: Single) Quaternion(vectorPart: Vector3, scalarPart: Single) """ @staticmethod def Add(value1, value2): """ Add(value1: Quaternion, value2: Quaternion) -> Quaternion Adds each element in one quaternion with its corresponding element in a second quaternion. value1: The first quaternion. value2: The second quaternion. Returns: The quaternion that contains the summed values of value1value1 and value2value2. """ pass @staticmethod def Concatenate(value1, value2): """ Concatenate(value1: Quaternion, value2: Quaternion) -> Quaternion Concatenates two quaternions. value1: The first quaternion rotation in the series. value2: The second quaternion rotation in the series. Returns: A new quaternion representing the concatenation of the value1value1 rotation followed by the value2value2 rotation. """ pass @staticmethod def Conjugate(value): """ Conjugate(value: Quaternion) -> Quaternion Returns the conjugate of a specified quaternion. value: The quaternion. Returns: A new quaternion that is the conjugate of value. """ pass @staticmethod def CreateFromAxisAngle(axis, angle): """ CreateFromAxisAngle(axis: Vector3, angle: Single) -> Quaternion Creates a quaternion from a vector and an angle to rotate about the vector. axis: The vector to rotate around. angle: The angle, in radians, to rotate around the vector. Returns: The newly created quaternion. """ pass @staticmethod def CreateFromRotationMatrix(matrix): """ CreateFromRotationMatrix(matrix: Matrix4x4) -> Quaternion Creates a quaternion from the specified rotation matrix. matrix: The rotation matrix. Returns: The newly created quaternion. """ pass @staticmethod def CreateFromYawPitchRoll(yaw, pitch, roll): """ CreateFromYawPitchRoll(yaw: Single, pitch: Single, roll: Single) -> Quaternion Creates a new quaternion from the given yaw, pitch, and roll. yaw: The yaw angle, in radians, around the Y axis. pitch: The pitch angle, in radians, around the X axis. roll: The roll angle, in radians, around the Z axis. Returns: The resulting quaternion. """ pass @staticmethod def Divide(value1, value2): """ Divide(value1: Quaternion, value2: Quaternion) -> Quaternion Divides one quaternion by a second quaternion. value1: The dividend. value2: The divisor. Returns: The quaternion that results from dividing value1value1 by value2value2. """ pass @staticmethod def Dot(quaternion1, quaternion2): """ Dot(quaternion1: Quaternion, quaternion2: Quaternion) -> Single Calculates the dot product of two quaternions. quaternion1: The first quaternion. quaternion2: The second quaternion. Returns: The dot product. """ pass def Equals(self, *__args): """ Equals(self: Quaternion, other: Quaternion) -> bool Returns a value that indicates whether this instance and another quaternion are equal. other: The other quaternion. Returns: true if the two quaternions are equal; otherwise, false. Equals(self: Quaternion, obj: object) -> bool Returns a value that indicates whether this instance and a specified object are equal. obj: The object to compare with the current instance. Returns: true if the current instance and objobj are equal; otherwise, false. If objobj is null, the method returns false. """ pass def GetHashCode(self): """ GetHashCode(self: Quaternion) -> int Returns the hash code for this instance. Returns: The hash code. """ pass @staticmethod def Inverse(value): """ Inverse(value: Quaternion) -> Quaternion Returns the inverse of a quaternion. value: The quaternion. Returns: The inverted quaternion. """ pass def Length(self): """ Length(self: Quaternion) -> Single Calculates the length of the quaternion. Returns: The computed length of the quaternion. """ pass def LengthSquared(self): """ LengthSquared(self: Quaternion) -> Single Calculates the squared length of the quaternion. Returns: The length squared of the quaternion. """ pass @staticmethod def Lerp(quaternion1, quaternion2, amount): """ Lerp(quaternion1: Quaternion, quaternion2: Quaternion, amount: Single) -> Quaternion Performs a linear interpolation between two quaternions based on a value that specifies the weighting of the second quaternion. quaternion1: The first quaternion. quaternion2: The second quaternion. amount: The relative weight of quaternion2 in the interpolation. Returns: The interpolated quaternion. """ pass @staticmethod def Multiply(value1, value2): """ Multiply(value1: Quaternion, value2: Quaternion) -> Quaternion Returns the quaternion that results from multiplying two quaternions together. value1: The first quaternion. value2: The second quaternion. Returns: The product quaternion. Multiply(value1: Quaternion, value2: Single) -> Quaternion Returns the quaternion that results from scaling all the components of a specified quaternion by a scalar factor. value1: The source quaternion. value2: The scalar value. Returns: The scaled quaternion. """ pass @staticmethod def Negate(value): """ Negate(value: Quaternion) -> Quaternion Reverses the sign of each component of the quaternion. value: The quaternion to negate. Returns: The negated quaternion. """ pass @staticmethod def Normalize(value): """ Normalize(value: Quaternion) -> Quaternion Divides each component of a specified System.Numerics.Quaternion by its length. value: The quaternion to normalize. Returns: The normalized quaternion. """ pass @staticmethod def Slerp(quaternion1, quaternion2, amount): """ Slerp(quaternion1: Quaternion, quaternion2: Quaternion, amount: Single) -> Quaternion Interpolates between two quaternions, using spherical linear interpolation. quaternion1: The first quaternion. quaternion2: The second quaternion. amount: The relative weight of the second quaternion in the interpolation. Returns: The interpolated quaternion. """ pass @staticmethod def Subtract(value1, value2): """ Subtract(value1: Quaternion, value2: Quaternion) -> Quaternion Subtracts each element in a second quaternion from its corresponding element in a first quaternion. value1: The first quaternion. value2: The second quaternion. Returns: The quaternion containing the values that result from subtracting each element in value2value2 from its corresponding element in value1value1. """ pass def ToString(self): """ ToString(self: Quaternion) -> str Returns a string that represents this quaternion. Returns: The string representation of this quaternion. """ pass def __add__(self, *args): #cannot find CLR method """ x.__add__(y) <==> x+y """ pass def __div__(self, *args): #cannot find CLR method """ x.__div__(y) <==> x/y """ pass def __eq__(self, *args): #cannot find CLR method """ x.__eq__(y) <==> x==y """ pass def __init__(self, *args): #cannot find CLR method """ x.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signature """ pass def __mul__(self, *args): #cannot find CLR method """ x.__mul__(y) <==> x*yx.__mul__(y) <==> x*y """ pass def __neg__(self, *args): #cannot find CLR method """ x.__neg__() <==> -x """ pass @staticmethod # known case of __new__ def __new__(self, *__args): """ __new__(cls: type, x: Single, y: Single, z: Single, w: Single) __new__(cls: type, vectorPart: Vector3, scalarPart: Single) __new__[Quaternion]() -> Quaternion """ pass def __ne__(self, *args): #cannot find CLR method pass def __radd__(self, *args): #cannot find CLR method """ __radd__(value1: Quaternion, value2: Quaternion) -> Quaternion Adds each element in one quaternion with its corresponding element in a second quaternion. value1: The first quaternion. value2: The second quaternion. Returns: The quaternion that contains the summed values of value1value1 and value2value2. """ pass def __rdiv__(self, *args): #cannot find CLR method """ __rdiv__(value1: Quaternion, value2: Quaternion) -> Quaternion Divides one quaternion by a second quaternion. value1: The dividend. value2: The divisor. Returns: The quaternion that results from dividing value1value1 by value2value2. """ pass def __repr__(self, *args): #cannot find CLR method """ __repr__(self: object) -> str """ pass def __rmul__(self, *args): #cannot find CLR method """ __rmul__(value1: Quaternion, value2: Quaternion) -> Quaternion Returns the quaternion that results from multiplying two quaternions together. value1: The first quaternion. value2: The second quaternion. Returns: The product quaternion. """ pass def __rsub__(self, *args): #cannot find CLR method """ __rsub__(value1: Quaternion, value2: Quaternion) -> Quaternion Subtracts each element in a second quaternion from its corresponding element in a first quaternion. value1: The first quaternion. value2: The second quaternion. Returns: The quaternion containing the values that result from subtracting each element in value2value2 from its corresponding element in value1value1. """ pass def __str__(self, *args): #cannot find CLR method pass def __sub__(self, *args): #cannot find CLR method """ x.__sub__(y) <==> x-y """ pass IsIdentity = property(lambda self: object(), lambda self, v: None, lambda self: None) # default """Gets a value that indicates whether the current instance is the identity quaternion. Get: IsIdentity(self: Quaternion) -> bool """ Identity = None W = None X = None Y = None Z = None class Vector2(object, IEquatable[Vector2], IFormattable): """ Represents a vector with two single-precision floating-point values. Vector2(value: Single) Vector2(x: Single, y: Single) """ @staticmethod def Abs(value): """ Abs(value: Vector2) -> Vector2 Returns a vector whose elements are the absolute values of each of the specified vector&#39;s elements. value: A vector. Returns: The absolute value vector. """ pass @staticmethod def Add(left, right): """ Add(left: Vector2, right: Vector2) -> Vector2 Adds two vectors together. left: The first vector to add. right: The second vector to add. Returns: The summed vector. """ pass @staticmethod def Clamp(value1, min, max): """ Clamp(value1: Vector2, min: Vector2, max: Vector2) -> Vector2 Restricts a vector between a minimum and a maximum value. value1: The vector to restrict. min: The minimum value. max: The maximum value. Returns: The restricted vector. """ pass def CopyTo(self, array, index=None): """ CopyTo(self: Vector2, array: Array[Single]) Copies the elements of the vector to a specified array. array: The destination array. CopyTo(self: Vector2, array: Array[Single], index: int) Copies the elements of the vector to a specified array starting at a specified index position. array: The destination array. index: The index at which to copy the first element of the vector. """ pass @staticmethod def Distance(value1, value2): """ Distance(value1: Vector2, value2: Vector2) -> Single Computes the Euclidean distance between the two given points. value1: The first point. value2: The second point. Returns: The distance. """ pass @staticmethod def DistanceSquared(value1, value2): """ DistanceSquared(value1: Vector2, value2: Vector2) -> Single Returns the Euclidean distance squared between two specified points. value1: The first point. value2: The second point. Returns: The distance squared. """ pass @staticmethod def Divide(left, *__args): """ Divide(left: Vector2, right: Vector2) -> Vector2 Divides the first vector by the second. left: The first vector. right: The second vector. Returns: The vector resulting from the division. Divide(left: Vector2, divisor: Single) -> Vector2 Divides the specified vector by a specified scalar value. left: The vector. divisor: The scalar value. Returns: The vector that results from the division. """ pass @staticmethod def Dot(value1, value2): """ Dot(value1: Vector2, value2: Vector2) -> Single Returns the dot product of two vectors. value1: The first vector. value2: The second vector. Returns: The dot product. """ pass def Equals(self, *__args): """ Equals(self: Vector2, obj: object) -> bool Returns a value that indicates whether this instance and a specified object are equal. obj: The object to compare with the current instance. Returns: true if the current instance and objobj are equal; otherwise, false. If objobj is null, the method returns false. Equals(self: Vector2, other: Vector2) -> bool Returns a value that indicates whether this instance and another vector are equal. other: The other vector. Returns: true if the two vectors are equal; otherwise, false. """ pass def GetHashCode(self): """ GetHashCode(self: Vector2) -> int Returns the hash code for this instance. Returns: The hash code. """ pass def Length(self): """ Length(self: Vector2) -> Single Returns the length of the vector. Returns: The vector&#39;s length. """ pass def LengthSquared(self): """ LengthSquared(self: Vector2) -> Single Returns the length of the vector squared. Returns: The vector&#39;s length squared. """ pass @staticmethod def Lerp(value1, value2, amount): """ Lerp(value1: Vector2, value2: Vector2, amount: Single) -> Vector2 Performs a linear interpolation between two vectors based on the given weighting. value1: The first vector. value2: The second vector. amount: A value between 0 and 1 that indicates the weight of value2. Returns: The interpolated vector. """ pass @staticmethod def Max(value1, value2): """ Max(value1: Vector2, value2: Vector2) -> Vector2 Returns a vector whose elements are the maximum of each of the pairs of elements in two specified vectors. value1: The first vector. value2: The second vector. Returns: The maximized vector. """ pass @staticmethod def Min(value1, value2): """ Min(value1: Vector2, value2: Vector2) -> Vector2 Returns a vector whose elements are the minimum of each of the pairs of elements in two specified vectors. value1: The first vector. value2: The second vector. Returns: The minimized vector. """ pass @staticmethod def Multiply(left, right): """ Multiply(left: Vector2, right: Vector2) -> Vector2 Multiplies two vectors together. left: The first vector. right: The second vector. Returns: The product vector. Multiply(left: Vector2, right: Single) -> Vector2 Multiplies a vector by a specified scalar. left: The vector to multiply. right: The scalar value. Returns: The scaled vector. Multiply(left: Single, right: Vector2) -> Vector2 Multiplies a scalar value by a specified vector. left: The scaled value. right: The vector. Returns: The scaled vector. """ pass @staticmethod def Negate(value): """ Negate(value: Vector2) -> Vector2 Negates a specified vector. value: The vector to negate. Returns: The negated vector. """ pass @staticmethod def Normalize(value): """ Normalize(value: Vector2) -> Vector2 Returns a vector with the same direction as the specified vector, but with a length of one. value: The vector to normalize. Returns: The normalized vector. """ pass @staticmethod def Reflect(vector, normal): """ Reflect(vector: Vector2, normal: Vector2) -> Vector2 Returns the reflection of a vector off a surface that has the specified normal. vector: The source vector. normal: The normal of the surface being reflected off. Returns: The reflected vector. """ pass @staticmethod def SquareRoot(value): """ SquareRoot(value: Vector2) -> Vector2 Returns a vector whose elements are the square root of each of a specified vector&#39;s elements. value: A vector. Returns: The square root vector. """ pass @staticmethod def Subtract(left, right): """ Subtract(left: Vector2, right: Vector2) -> Vector2 Subtracts the second vector from the first. left: The first vector. right: The second vector. Returns: The difference vector. """ pass def ToString(self, format=None, formatProvider=None): """ ToString(self: Vector2) -> str Returns the string representation of the current instance using default formatting. Returns: The string representation of the current instance. ToString(self: Vector2, format: str) -> str Returns the string representation of the current instance using the specified format string to format individual elements. format: A or that defines the format of individual elements. Returns: The string representation of the current instance. ToString(self: Vector2, format: str, formatProvider: IFormatProvider) -> str Returns the string representation of the current instance using the specified format string to format individual elements and the specified format provider to define culture-specific formatting. format: A or that defines the format of individual elements. formatProvider: A format provider that supplies culture-specific formatting information. Returns: The string representation of the current instance. """ pass @staticmethod def Transform(*__args): """ Transform(position: Vector2, matrix: Matrix3x2) -> Vector2 Transforms a vector by a specified 3x2 matrix. position: The vector to transform. matrix: The transformation matrix. Returns: The transformed vector. Transform(position: Vector2, matrix: Matrix4x4) -> Vector2 Transforms a vector by a specified 4x4 matrix. position: The vector to transform. matrix: The transformation matrix. Returns: The transformed vector. Transform(value: Vector2, rotation: Quaternion) -> Vector2 Transforms a vector by the specified Quaternion rotation value. value: The vector to rotate. rotation: The rotation to apply. Returns: The transformed vector. """ pass @staticmethod def TransformNormal(normal, matrix): """ TransformNormal(normal: Vector2, matrix: Matrix3x2) -> Vector2 Transforms a vector normal by the given 3x2 matrix. normal: The source vector. matrix: The matrix. Returns: The transformed vector. TransformNormal(normal: Vector2, matrix: Matrix4x4) -> Vector2 Transforms a vector normal by the given 4x4 matrix. normal: The source vector. matrix: The matrix. Returns: The transformed vector. """ pass def __abs__(self, *args): #cannot find CLR method """ x.__abs__() <==> abs(x) """ pass def __add__(self, *args): #cannot find CLR method """ x.__add__(y) <==> x+y """ pass def __div__(self, *args): #cannot find CLR method """ x.__div__(y) <==> x/yx.__div__(y) <==> x/y """ pass def __eq__(self, *args): #cannot find CLR method """ x.__eq__(y) <==> x==y """ pass def __format__(self, *args): #cannot find CLR method """ __format__(formattable: IFormattable, format: str) -> str """ pass def __init__(self, *args): #cannot find CLR method """ x.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signature """ pass def __mul__(self, *args): #cannot find CLR method """ x.__mul__(y) <==> x*yx.__mul__(y) <==> x*y """ pass def __neg__(self, *args): #cannot find CLR method """ x.__neg__() <==> -x """ pass @staticmethod # known case of __new__ def __new__(self, *__args): """ __new__(cls: type, value: Single) __new__(cls: type, x: Single, y: Single) __new__[Vector2]() -> Vector2 """ pass def __ne__(self, *args): #cannot find CLR method pass def __radd__(self, *args): #cannot find CLR method """ __radd__(left: Vector2, right: Vector2) -> Vector2 Adds two vectors together. left: The first vector to add. right: The second vector to add. Returns: The summed vector. """ pass def __rdiv__(self, *args): #cannot find CLR method """ __rdiv__(left: Vector2, right: Vector2) -> Vector2 Divides the first vector by the second. left: The first vector. right: The second vector. Returns: The vector that results from dividing leftleft by rightright. """ pass def __repr__(self, *args): #cannot find CLR method """ __repr__(self: object) -> str """ pass def __rmul__(self, *args): #cannot find CLR method """ __rmul__(left: Vector2, right: Vector2) -> Vector2 Multiplies two vectors together. left: The first vector. right: The second vector. Returns: The product vector. __rmul__(left: Single, right: Vector2) -> Vector2 Multiples the scalar value by the specified vector. left: The vector. right: The scalar value. Returns: The scaled vector. """ pass def __rsub__(self, *args): #cannot find CLR method """ __rsub__(left: Vector2, right: Vector2) -> Vector2 Subtracts the second vector from the first. left: The first vector. right: The second vector. Returns: The vector that results from subtracting rightright from leftleft. """ pass def __str__(self, *args): #cannot find CLR method pass def __sub__(self, *args): #cannot find CLR method """ x.__sub__(y) <==> x-y """ pass One = None UnitX = None UnitY = None X = None Y = None Zero = None class Vector3(object, IEquatable[Vector3], IFormattable): """ Represents a vector with three single-precision floating-point values. Vector3(value: Single) Vector3(value: Vector2, z: Single) Vector3(x: Single, y: Single, z: Single) """ @staticmethod def Abs(value): """ Abs(value: Vector3) -> Vector3 Returns a vector whose elements are the absolute values of each of the specified vector&#39;s elements. value: A vector. Returns: The absolute value vector. """ pass @staticmethod def Add(left, right): """ Add(left: Vector3, right: Vector3) -> Vector3 Adds two vectors together. left: The first vector to add. right: The second vector to add. Returns: The summed vector. """ pass @staticmethod def Clamp(value1, min, max): """ Clamp(value1: Vector3, min: Vector3, max: Vector3) -> Vector3 Restricts a vector between a minimum and a maximum value. value1: The vector to restrict. min: The minimum value. max: The maximum value. Returns: The restricted vector. """ pass def CopyTo(self, array, index=None): """ CopyTo(self: Vector3, array: Array[Single]) Copies the elements of the vector to a specified array. array: The destination array. CopyTo(self: Vector3, array: Array[Single], index: int) Copies the elements of the vector to a specified array starting at a specified index position. array: The destination array. index: The index at which to copy the first element of the vector. """ pass @staticmethod def Cross(vector1, vector2): """ Cross(vector1: Vector3, vector2: Vector3) -> Vector3 Computes the cross product of two vectors. vector1: The first vector. vector2: The second vector. Returns: The cross product. """ pass @staticmethod def Distance(value1, value2): """ Distance(value1: Vector3, value2: Vector3) -> Single Computes the Euclidean distance between the two given points. value1: The first point. value2: The second point. Returns: The distance. """ pass @staticmethod def DistanceSquared(value1, value2): """ DistanceSquared(value1: Vector3, value2: Vector3) -> Single Returns the Euclidean distance squared between two specified points. value1: The first point. value2: The second point. Returns: The distance squared. """ pass @staticmethod def Divide(left, *__args): """ Divide(left: Vector3, right: Vector3) -> Vector3 Divides the first vector by the second. left: The first vector. right: The second vector. Returns: The vector resulting from the division. Divide(left: Vector3, divisor: Single) -> Vector3 Divides the specified vector by a specified scalar value. left: The vector. divisor: The scalar value. Returns: The vector that results from the division. """ pass @staticmethod def Dot(vector1, vector2): """ Dot(vector1: Vector3, vector2: Vector3) -> Single Returns the dot product of two vectors. vector1: The first vector. vector2: The second vector. Returns: The dot product. """ pass def Equals(self, *__args): """ Equals(self: Vector3, obj: object) -> bool Returns a value that indicates whether this instance and a specified object are equal. obj: The object to compare with the current instance. Returns: true if the current instance and objobj are equal; otherwise, false. If objobj is null, the method returns false. Equals(self: Vector3, other: Vector3) -> bool Returns a value that indicates whether this instance and another vector are equal. other: The other vector. Returns: true if the two vectors are equal; otherwise, false. """ pass def GetHashCode(self): """ GetHashCode(self: Vector3) -> int Returns the hash code for this instance. Returns: The hash code. """ pass def Length(self): """ Length(self: Vector3) -> Single Returns the length of this vector object. Returns: The vector&#39;s length. """ pass def LengthSquared(self): """ LengthSquared(self: Vector3) -> Single Returns the length of the vector squared. Returns: The vector&#39;s length squared. """ pass @staticmethod def Lerp(value1, value2, amount): """ Lerp(value1: Vector3, value2: Vector3, amount: Single) -> Vector3 Performs a linear interpolation between two vectors based on the given weighting. value1: The first vector. value2: The second vector. amount: A value between 0 and 1 that indicates the weight of value2. Returns: The interpolated vector. """ pass @staticmethod def Max(value1, value2): """ Max(value1: Vector3, value2: Vector3) -> Vector3 Returns a vector whose elements are the maximum of each of the pairs of elements in two specified vectors. value1: The first vector. value2: The second vector. Returns: The maximized vector. """ pass @staticmethod def Min(value1, value2): """ Min(value1: Vector3, value2: Vector3) -> Vector3 Returns a vector whose elements are the minimum of each of the pairs of elements in two specified vectors. value1: The first vector. value2: The second vector. Returns: The minimized vector. """ pass @staticmethod def Multiply(left, right): """ Multiply(left: Vector3, right: Vector3) -> Vector3 Multiplies two vectors together. left: The first vector. right: The second vector. Returns: The product vector. Multiply(left: Vector3, right: Single) -> Vector3 Multiplies a vector by a specified scalar. left: The vector to multiply. right: The scalar value. Returns: The scaled vector. Multiply(left: Single, right: Vector3) -> Vector3 Multiplies a scalar value by a specified vector. left: The scaled value. right: The vector. Returns: The scaled vector. """ pass @staticmethod def Negate(value): """ Negate(value: Vector3) -> Vector3 Negates a specified vector. value: The vector to negate. Returns: The negated vector. """ pass @staticmethod def Normalize(value): """ Normalize(value: Vector3) -> Vector3 Returns a vector with the same direction as the specified vector, but with a length of one. value: The vector to normalize. Returns: The normalized vector. """ pass @staticmethod def Reflect(vector, normal): """ Reflect(vector: Vector3, normal: Vector3) -> Vector3 Returns the reflection of a vector off a surface that has the specified normal. vector: The source vector. normal: The normal of the surface being reflected off. Returns: The reflected vector. """ pass @staticmethod def SquareRoot(value): """ SquareRoot(value: Vector3) -> Vector3 Returns a vector whose elements are the square root of each of a specified vector&#39;s elements. value: A vector. Returns: The square root vector. """ pass @staticmethod def Subtract(left, right): """ Subtract(left: Vector3, right: Vector3) -> Vector3 Subtracts the second vector from the first. left: The first vector. right: The second vector. Returns: The difference vector. """ pass def ToString(self, format=None, formatProvider=None): """ ToString(self: Vector3) -> str Returns the string representation of the current instance using default formatting. Returns: The string representation of the current instance. ToString(self: Vector3, format: str) -> str Returns the string representation of the current instance using the specified format string to format individual elements. format: A or that defines the format of individual elements. Returns: The string representation of the current instance. ToString(self: Vector3, format: str, formatProvider: IFormatProvider) -> str Returns the string representation of the current instance using the specified format string to format individual elements and the specified format provider to define culture-specific formatting. format: A or that defines the format of individual elements. formatProvider: A format provider that supplies culture-specific formatting information. Returns: The string representation of the current instance. """ pass @staticmethod def Transform(*__args): """ Transform(position: Vector3, matrix: Matrix4x4) -> Vector3 Transforms a vector by a specified 4x4 matrix. position: The vector to transform. matrix: The transformation matrix. Returns: The transformed vector. Transform(value: Vector3, rotation: Quaternion) -> Vector3 Transforms a vector by the specified Quaternion rotation value. value: The vector to rotate. rotation: The rotation to apply. Returns: The transformed vector. """ pass @staticmethod def TransformNormal(normal, matrix): """ TransformNormal(normal: Vector3, matrix: Matrix4x4) -> Vector3 Transforms a vector normal by the given 4x4 matrix. normal: The source vector. matrix: The matrix. Returns: The transformed vector. """ pass def __abs__(self, *args): #cannot find CLR method """ x.__abs__() <==> abs(x) """ pass def __add__(self, *args): #cannot find CLR method """ x.__add__(y) <==> x+y """ pass def __div__(self, *args): #cannot find CLR method """ x.__div__(y) <==> x/yx.__div__(y) <==> x/y """ pass def __eq__(self, *args): #cannot find CLR method """ x.__eq__(y) <==> x==y """ pass def __format__(self, *args): #cannot find CLR method """ __format__(formattable: IFormattable, format: str) -> str """ pass def __init__(self, *args): #cannot find CLR method """ x.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signature """ pass def __mul__(self, *args): #cannot find CLR method """ x.__mul__(y) <==> x*yx.__mul__(y) <==> x*y """ pass def __neg__(self, *args): #cannot find CLR method """ x.__neg__() <==> -x """ pass @staticmethod # known case of __new__ def __new__(self, *__args): """ __new__(cls: type, value: Single) __new__(cls: type, value: Vector2, z: Single) __new__(cls: type, x: Single, y: Single, z: Single) __new__[Vector3]() -> Vector3 """ pass def __ne__(self, *args): #cannot find CLR method pass def __radd__(self, *args): #cannot find CLR method """ __radd__(left: Vector3, right: Vector3) -> Vector3 Adds two vectors together. left: The first vector to add. right: The second vector to add. Returns: The summed vector. """ pass def __rdiv__(self, *args): #cannot find CLR method """ __rdiv__(left: Vector3, right: Vector3) -> Vector3 Divides the first vector by the second. left: The first vector. right: The second vector. Returns: The vector that results from dividing leftleft by rightright. """ pass def __repr__(self, *args): #cannot find CLR method """ __repr__(self: object) -> str """ pass def __rmul__(self, *args): #cannot find CLR method """ __rmul__(left: Vector3, right: Vector3) -> Vector3 Multiplies two vectors together. left: The first vector. right: The second vector. Returns: The product vector. __rmul__(left: Single, right: Vector3) -> Vector3 Multiples the scalar value by the specified vector. left: The vector. right: The scalar value. Returns: The scaled vector. """ pass def __rsub__(self, *args): #cannot find CLR method """ __rsub__(left: Vector3, right: Vector3) -> Vector3 Subtracts the second vector from the first. left: The first vector. right: The second vector. Returns: The vector that results from subtracting rightright from leftleft. """ pass def __str__(self, *args): #cannot find CLR method pass def __sub__(self, *args): #cannot find CLR method """ x.__sub__(y) <==> x-y """ pass One = None UnitX = None UnitY = None UnitZ = None X = None Y = None Z = None Zero = None class Vector4(object, IEquatable[Vector4], IFormattable): """ Represents a vector with four single-precision floating-point values. Vector4(value: Single) Vector4(x: Single, y: Single, z: Single, w: Single) Vector4(value: Vector2, z: Single, w: Single) Vector4(value: Vector3, w: Single) """ @staticmethod def Abs(value): """ Abs(value: Vector4) -> Vector4 Returns a vector whose elements are the absolute values of each of the specified vector&#39;s elements. value: A vector. Returns: The absolute value vector. """ pass @staticmethod def Add(left, right): """ Add(left: Vector4, right: Vector4) -> Vector4 Adds two vectors together. left: The first vector to add. right: The second vector to add. Returns: The summed vector. """ pass @staticmethod def Clamp(value1, min, max): """ Clamp(value1: Vector4, min: Vector4, max: Vector4) -> Vector4 Restricts a vector between a minimum and a maximum value. value1: The vector to restrict. min: The minimum value. max: The maximum value. Returns: The restricted vector. """ pass def CopyTo(self, array, index=None): """ CopyTo(self: Vector4, array: Array[Single]) Copies the elements of the vector to a specified array. array: The destination array. CopyTo(self: Vector4, array: Array[Single], index: int) Copies the elements of the vector to a specified array starting at a specified index position. array: The destination array. index: The index at which to copy the first element of the vector. """ pass @staticmethod def Distance(value1, value2): """ Distance(value1: Vector4, value2: Vector4) -> Single Computes the Euclidean distance between the two given points. value1: The first point. value2: The second point. Returns: The distance. """ pass @staticmethod def DistanceSquared(value1, value2): """ DistanceSquared(value1: Vector4, value2: Vector4) -> Single Returns the Euclidean distance squared between two specified points. value1: The first point. value2: The second point. Returns: The distance squared. """ pass @staticmethod def Divide(left, *__args): """ Divide(left: Vector4, right: Vector4) -> Vector4 Divides the first vector by the second. left: The first vector. right: The second vector. Returns: The vector resulting from the division. Divide(left: Vector4, divisor: Single) -> Vector4 Divides the specified vector by a specified scalar value. left: The vector. divisor: The scalar value. Returns: The vector that results from the division. """ pass @staticmethod def Dot(vector1, vector2): """ Dot(vector1: Vector4, vector2: Vector4) -> Single Returns the dot product of two vectors. vector1: The first vector. vector2: The second vector. Returns: The dot product. """ pass def Equals(self, *__args): """ Equals(self: Vector4, obj: object) -> bool Returns a value that indicates whether this instance and a specified object are equal. obj: The object to compare with the current instance. Returns: true if the current instance and objobj are equal; otherwise, false. If objobj is null, the method returns false. Equals(self: Vector4, other: Vector4) -> bool Returns a value that indicates whether this instance and another vector are equal. other: The other vector. Returns: true if the two vectors are equal; otherwise, false. """ pass def GetHashCode(self): """ GetHashCode(self: Vector4) -> int Returns the hash code for this instance. Returns: The hash code. """ pass def Length(self): """ Length(self: Vector4) -> Single Returns the length of this vector object. Returns: The vector&#39;s length. """ pass def LengthSquared(self): """ LengthSquared(self: Vector4) -> Single Returns the length of the vector squared. Returns: The vector&#39;s length squared. """ pass @staticmethod def Lerp(value1, value2, amount): """ Lerp(value1: Vector4, value2: Vector4, amount: Single) -> Vector4 Performs a linear interpolation between two vectors based on the given weighting. value1: The first vector. value2: The second vector. amount: A value between 0 and 1 that indicates the weight of value2. Returns: The interpolated vector. """ pass @staticmethod def Max(value1, value2): """ Max(value1: Vector4, value2: Vector4) -> Vector4 Returns a vector whose elements are the maximum of each of the pairs of elements in two specified vectors. value1: The first vector. value2: The second vector. Returns: The maximized vector. """ pass @staticmethod def Min(value1, value2): """ Min(value1: Vector4, value2: Vector4) -> Vector4 Returns a vector whose elements are the minimum of each of the pairs of elements in two specified vectors. value1: The first vector. value2: The second vector. Returns: The minimized vector. """ pass @staticmethod def Multiply(left, right): """ Multiply(left: Vector4, right: Vector4) -> Vector4 Multiplies two vectors together. left: The first vector. right: The second vector. Returns: The product vector. Multiply(left: Vector4, right: Single) -> Vector4 Multiplies a vector by a specified scalar. left: The vector to multiply. right: The scalar value. Returns: The scaled vector. Multiply(left: Single, right: Vector4) -> Vector4 Multiplies a scalar value by a specified vector. left: The scaled value. right: The vector. Returns: The scaled vector. """ pass @staticmethod def Negate(value): """ Negate(value: Vector4) -> Vector4 Negates a specified vector. value: The vector to negate. Returns: The negated vector. """ pass @staticmethod def Normalize(vector): """ Normalize(vector: Vector4) -> Vector4 Returns a vector with the same direction as the specified vector, but with a length of one. vector: The vector to normalize. Returns: The normalized vector. """ pass @staticmethod def SquareRoot(value): """ SquareRoot(value: Vector4) -> Vector4 Returns a vector whose elements are the square root of each of a specified vector&#39;s elements. value: A vector. Returns: The square root vector. """ pass @staticmethod def Subtract(left, right): """ Subtract(left: Vector4, right: Vector4) -> Vector4 Subtracts the second vector from the first. left: The first vector. right: The second vector. Returns: The difference vector. """ pass def ToString(self, format=None, formatProvider=None): """ ToString(self: Vector4) -> str Returns the string representation of the current instance using default formatting. Returns: The string representation of the current instance. ToString(self: Vector4, format: str) -> str Returns the string representation of the current instance using the specified format string to format individual elements. format: A or that defines the format of individual elements. Returns: The string representation of the current instance. ToString(self: Vector4, format: str, formatProvider: IFormatProvider) -> str Returns the string representation of the current instance using the specified format string to format individual elements and the specified format provider to define culture-specific formatting. format: A or that defines the format of individual elements. formatProvider: A format provider that supplies culture-specific formatting information. Returns: The string representation of the current instance. """ pass @staticmethod def Transform(*__args): """ Transform(position: Vector2, matrix: Matrix4x4) -> Vector4 Transforms a two-dimensional vector by a specified 4x4 matrix. position: The vector to transform. matrix: The transformation matrix. Returns: The transformed vector. Transform(position: Vector3, matrix: Matrix4x4) -> Vector4 Transforms a three-dimensional vector by a specified 4x4 matrix. position: The vector to transform. matrix: The transformation matrix. Returns: The transformed vector. Transform(vector: Vector4, matrix: Matrix4x4) -> Vector4 Transforms a four-dimensional vector by a specified 4x4 matrix. vector: The vector to transform. matrix: The transformation matrix. Returns: The transformed vector. Transform(value: Vector2, rotation: Quaternion) -> Vector4 Transforms a two-dimensional vector by the specified Quaternion rotation value. value: The vector to rotate. rotation: The rotation to apply. Returns: The transformed vector. Transform(value: Vector3, rotation: Quaternion) -> Vector4 Transforms a three-dimensional vector by the specified Quaternion rotation value. value: The vector to rotate. rotation: The rotation to apply. Returns: The transformed vector. Transform(value: Vector4, rotation: Quaternion) -> Vector4 Transforms a four-dimensional vector by the specified Quaternion rotation value. value: The vector to rotate. rotation: The rotation to apply. Returns: The transformed vector. """ pass def __abs__(self, *args): #cannot find CLR method """ x.__abs__() <==> abs(x) """ pass def __add__(self, *args): #cannot find CLR method """ x.__add__(y) <==> x+y """ pass def __div__(self, *args): #cannot find CLR method """ x.__div__(y) <==> x/yx.__div__(y) <==> x/y """ pass def __eq__(self, *args): #cannot find CLR method """ x.__eq__(y) <==> x==y """ pass def __format__(self, *args): #cannot find CLR method """ __format__(formattable: IFormattable, format: str) -> str """ pass def __init__(self, *args): #cannot find CLR method """ x.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signature """ pass def __mul__(self, *args): #cannot find CLR method """ x.__mul__(y) <==> x*yx.__mul__(y) <==> x*y """ pass def __neg__(self, *args): #cannot find CLR method """ x.__neg__() <==> -x """ pass @staticmethod # known case of __new__ def __new__(self, *__args): """ __new__(cls: type, value: Single) __new__(cls: type, x: Single, y: Single, z: Single, w: Single) __new__(cls: type, value: Vector2, z: Single, w: Single) __new__(cls: type, value: Vector3, w: Single) __new__[Vector4]() -> Vector4 """ pass def __ne__(self, *args): #cannot find CLR method pass def __radd__(self, *args): #cannot find CLR method """ __radd__(left: Vector4, right: Vector4) -> Vector4 Adds two vectors together. left: The first vector to add. right: The second vector to add. Returns: The summed vector. """ pass def __rdiv__(self, *args): #cannot find CLR method """ __rdiv__(left: Vector4, right: Vector4) -> Vector4 Divides the first vector by the second. left: The first vector. right: The second vector. Returns: The vector that results from dividing leftleft by rightright. """ pass def __repr__(self, *args): #cannot find CLR method """ __repr__(self: object) -> str """ pass def __rmul__(self, *args): #cannot find CLR method """ __rmul__(left: Vector4, right: Vector4) -> Vector4 Multiplies two vectors together. left: The first vector. right: The second vector. Returns: The product vector. __rmul__(left: Single, right: Vector4) -> Vector4 Multiples the scalar value by the specified vector. left: The vector. right: The scalar value. Returns: The scaled vector. """ pass def __rsub__(self, *args): #cannot find CLR method """ __rsub__(left: Vector4, right: Vector4) -> Vector4 Subtracts the second vector from the first. left: The first vector. right: The second vector. Returns: The vector that results from subtracting rightright from leftleft. """ pass def __str__(self, *args): #cannot find CLR method pass def __sub__(self, *args): #cannot find CLR method """ x.__sub__(y) <==> x-y """ pass One = None UnitW = None UnitX = None UnitY = None UnitZ = None W = None X = None Y = None Z = None Zero = None
import json def translate_item(item, translator = None, exclusive = False, print_debug = False): """ Translate a single json Parameters -------------- item : dict Item to translate. translator : Dict[str, str] Dict specifying translation, where the key is the field name in the input and value the field name in the output. exclusive : bool Translate only the fields specified by the translator. Ignored if no translator. print_debug : bool Whether to print the resulting translation or not Returns -------------- translation_generator : Generator[Dict] Generator that gives a single translated json at a time """ if translator is None: return item translated = dict() for source in item: if source in translator: target = translator[source] if (print_debug): print("translating: {} [{}] to {}".format(source, item[source], target)) translated[target] = item[source] elif not exclusive: if (print_debug): print("copying: {} [{}]".format(source, item[source])) translated[source] = item[source] return translated def translate(input_path, translator = None, exclusive = False, print_debug = False): """ Generator that translates jsons read from input file. Parameters -------------- input : str Input file path. translator : Dict[str, str] Dict specifying translation, where the key is the field name in the input and value the field name in the output. exclusive : bool Translate only the fields specified by the translator. Ignored if no translator. print_debug : bool Whether to print the resulting translation or not Returns -------------- translation_generator : Generator[Dict] Generator that gives a single translated json at a time """ with open(input_path, 'r') as file: if translator is None: for line in file: yield json.loads(line) else: for line in file: current = json.loads(line) yield translate_item(current, translator=translator, exclusive=exclusive, print_debug=print_debug) def translate_all(input_path, translator = None, exclusive = False, print_debug = False): """ Translate jsons read from input file. Parameters -------------- input : str Input file path. translator : Dict[str, str] Dict specifying translation, where the key is the field name in the input and value the field name in the output. exclusive : bool Translate only the fields specified by the translator. Ignored if no translator. print_debug : bool Whether to print the resulting translation or not Returns -------------- translations : List[Dict] List of all translated jsons in a file """ result = [] for translated in translate(input_path, translator, exclusive, print_debug): result.append(translated) return result
#!/usr/bin/env python3 i = 1 for i in range(1,101): if i%7 ==0: continue elif i%10==7 or i//10 ==7: continue else: print(i) i+=1
'''Two words are anagrams if you can rearrange the letters from one to spell the other. Write a function called is_anagram that takes two strings and returns True if they are anagrams. ''' def is_anagram(string1,string2): if sorted(string1) == sorted(string2): return True else: return False string1 = 'heart' string2 = 'earth' result = is_anagram(string1,string2) print(result)
def is_palindrome(s): res= s== s[::-1] return res s = 'mom' res=is_palindrome(s) print("is the string palindrome :" ,res)
'''The greatest common divisor (GCD) of a and b is the largest number that divides both of them with no remainder. One way to find the GCD of two numbers is based on the observation that if r is the remainder when a is divided by b, then gcd(a, b) = gcd(b, r). As a base case, we can use gcd(a, 0) = a. Write a function called gcd that takes parameters a and b and returns their greatest common divisor.''' '''from math import * result = gcd(15,20) print(result) OR ''' def calculateGcd(number1,number2): if number2==0: return number1 else: return calculateGcd(number2,number1%number2) number1 = int(input("enter 1st number: ")) number2 = int(input("enter 2nd number: ")) gcd=calculateGcd(number1,number2) print(gcd)
# Name: Elena Rangelov # Date: 1.7.2021 import random class RandomBot: def __init__(self): self.white = "O" self.black = "@" self.directions = [[-1, -1], [-1, 0], [-1, 1], [0, -1], [0, 1], [1, -1], [1, 0], [1, 1]] self.opposite_color = {self.black: self.white, self.white: self.black} self.x_max = None self.y_max = None def best_strategy(self, board, color): # returns best move self.x_max = len(board) self.y_max = len(board[0]) if color == "#000000": color = "@" else: color = "O" moves1 = self.find_moves(board, color) moves = [] for m in moves1: x = m // 8 y = m % 8 moves += [[x, y]] x = random.randint(0, len(moves) - 1) best_move = moves[x] return best_move, 0 def stones_left(self, board): count = 0 for x in board: for y in board[x]: if board[x, y] == ".": count += 1 return count def find_moves(self, board, color): moves_found = {} for i in range(len(board)): for j in range(len(board[i])): flipped_stones = self.find_flipped(board, i, j, color) if len(flipped_stones) > 0: moves_found.update({i * self.y_max + j: flipped_stones}) return moves_found def find_flipped(self, board, x, y, color): if board[x][y] != ".": return [] if color == self.black: my_color = "@" else: my_color = "O" flipped_stones = [] for incr in self.directions: temp_flip = [] x_pos = x + incr[0] y_pos = y + incr[1] while 0 <= x_pos < self.x_max and 0 <= y_pos < self.y_max: if board[x_pos][y_pos] == ".": break if board[x_pos][y_pos] == my_color: flipped_stones += temp_flip break temp_flip.append([x_pos, y_pos]) x_pos += incr[0] y_pos += incr[1] return flipped_stones class Best_AI_bot: def __init__(self): self.white = "o" self.black = "@" self.directions = [[-1, -1], [-1, 0], [-1, 1], [0, -1], [0, 1], [1, -1], [1, 0], [1, 1]] self.opposite_color = {self.black: self.white, self.white: self.black} self.x_max = None self.y_max = None def best_strategy(self, board, color): # returns best move return self.alphabeta(board, color, 3, float("inf"), float("-inf")) def minimax(self, board, color, search_depth): # returns best "value" return 1 def negamax(self, board, color, search_depth): # returns best "value" return 1 def alphabeta(self, board, color, search_depth, alpha, beta): # returns best "value" while also pruning # v = self.max_value(board, color, alpha, beta) # for f in self.find_moves(board, color): # n_board = self.make_move(f, board)) # # return self.find_moves(board, color)[v] # self.x_max = len(board) self.y_max = len(board[0]) if color == "#ffffff": m_color = self.white else: m_color = self.black moves = self.find_moves(board, m_color) print("heya", color, moves) value = -9999 move = -1 v = self.max_value(board, m_color, search_depth, alpha, beta) for m in moves: n_board = self.make_move(board, color, m) n_value = self.min_value(n_board, self.opposite_color[m_color], 2, alpha, beta) if n_value > value: value = n_value move = m return (move // self.y_max, move % self.y_max), value def max_value(self, board, color, search_depth, alpha, beta): # if self.stones_left(board) == 0: # moves = self.find_moves(board, color) # return self.evaluate(board, color, moves) # v = float("-inf") # for m in self.find_moves(board, color): # v = max(v, self.min_value(self.make_move(m, board), alpha, beta)) # if v > beta: # return v # alpha = max(alpha, v) # return v moves = self.find_moves(board, color) if len(moves) == 0: return -1000 if len(self.find_moves(board, self.opposite_color[color])) == 0: return 1000 if search_depth == 1: return self.evaluate(board, color, moves) v = float("-inf") for m in moves: n_board = self.make_move(board, color, m) next = self.min_value(n_board, self.opposite_color[color], search_depth - 1, alpha, beta) if max(v, next) != v: v = next if v > beta: return v alpha = max(alpha, v) return v def min_value(self, board, color, search_depth, alpha, beta): # if self.stones_left(board) == 0: # return self.evaluate(board) # v = float("inf") # for m in self.find_moves(board, color): # v = min(v, self.max_value(self.make_move(m, board), alpha, beta)) # if v < alpha: # return v # beta = min(beta, v) # return v moves = self.find_moves(board, color) if len(moves) == 0: return 1000 if len(self.find_moves(board, self.opposite_color[color])) == 0: return -1000 if search_depth == 1: return -self.evaluate(board, color, moves) v = float("inf") for m in moves: n_board = self.make_move(board, color, m) next = self.max_value(n_board, self.opposite_color[color], search_depth - 1, alpha, beta) if min(v, next) != v: v = next if v < alpha: return v beta = min(beta, v) return v def make_key(self, board, color): # hashes the board return 1 def stones_left(self, board): count = 0 for x in range(len(board)): if board[x] == ".": count += 1 return count def make_move(self, board, color, move): n_board = [row[:] for row in board] if color == self.white: char = "O" else: char = "@" x = move // 8 y = move % 8 n_board[x][y] = char flip = self.find_flipped(board, x, y, color) for f in flip: x = f[0] y = f[1] n_board[x][y] = char return n_board def evaluate(self, board, color, possible_moves): # returns the utility value # if color == "#ffffff": # m_color = self.white # else: m_color = self.black # return len(possible_moves) - len(self.find_moves(board, self.opposite_color[m_color])) mx = 0 for m in possible_moves: mx = max(len(possible_moves[m]), mx) return mx def score(self, board, color): # returns the score of the board return 1 def find_moves(self, board, color): moves_found = {} for i in range(len(board)): for j in range(len(board[i])): flipped_stones = self.find_flipped(board, i, j, color) if len(flipped_stones) > 0: moves_found.update({i * self.y_max + j: flipped_stones}) return moves_found def find_flipped(self, board, x, y, color): if board[x][y] != ".": return [] if color == self.black: my_color = "@" else: my_color = "O" flipped_stones = [] for incr in self.directions: temp_flip = [] x_pos = x + incr[0] y_pos = y + incr[1] while 0 <= x_pos < self.x_max and 0 <= y_pos < self.y_max: if board[x_pos][y_pos] == ".": break if board[x_pos][y_pos] == my_color: flipped_stones += temp_flip break temp_flip.append([x_pos, y_pos]) x_pos += incr[0] y_pos += incr[1] return flipped_stones
import numpy as np import pandas as pd import matplotlib.pyplot as plt data = pd.read_csv('/home/amartya/Desktop/Udemy_data/K_Nearest_Neighbors/K_Nearest_Neighbors/Social_Network_Ads.csv') X = data.iloc[:, 2:4].values y = data.iloc[:, 4:5].values from sklearn.cross_validation import train_test_split X_train, X_test, y_train, y_test = train_test_split(X,y,train_size = 0.75, random_state = 0) '''Feature Scaling''' from sklearn.preprocessing import StandardScaler standard_scaler = StandardScaler() X_train = standard_scaler.fit_transform(X_train) X_test = standard_scaler.transform(X_test) '''Kernel_SVM(Max.length classifier)''' '''It is a gaussian curve that is at the maximum sum of distances from the 2 nearest points(support vectors) to it. It looks at the extreme cases which are very close to the boundary and uses that to construct it's analysis. Same as SVM, just we use gaussian kernel. ''' from sklearn.svm import SVC classifier = SVC(kernel = 'rbf', random_state=0) classifier.fit(X_train, y_train) '''Predicting the test set result''' y_pred = classifier.predict(X_test) from sklearn.metrics import confusion_matrix cm = confusion_matrix(y_test, y_pred) '''Applying k-fold cross validation''' ''' This is much better than accuracy through confusion matrix as it first divides the training set into cv(here 10) parts and then determines the accuracy of each part. ''' from sklearn.model_selection import cross_val_score accuracies = cross_val_score(estimator=classifier, X=X_train, y=y_train, cv=10) accuracies.mean() accuracies.std() '''Applying grid-search to find best model and best parameters.''' from sklearn.model_selection import GridSearchCV # For parameters, check the parameters of the classifier(here SVC) and make it a list of dictionaries. parameters = [{'C':[1,10,100,1000], 'kernel':['linear']}, {'C':[1,10,100,1000], 'kernel':['rbf'], 'gamma':[0.5,0.1,0.01,0.001,0.50]} ] '''In SVC, C is the regularization parameter. It prevents overfitting. If it is too large, then overfitting can occur. Kernel specifies whether we use linear, rbf or poly kernel. Gamma parameter is (1/no.of features, here 0.5) kernel coefficient. Choose the parameters around the default and then after the result, change the calues and test again. ''' grid_search = GridSearchCV(estimator = classifier, param_grid = parameters, scoring='accuracy', cv =10, n_jobs=-1) grid_search = grid_search.fit(X_train, y_train) best_accuracy = grid_search.best_score_ best_parameters = grid_search.best_params_ '''Visualizing the results on the training set.''' from matplotlib.colors import ListedColormap X_set, y_set = X_train, y_train X1, X2 = np.meshgrid(np.arange(start = X_set[:,0].min()-1, stop = X_set[:,0].max()+1, step = 0.01), np.arange(start = X_set[:,1].min()-1, stop = X_set[:,1].max()+1, step = 0.01)) plt.contourf(X1, X2, classifier.predict(np.array([X1.ravel(), X2.ravel()]).T).reshape(X1.shape), alpha = 0.75, cmap = ListedColormap(('red', 'green'))) plt.xlim(X1.min(), X1.max()) plt.ylim(X2.min(), X2.max()) for i,j in enumerate(np.unique(y_set)): plt.scatter(X_set[y_set == j,0], X_set[y_set == j,1], c = ListedColormap(('red','green'))(i), label = j) plt.title('SVM(Training Set)') plt.xlabel('Age') plt.ylabel('Salary') plt.legend() plt.show() '''Visualizing the test set results.''' from matplotlib.colors import ListedColormap X_set, y_set = X_test, y_test X1, X2 = np.meshgrid(np.arange(start = X_set[:,0].min()-1, stop = X_set[:,0].max()+1, step = 0.01), np.arange(start = X_set[:,1].min()-1, stop = X_set[:,1].max()+1, step = 0.01)) plt.contourf(X1, X2, classifier.predict(np.array([X1.ravel(), X2.ravel()]).T).reshape(X1.shape), alpha = 0.75, cmap = ListedColormap(('red', 'green'))) plt.xlim(X1.min(), X1.max()) plt.ylim(X2.min(), X2.max()) for i,j in enumerate(np.unique(y_set)): plt.scatter(X_set[y_set == j,0], X_set[y_set == j,1], c = ListedColormap(('red','green'))(i), label = j) plt.title('KNN(Training Set)') plt.xlabel('Age') plt.ylabel('Salary') plt.legend() plt.show()
import numpy as np import pandas as pd import matplotlib.pyplot as plt data = pd.read_csv('/home/amartya/Desktop/Udemy_data/Simple_Linear_Regression/Salary_Data.csv') X = data.iloc[:, 0:1].values y = data.iloc[:, 1:2].values '''For splitting the data into training and test set''' from sklearn.cross_validation import train_test_split X_train, X_test, y_train, y_test = train_test_split(X, y, train_size = 0.66, random_state = 0) '''Feature Scaling is necessary for scaling the data. Normalization(values between 0 and 1)- Use MinMaxScaler and Standardization(mean = 0 and std. dev=1)''' '''from sklearn.preprocessing import StandardScaler standard_scaler = StandardScaler() X_train = standard_scaler.fit_transform(X_train) X_test = standard_scaler.transform(X_test)''' '''Linear Regression''' from sklearn.linear_model import LinearRegression linear_regressor = LinearRegression() linear_regressor.fit(X_train, y_train) y_predict = linear_regressor.predict(X_test) '''Regression line for training data and pred training data Scatterplot for test data. Calculate the error between y_test(red) and the y_predict(found above and corresponding point on graph)''' plt.scatter(X_test, y_test, color = 'red') plt.plot(X_train, linear_regressor.predict(X_train), color='blue') plt.xlabel('Years of experience') plt.ylabel('Salary') plt.show()
print("hello"+"world") print("hello","world") print("-------------------") name=input("请输入你的名字:") age=input("请输入你的年龄:") hobby=input("请输入你的爱好:") print("你的名字为:"+name+",\n年龄是:"+age+",\n爱好为:"+hobby)
# OOP Aggregation class Salary: def __init__(self, pay, bonus): self.pay = pay self.bonus = bonus def annual_salary(self): return (self.pay * 12) + self.bonus # Instantiating the salary class in the Employee class so # salary class is the content and Employee class is container class Employee: def __init__(self, name, age, salary): self.name = name self.age = age self.obj_salary = salary def total_salary(self): return self.obj_salary.annual_salary() salary = Salary(90000, 10000) emp = Employee('Aditya', 21, salary) print(emp.total_salary())
# Class Attributes class Person: number_of_people = 0 # This is a Class Attribute which is same for all people and hence it is # common to all instances of the class def __init__(self, name): self.name = name Person.number_of_people += 1 p1 = Person("Aditya") print(p1.number_of_people) p2 = Person("Sophie") print(p2.number_of_people) # Class Methods class Person: number_of_people = 0 # This is a Class Attribute which is same for all people and hence it is # common to all instances of the class def __init__(self, name): self.name = name Person.add_person() @classmethod def number_of_people_(cls): return cls.number_of_people @classmethod def add_person(cls): cls.number_of_people += 1 p1 = Person("Aditya") p2 = Person("Sophie") print(Person.number_of_people_())
# Introduction to Inheritance # Upper Level Class and all other classes borrow from it # generalisation class Pet: def __init__(self, name, age): self.name = name self.age = age def show(self): print(f"I am {self.name} and I am {self.age} years old") def speak(self): print("I don't know what to say") class Cat(Pet): def __init__(self, name, age, color): super().__init__(name, age) self.color = color def show(self): print(f"I am {self.name} and I am {self.age} years old and I am {self.color} in color") def speak(self): print("Meow") class Dog(Pet): def speak(self): print("Bark") class Fish(Pet): pass p = Pet("Aditya", 21) p.show() p.speak() c = Cat("Ishita", 22, "Violet") c.show() c.speak() d = Dog("Sanan", 23) d.show() d.speak() f = Fish("Saransh", 25) f.show() f.speak()