text
stringlengths
37
1.41M
# create a simple list a = ['a', 'b', 'c', 'x', 'y', 'z'] # iterate through list, using enumarate to retrieve index and item for index, item in enumerate(a): print("index", index, ", ", "item", item)
string = input("Введите текст: ") length = len(string) lower = upper = 0 for i in string: if i.islower(): lower += 1 elif i.isupper(): upper += 1 per_lower = lower / length * 100 per_upper = upper / length * 100 print("%% строчных букв: %.2f%%" % per_lower) print("%% прописных букв: %.2f%%" % per_upper)
# Input : A collection A = {a1, . . . , an}, indices l, r # Output: An array A' containing all elements of A in nondecreasing order A = [2, 4, 1, 6, 5, 3] def quick_sort(array, left, right): index = partition(array, left, right) if left < index - 1: quick_sort(array, left, index - 1) if index < right: quick_sort(array, index, right) return array def partition(array, i, j): a = int( (i + j) / 2) pivot = array[a] while i <= j: while array[i] < pivot: i = i + 1 while array[j] > pivot: j = j - 1 if i <= j: aux = array[i] array[i] = array[j] array[j] = aux i = i + 1 j = j - 1 return i response = quick_sort(A, 0, 5) print(response)
def reverse_word(word): res = "" for letter in range(len(word) - 1, -1, -1): res += word[letter] return res if __name__ == "__main__": inpt = input("Enter yout sentence: ") string = "" for symbol in inpt: if symbol not in ":.,;-!?": string += symbol.lower() res = [word for word in string.split() if word == reverse_word(word)] print(" ".join(res))
import copy def calculate(number): """ function calculates number of elements, the highest and the lowest, their sum, average and median >>> calculate([1, 2, 3, 4, 5]) ([1, 2, 3, 4, 5], 5, 15, 1, 5, 3.0, 3) >>> calculate([2, 4, 6, 7, 3]) ([2, 4, 6, 7, 3], 5, 22, 2, 7, 4.4, 4) >>> calculate([5, 7, 3, 6, 3]) ([5, 7, 3, 6, 3], 5, 24, 3, 7, 4.8, 5) """ cp = copy.copy(number) count = len(number) sum = 0 for j in number: # j=int(j) sum += j number1 = sorted(number) highest = number1[len(number1)-1] lowest = number1[0] mean = sum/len(number) if count % 2 == 1: median = number1[int(count/2)] else: median = (number1[int(count/2)] + number1[int(count/2 - 1)])/2 return cp, count, sum, lowest, highest, mean, median # ([5, 4, 1, 8, 5, 2], 6, 25, 1, 8, 4.166666666666667, 4.5) print(calculate([5,4,1,8,5,2])) import doctest doctest.testmod()
from copy import deepcopy def make_board(n): """ int -> list Returns a list, filled with zeros, representing a board """ column = [0 for i in range(n)] board = [column[:] for i in range(n)] return board def print_result(n, lst_of_results): """ int, list -> None This function is used for printing all answers in an accessible way """ print('_' * 20) for index, result in enumerate(lst_of_results): print(f'Solution №{index + 1}:') for row in result: print('0 ' * row + '1 ' + '0 ' * (n - row - 1)) print('_' * 20) def check_if_ok(board, row, column): """ list, int, int -> bool Returns True if we can place a queen on these coordinates, else False """ # Checking the horizontal cells: for col in range(column): if board[row][col] == 1: return False row_down, row_up, col_diagonal = row, row, column # Cheching cells on the top left diagonal while row_up >= 0 and col_diagonal >= 0: if board[row_up][col_diagonal] == 1: return False col_diagonal -= 1 row_up -= 1 col_diagonal = column # Cheching cells on the bottom left diagonal while row_down < len(board) and col_diagonal >= 0: if board[row_down][col_diagonal] == 1: return False col_diagonal -= 1 row_down += 1 return True def find_backtracking(n, board, lst_of_results, column=0): """ int, list, list, int -> bool Recursive algorithm that finds all possible solutions by backtracking to smaller boards """ # When we reach the last column if column == n: return True for row in range(n): # Cheching if we can place a queen in this cell: if check_if_ok(board, row, column): # Placing a queen in this cell board[row][column] = 1 # When we find a result, we save it to the lst_of_results and go on if column == n-1: if board not in lst_of_results: lst_of_results.append(deepcopy(board)) board[row][column] = 0 continue # Going to the next column if find_backtracking(n, board, lst_of_results, column + 1): # When there's a solution for this column: return True # We can't place a queen here. There is no solution in next columns else: board[row][column] = 0 return False def convert_format(n, solutions): """ int, list -> None Converts the board states to a different format (e.g. [[0, 0, 1],[0, 1, 0],[1, 0, 0]] -> [0, 1, 2]) """ for index, solution in enumerate(solutions): result = [solution[row].index(1) for row in range(n)] solutions[index] = result def duplicate_filter(n, solutions): """ int, list -> list Removes all of the duplicate solutions (mirror reflections, rotations, or both) """ results = [solutions[0]] # First can't be duplicate, checking all others for solution in solutions[1:]: # Trying all different reflections/rotations mirror = solution[::-1] reverse = [n - 1 - row for row in mirror] miror_reverse = [n - 1 - row for row in solution] right_turn = [n - 1 - solution.index(i) for i in range(n)] left_turn = [solution.index(n - 1 - j) for j in range(n)] right_mirror = [n - 1 - mirror.index(k) for k in range(n)] left_mirror = [mirror.index(n - 1 - l) for l in range(n)] if mirror in results or reverse in results or miror_reverse in results: continue if right_turn in results or left_turn in results: continue if right_mirror in results or left_mirror in results: continue # If solution is not duplicate, we save it to results list results.append(solution) return results def main(): """ None -> None This function is used to call all other functions and print the result """ # Inputting an n and checking if it's an integer >= 0 while True: n = input("Enter the number of queens: ") if n.isdigit(): n = int(n) break print("N has to be a positive integer!") if n < 4: if n == 0: print(f'\nTechnically, there are infinite solutions for n = {n}.') else: print(f'\nThere are no solutions for n = {n}.') return board = make_board(n) lst_of_results = [] # Filling lst_of_results with all possible boards find_backtracking(n, board, lst_of_results) # Eliminate the duplicate solutions convert_format(n, lst_of_results) unique_results = duplicate_filter(n, lst_of_results) # Prinring the results print_result(n, unique_results) print(f'\nSolutions for n = {n}: {len(lst_of_results)}') print(f'Unique solutions for n = {n}: {len(unique_results)}\n') if __name__ == "__main__": main()
#Problem 1 def get_position(ch): """ str -> int Return a positon of letter in alphabet. If argument is not a letter function should return None. >>> get_position('A') 1 >>> get_position('z') 26 >>> get_position('Dj') """ if not isinstance(ch, str): return None if len(ch) == 1: letter_order = ord(ch.upper()) - 64 if 1 <= letter_order <= 26: return letter_order return None # print(get_position(1258)) # **************************************** # Problem 3 def compare_str(s1, s2): """ (str, str) -> bool Compare two srings lexicographicly. Return True if string s1 is larger than string s2 and False otherwise. If arguments aren't string or function have different length function should return None. >>> compare_str('abc', 'Abd') False >>> compare_str('zaD', 'zab') True >>> compare_str('zaD', 'Zad') False >>> compare_str('aaa', 'aaaaa') >>> compare_str('2015', 2015) """ try: for i in range(max(len(s1), len(s2))): if s1[i].upper() == s2[i].upper(): continue if s1[i].upper() > s2[i].upper(): return True return False except: return None # **************************************** # Problem 4 def type_by_angles(a, b, c): """ (float, float, float) -> str Detect the type of triangle by it's angles in degrees and return type as string ("right angled triangle", "obtuse triangle", "acute triangle"). If there is no triangle with such angles, then function should return None. >>> type_by_angles(60, 60, 60) 'acute triangle' >>> type_by_angles(90, 30, 60) 'right angled triangle' >>> type_by_angles(2015, 2015, 2015) """ if a + b + c != 180: return None max_angle = max(a, b, c) if max_angle == 90: return "right angled triangle" return "obtuse triangle" if max_angle > 90 else "acute triangle" # **************************************** # Problem 6 def remove_spaces(s): """ str -> str Remove all additional spaces in string and return a new string without additional spaces. If argument is not a string function should return None. >>> remove_spaces("I'll make him an offer he can't refuse.") "I'll make him an offer he can't refuse." >>> remove_spaces("Great men are not born great, they grow great...") 'Great men are not born great, they grow great...' >>> remove_spaces(2015) """ try: while True: if s.find(" ") == -1: break s = s.replace(" ", " ") return s except : return None # **************************************** # Problem 8 def number_of_sentences(s): """ str -> str Return number of sentence in the string. If argument is not a string function should return None. >>> number_of_sentences("Revenge is a dish that tastes best when served cold.") 1 >>> number_of_sentences("Never hate your enemies. It affects your judgment.") 2 >>> number_of_sentences(2015) """ if isinstance(s, str): return s.count(".") else: return None # **************************************** # Problem 11 def decrypt_message(s): """ str -> str Replace all letters in string with previous letters in aplhabet. If argument isn't a string function should return None. >>> decrypt_message("Sfwfohf jt b ejti uibu ubtuft cftu xifo tfswfe dpme.") 'Revenge is a dish that tastes best when served cold.' >>> decrypt_message("Ofwfs ibuf zpvs fofnjft. Ju bggfdut zpvs kvehnfou.") 'Never hate your enemies. It affects your judgment.' >>> decrypt_message(2015) """ if isinstance(s, str): for i in range(64, 123, 1): s = s.replace(chr(i), chr(i - 1)) return s return None # **************************************** # Problem 16 def find_union(s1, s2): """ (str, str) -> str Find and return string of all letters in alphabetic order that are present in either strings. If arguments aren't strings function should return None. >>> find_union("aaabb", "bbbbccc") 'abc' >>> find_union("aZAbc", "zzYYxp") 'AYZabcpxz' >>> find_union("sfdfsdf", 2015) """ if isinstance(s1, str) and isinstance(s2, str): res = "" for i in range(65, 123): if chr(i) in s1 + s2: res += chr(i) return res return None # **************************************** # Problem 17 def number_of_occurence(lst, s): """ (list, str) -> int Find and return number of occurence of string s in all elements of the list lst. If lst isn't list of strings or s isn't string function should return None. >>> number_of_occurence(["man", "girl", "women", "boy"], "m") 2 >>> number_of_occurence(["ab", "aba", "a", "b", "ba"], "ba") 2 >>> number_of_occurence([1, 2, 2015, 1, 3], "1") """ counter = 0 for i in lst: if isinstance(i, str) and isinstance(s, str): counter += i.count(s) else: return None return counter # **************************************** # Problem 22 def pattern_number(sequence): """ list -> list >>> pattern_number([]) >>> pattern_number([42]) >>> pattern_number([1,2]) >>> pattern_number([1,1]) ([1], 2) >>> pattern_number([1,2,1]) >>> pattern_number([1,2,3,1,2,3]) ([1, 2, 3], 2) >>> pattern_number([1,2,3,1,2]) >>> pattern_number([1,2,3,1,2,3,1]) >>> pattern_number(list(range(10))*20) ([0, 1, 2, 3, 4, 5, 6, 7, 8, 9], 20) >>> pattern_number('мама') ('ма', 2) >>> pattern_number('барабан') """ number_of_ok = 1 ok_value = 0 length = len(sequence) for i in range(1, length):# i - number of items in sequence this_length_is_ok = True for sequence_elem in range(0, i): for check in range(0 + sequence_elem, length, i): # j - elems of sequence if sequence[check] != sequence[sequence_elem]: this_length_is_ok = False if this_length_is_ok: number_of_ok += 1 if ok_value == 0: ok_value = i res = sequence[0:ok_value] if number_of_ok == 1 or len(res) * number_of_ok != len(sequence): return None return res, number_of_ok # **************************************** # Problem 24 def numbers_Ulam(n): """ >>> numbers_Ulam(10) [1, 2, 3, 4, 6, 8, 11, 13, 16, 18] >>> numbers_Ulam(2) [1, 2] >>> numbers_Ulam(1) [1] """ res = [1, 2] if not isinstance(n, int) or n ==0: return None number_to_check = 3 while len(res) < n: temporary_possible = [] for value1 in res: for value2 in res: possible_number = value1 + value2 if value1 >= value2 or possible_number in res: continue temporary_possible.append(possible_number) while True: if temporary_possible.count(number_to_check) == 1: res.append(number_to_check) break number_to_check += 1 return [1] if n== 1 else res # **************************************** # Problem 25 def happy_number(n): """ >>> happy_number(32) True >>> happy_number(33) False """ x = n y = n next_number = 0 tries = 0 while next_number != 1: length = 0 while x > 0: x = x // 10 length += 1 next_number = 0 for i in range(length): next_number += ((y // 10**i)% 10)**2 x ,y = next_number, next_number tries += 1 if tries > 100000: return False return True # **************************************** # Problem 26 # **************************************** def sum_of_divisors(n, lst): """ (int, list) -> int Find and return sum of all odd numbers in the list, that are divisible by n. >>> sum_of_divisors(3, [2, 0, 1, 5]) 0 >>> sum_of_divisors(5, [2, 0, 1, 5]) 5 >>> sum_of_divisors(7, []) 0 """ if not isinstance(n, int) and not isinstance(lst, list): return None res = 0 for i in lst: if i%n == 0 and i%2 == 1: res += i return res if __name__ == "__main__": import doctest doctest.testmod() # for i, j in enumerate(lst): # print(i, j)
def make_board(): """ returns a list, representing 8*8 board """ return [[0 for i in range(8)] for i in range(8)] def print_board(board): """ Prints a board """ for i in board: for j in i: print(j, end=" ") print() def convert_postition(pos): """ str -> tuple returns a tuple with coordinates of a figure """ second = int(pos[1]) - 1 first = ord(pos[0]) - 97 return first, second def elephant(elephant_pos, board): """ (tuple, list) -> list Returns a board with 1, where user cannot place a figure because elephant beats it """ col = elephant_pos[0] row = elephant_pos[1] board[col][row] = 3 # top left: i, j = col, row while i >= 0 and j >= 0: board[i][j] = 1 i -= 1 j -= 1 i, j = col, row while i <= 7 and j >= 0: board[i][j] = 1 i += 1 j -= 1 i, j = col, row while i <= 7 and j <= 7: board[i][j] = 1 i += 1 j += 1 i, j = col, row while i >= 0 and j <= 7: board[i][j] = 1 i -= 1 j += 1 def turrel(pos, board): """ tuple, list -> list writes 1 where turrel beats a cell """ row = pos[0] col = pos[1] for i in range(len(board)): board[i][col] = 1 for j in range(len(board)): board[row][j] = 1 def result(board): res = [] for i in range(8): for j in range(8): if board[i][j] == 0: res.append([chr(i + 97), j + 1]) return res def main(elephant_pos, queen_pos): """ (str, str) -> set Receives position of white elephant and queen and returns all possible positions for black figures """ board = make_board() elephant_pos = convert_postition(elephant_pos) queen_pos = convert_postition(queen_pos) elephant(elephant_pos, board) turrel(queen_pos, board) elephant(queen_pos, board) res = result(board) for i in range(len(res)): res[i] = res[i][0] + str(res[i][1]) set_res = set(res) return set_res # print(main("b5", "g3"))
def calculate_expression(expression): """ str -> int Return the result of arithmetic calculations in expression entered as text. >>> calculate_expression("Скільки буде 8 відняти 3?") 5 >>> calculate_expression("Скільки буде 7 додати 3 помножити на 5?") 22 >>> calculate_expression("Скільки буде 10 поділити на -2 додати 11 мінус -3?") 9 >>> calculate_expression("Скільки буде 3 в кубі?") 'Неправильний вираз!' """ spaces_number = 0 arr_of = ["додати", 'відняти', 'мінус', 'поділити на', 'помножити на'] for i in arr_of: num_of_spaces += expression.count(i) * 2 expression = expression.replace('Скільки буде ','') expression = expression.replace('додати','+') expression = expression.replace('відняти','-') expression = expression.replace('мінус','-') expression = expression.replace('поділити на','/') expression = expression.replace('помножити на','*') expression = expression.replace('?','') try: if num_of_spaces > expression.count(" "): return "Неправильний вираз!" res = eval(expression) return int(res) except: return "Неправильний вираз!"
import math def level(nodes): return math.ceil(math.log(nodes+1,2)) def leveltwo(nodes): if nodes > 0: return math.floor(math.log(nodes,2))+1 return 0 for i in range(20): print(str(i)+" nodes, level: "+str(level(i))+"function 2 says its level: "+str(leveltwo(i)))
import random import numpy as np class Network: # Input parameter # sizes: list in which each element is the number of neurons in each layer. def __init__(self, sizes): self.num_layers = len(sizes) self.sizes = sizes self.biases = [np.random.randn(y) for y in sizes[1:]] # There is one bias for each node, except for those in the input layer. self.weights = [np.random.randn(y, x) for x, y in zip(sizes[:-1], sizes[1:])] # Except for the input layer... # weights is a list of layers. Each layer has a list of nodes. # Each node has a list of input weights. There is a weight for each of the nodes from the previous layer. # E.g., weights[1] is a list containing the weights connecting the second layer to the third. # Returns the output of the neural net given an input, a. def feedforward(self, a): # The zip pairs the weights and biases for each layer # so we can get the output values for this layer. # We loop to feed forward all the way to the output. for w, b in zip(self.weights, self.biases): a = sigmoid(np.dot(w, a) + b) return a """Train the neural network using mini-batch stochastic gradient descent.""" # Input params: # training_data: a list of tuples "(x, y)" representing the # training inputs and the desired outputs. # epochs: number of "epochs" to train for. One epoch involves training over # the entire training data set. # batch_size: size of the batches to divide training_data into. # eta: learning rate. def SGD(self, training_data, epochs, batch_size, eta): n = len(training_data) for epoch in range(epochs): # Get the mini batches random.shuffle(training_data) mini_batches = [ training_data[k : k + batch_size] for k in range(0, n, batch_size) # increment by batch_size ] # Train on each mini batch for mini_batch in mini_batches: self.train_on_mini_batch(mini_batch, eta) print("Epoch {} complete".format(epoch)) """Update the network's weights and biases by applying gradient descent using backpropagation to a single mini batch.""" def train_on_mini_batch(self, mini_batch, eta): return ### Miscellaneous functions # Used by Network.feedforward # Takes as input wa+b for each node and applies the sigmoid # function to each element. # Returns a list of the final activation/output values for each node in # the layer. def sigmoid(a): # Operations on a numpy array are applied individually to each element. # So this will return a list of elements with the operations below # applied individually to each element. # The list is for a whole layer, consists of the output values for # each node. return 1.0/(1.0 + np.exp(-a))
class Restaurant: def __init__(self, seatings): self.seatings = seatings self.tables = [None for _ in range(0, seatings)] def seat(self, guest): is_table_available = not all(self.tables) if is_table_available: idx = next(i for i, t in enumerate(self.tables) if t is None) print('Seating guest {} at table {}'.format(guest.name, idx)) self.tables[idx] = guest else: print('No free table!') return is_table_available def serve(self): is_somebody_seating = any(self.tables) if is_somebody_seating: idx = next(i for i, t in enumerate(self.tables) if t is not None) print('Serving guest {}'.format(self.tables[idx].name)) if not self.tables[idx].eat(): self.tables[idx] = None else: print('No guest to serve!')
n=int(input('Enter num: ')) if n%2!=0: for i in range (1,n+1): for j in range (1,n+1): if (i==n//2+1 or j==n//2+1): print('*',end=' ') else: print(' ',end=' ') print() else: print('Entered wrong input') ''' Enter num: 7 * * * * * * * * * * * * * Enter num: 6 Entered wrong input '''
candies=list(map(int,input().split())) a=[] extra_c=int(input('Enter extra candies:')) for i in candies : if i+extra_c>=max(candies): a.append(True) else: a.append(False) print(a) ''' 2 4 1 5 3 Enter extra candies:3 [True, True, False, True, True] '''
n=int(input('Enter an odd num: ')) if n%2!=0: for i in range(1,n+1): for j in range(1,n+1): if(i==1 or i==n or i==n//2+1 or j==1 or j==n or j==n//2+1): print('*',end=' ') else: print(' ',end=' ') print() else: print('You have entered wrong number') ''' Enter an odd num: 7 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Enter an odd num: 8 You have entered wrong number '''
# 打开文件:open() # 输入:read() # 输入一行: readline() # 文件内移动 seek() # 输出write() # 关闭文件close() # file1 = open('name.txt', 'w') # file1.write('ddddd') # file1.close() # # file2 = open('name.txt') # print(file2.read()) # file2.close() # # file3 = open('name.txt', 'a') # file3.write('bbbb') # file3.close() file4 = open('name.txt') print(file4.readline()) # file5 = open('name.txt') # for line in file5.readlines(): # print(line) # 指定文件已什么编码方式打开 f3 = open('name.txt', encoding='GB18030') # 指针 file6 = open('name.txt') print('当前文件指针的位置 %s' %file6.tell()) print('当前读取到了一个字符,字符的内容是 %s' %file6.read(1)) print('当前文件指针的位置 %s' %file6.tell()) # 第一个参数代表偏移位置,第二个参数表示从文件开头偏移 file6.seek(5,0) print('我们进行了seek操作') print('当前文件指针的位置 %s' %file6.tell()) print('当前读取到了一个字符,字符的内容是 %s' %file6.read(1)) file6.close()
#列表 l = [3, 2, 3, 7, 8, 1] print(l.__sizeof__()) l.count(3) #2 表示统计列表 / 元组中 item 出现的次数 l.index(7) #3 index(item) 表示返回列表 / 元组中 item 第一次出现的索引 # list.reverse() 和 list.sort() 分别表示原地倒转列表和排序(注意,元组没有内置的这两个函数)。 l.reverse() #l [1, 8, 7, 3, 2, 3] l.sort() #l [1, 2, 3, 3, 7, 8] # 元组 tup = (3, 2, 3, 7, 8, 1) tup.count(3) #2 tup.index(7) #3 # reversed() 和 sorted() 同样表示对列表/ 元组进行倒转和排序但是会返回一个倒转后或者排好序的新的列表 / 元组。 list(reversed(tup)) #[1, 8, 7, 3, 2, 3] sorted(tup) #[1, 2, 3, 3, 7, 8] print(7 in tup) l = ['a333', 's33', 's33'] print(l.__sizeof__()) # 字典 d1 = {'name': 'jason', 'age': 20, 'gender': 'male'} d2 = dict({'name': 'jason', 'age': 20, 'gender': 'male'}) d3 = dict([('name', 'jason'), ('age', 20), ('gender', 'male')]) d4 = dict(name='jason', age=20, gender='male') # 集合 s1 = {1, 2, 3} # d1[0] || s1[0] 报错,不支持索引 print('ss' in s1) s2 = set([1, 2, 3]) # 字典和集合支持增删改等操作 d = {'name': 'jason', 'age': 20} d['gender'] = 'male' # 增加元素对'gender': 'male' d['dob'] = '1999-02-01' # 增加元素对'dob': '1999-02-01' #d{'name': 'jason', 'age': 20, 'gender': 'male', 'dob': '1999-02-01'} d['dob'] = '1998-01-01' # 更新键'dob'对应的值 d.pop('dob') # 删除键为'dob'的元素对 #'1998-01-01' #d{'name': 'jason', 'age': 20, 'gender': 'male'} s = {1, 2, 3} s.add(4) # 增加元素 4 到集合 #s{1, 2, 3, 4} s.remove(4) # 从集合中删除元素 4 #s{1, 2, 3} d = {'name': 'jason', 'education': ['Tsinghua University', 'Stanford University']} print(d)
# Pandas库数据预处理和清洗 # pip3 install pandas 安装命令 import numpy as np from numpy import nan from pandas import Series, DataFrame # 最重要的库 import pandas as pd # series基本操作 data = Series([4, 5, 6, 7]) print(data) # 输出结果,第一位为索引位置 # 0 4 # 1 5 # 2 6 # 3 7 # dtype: int64 print(data.index) # RangeIndex(start=0, stop=4, step=1) print(data.values) # [4 5 6 7] # 指定索引 obj = Series([4, 7, -6, 3], index=['a', 'b', 'c', 'd']) obj['a'] = 6 print(obj) print('f' in obj) # 判断f是否在index索引中 # 字典转换成series sdata = {'a': 100, 'b': 200, 'c': 300, 'd': 400} obj2 = Series(sdata) print(obj2) obj2.index = ['ab', 'cd', 'ef', 'hh'] print(obj2) # DataFrame基本操作 frame = { 'city': ['hangzhou', 'shanghai', 'shenzheng', 'gaungzhou', 'huzhou'], 'year': [2020, 2019, 2016, 2017, 2003], 'date': [2, 3, 1, 7, 5] } frame_data = DataFrame(frame) print(frame_data) # 输出类似与电子表格 # 根据columns内的字段将frame内的数据先后输出 frame2 = DataFrame(frame, columns=['year', 'date', 'city']) print(frame2) # 提取某个具体一列 print(frame2['city']) print(frame2.year) # 生成新的一列 frame2['new'] = [1, 2, 3, 4, 5] print(frame2) frame2['new2'] = frame2.city == 'hangzhou' print(frame2) # 行列索引对换 pop = { 'hangzhou': {2008: 1.5, 2009: 1.4}, 'huzhou': {2009: 3.3, 2008: 3.6} } frame3 = DataFrame(pop) print(frame3) print(frame3.T) # 填充数值 obj3 = Series([4, 5, 6, 7], index=['a', 'b', 'c', 'd']) obj4 = obj3.reindex(['a', 'b', 'c', 'd', 'e'], fill_value=10) # 重新指定索引 print(obj4) obj5 = Series(['blue', 'red', 'yellow'], index=[0, 2, 4]) print(obj5.reindex(range(6), method='ffill')) # method指定填充内容,'ffill'用上面的数据填充 # 删除缺失数据 data_nan = Series([1, nan, 2]) print(data_nan.dropna()) data_frame = DataFrame([[1, 2, 4], [1, nan, 3], [nan, nan, nan]]) print(data_frame.dropna()) # 删除所有出现nan的地方 print(data_frame.dropna(how='all')) # 只删除有全部nan的地方 data_frame[4] = nan print(data_frame) print(data_frame.dropna(axis=1, how='all')) # 删除整列都是nan # 填充为na的地方 print(data_frame.fillna(99)) print(data_frame.fillna(88, inplace=True)) # 层次化索引 data1 = Series(np.random.randn(10), index=[['a', 'a', 'a', 'b', 'b', 'b', 'c', 'c', 'd', 'd'], [1, 2, 3, 1, 2, 3, 1, 2, 3, 4]]) print(data1) print('--------------') print(data1['b']) print('--------------') print(data1['a':'c']) print('--------------') print(data1.unstack()) # 一维转换成二维 print(data1.unstack().stack()) # 二维转换成一维
def sieve(n): not_prime = [] prime = [] for i in xrange(2, n+1): if i not in not_prime: prime.append(i) for j in xrange(i*i, n+1, i): not_prime.append(j) return prime print "Till which integer you want to do the primality test?" x = int(raw_input(">")) print sieve(x)
import random print ("===============BEM AO VINDO AO JOKENPÔ================") print(''' [ 1 ] JOGAR [ 2 ] REGRAS [ 3 ] SAIR ''') opcao = int(input("")) if opcao == 3: exit (1) if opcao == 2: print ('''[ Pedra ganha da tesoura (amassando-a ou quebrando-a) ] [ Tesoura ganha do papel (cortando-o) ] [ Papel ganha da pedra (embrulhando-a ]\n''') else: jogada = 'pedra', 'papel', 'tesoura' sair = 'y' v_p1 = 0 v_com = 0 print("Digite SAIR a qualquer momento") while (sair != 'sair'): p1 = str(input("Qual sua jogada: Pedra, Papel ou Tesoura: ")).strip().lower() if p1 == 'sair': break while (p1 != 'pedra' and p1 != 'papel' and p1 != 'tesoura'): print ("Jogada inválida!!! Escolha pedra, papel ou tesoura") p1 = str(input("Qual sua jogada: Pedra, Papel ou Tesoura: ")).strip().lower() com = random.choice(jogada) print ("=+"*20) print (f"Você jogou {p1}") print(f"O computador jogou {com}") if p1 == 'pedra': if com == 'pedra': print('Empate') if com == 'papel': print(':( Você perdeu essa mas pode tentar de novo ):') v_com += 1 if com == 'tesoura': print('Você ganhou !!!') v_p1 += 1 #print("\n") elif p1 == 'papel': if com == 'papel': print('Empate') if com == 'tesoura': print(':( Você perdeu essa mas pode tentar de novo ):') v_com += 1 if com == 'pedra': print('Você ganhou !!!') v_p1 += 1 #print("\n") elif p1 == 'tesoura': if com == 'tesoura': print('Empate') if com == 'pedra': print(':( Você perdeu essa mas pode tentar de novo ):') v_com += 1 if com == 'papel': print('Você ganhou !!!') v_p1 += 1 print ("=+"*20) print("\n") print (f"Você ganhou {v_p1} vezes e o computador ganhou {v_com} vezes\n")
salario = float(input("Digite o salário do funcionário: ")) if salario>1250: aumentado = salario*1.10 else: aumentado = salario*1.15 print ("O salário do funcionário com aumento é igual a: R$ {:.2f}".format(aumentado))
celsius = float(input("Digite a temperatura em °C: ")) fahrenheit =( ((celsius * 9)/5)+32 ) print (f"A temperatura {celsius:.1f}°C equivale a {fahrenheit:.1f}°F")
import emoji import math num = int(input("Digite num: ")) print (f"A raiz de {num} = {math.sqrt(num):.2f}") print(emoji.emojize('Python is :thumbs_up:', use_aliases=True))
num = int(input("Digite o numero a ser convertido: ")) print('''Escolha a base para qual deseja converter: [ 2 ] Binário [ 8 ] Octal [ 16 ] Hexadecimal ''') base = int(input("Base a qual deseja converter: ")) while base != 2 and base != 8 and base != 16: print("\nVocê escolheu uma opção inválida!!!") base = int(input("Escolha entre base 2, base 8 ou base 16: ")) numero = num # armazena o numero para ser utilizado no print i = 0 resto = [] if base == 2: while (num >= 2): resto.append(num % 2) num = num // 2 i += 1 print(f"O numero {numero} em binário é representado por: ", end='') binario = str(num) k = len(resto) while (k != 0): binario += str(resto[k-1]) k = k-1 print(binario) print("\n") i = 0 resto = [] if base == 8: while (num >= 8): resto.append(num % 8) num = num // 8 i += 1 print(f"O numero {numero} em octal é representado por: ", end='') octal = str(num) k = len(resto) while (k != 0): octal += str(resto[k-1]) k = k-1 print(octal) print("\n") i = 0 resto = [] if base == 16: while (num >= 16): resto.append(num % 16) num = num // 16 i += 1 print(f"O numero {numero} em hexadecimal é representado por: ", end='') hexa = str(num) k = len(resto) while (k != 0): hexa += str(resto[k-1]) k = k-1 hexa = hexa.replace('10', 'A') hexa = hexa.replace('11', 'B') hexa = hexa.replace('12', 'C') hexa = hexa.replace('13', 'D') hexa = hexa.replace('14', 'E') hexa = hexa.replace('15', 'F') print(hexa) print("\n")
from datetime import date ano = int(input('Digite o ano que deseja saber se é bissexto: ')) if ano == 0: date.today().year if ano%100 == 0 and ano%4 == 0: print ("Ano não bissexto\n") else: if ano%4 != 0: if ano%400 != 0: print ("Ano não bissexto\n") else: print ("Ano bissexto\n") else: print ("Ano bissexto\n")
test = input ("Digite alguma coisa: ") print ("O tipo primitivo desse valor é", type(test)) if test.isspace(): print ("O seu texto só possui espaços ") if test.isnumeric(): print ("Você digitou um numero") if test.isalpha(): print ("Você digitou uma letra ou frase") if test.isupper(): print ("O seu texto está em MAISCULO") if test.islower(): print ("O seu texto está em MINUSCULO") if test.isalnum(): print ("Você digitou uma frase que possui numeros e ou letras") else : print ("Você não digitou nada ou o texto não contém numeros ou letras")
nome = (str(input("Digite seu nome completo: "))).strip() print ("Nome em maiúsculo: ", nome.upper()) print ("Nome em minúsculo: {}".format(nome.lower())) #separa o nome em razão do espaço entre as palavras, logo após junta sem espaços e calcula o length print (f'Tamanho do nome, sem contar espaços: {len("".join(nome.split()))} letras') #a lista p recebe os nomes separados com p[0] sendo o primeiro nome p = nome.split() print(f"Seu primeiro nome é: {p[0]} e ele possui {len(p[0])} letras \n" )
form = dict() # formulario para cada pessoa cadastro = list() while True: print() form['Nome'] = str(input('Nome da pessoa: ')) sexo = str(input("Sexo[M/F]: ")).upper().strip() while sexo not in 'MF': print('\033[31;1m'+'Responda apenas M ou F !!'+'\033[0;0m') sexo = str(input("Sexo[M/F]: ")).upper().strip() form['Sexo'] = sexo form['Idade'] = int(input("Idade: ")) cadastro.append(form.copy()) add = str(input("Cadastrar mais pessoas[S/N]? ")).upper().strip() while add not in 'SN': print('\033[31;1m'+"Responda apenas S ou N !!"+'\033[0;0m') add = str(input("Cadastrar mais pessoas[S/N]? ")).upper().strip() if add == 'N': break print("\n") print("=-"*30) print(f"Foram cadastradas {len(cadastro)} pessoas") soma_idade = 0 for pessoas in cadastro: soma_idade += pessoas['Idade'] media = soma_idade / len(cadastro) print(f"A média de idade dessas pessoas é {media:.2f} anos") print("=-"*30) print("As mulheres cadastradas são: ") for pessoa in cadastro: if pessoa['Sexo'] == 'F': print(f"{pessoa['Nome']}, {pessoa['Idade']} anos") print("=-"*30) print("Os homens cadastrados são: ") for pessoa in cadastro: if pessoa['Sexo'] == 'M': print(f"{pessoa['Nome']}, {pessoa['Idade']} anos") print("=-"*30) print("Pessoas com idade acima da média: ") for pessoa in cadastro: if pessoa['Idade'] > media: print(f"{pessoa['Nome']}, {pessoa['Sexo']}, {pessoa['Idade']} anos")
import math num = float(input("Digite um numero qualquer: ")) print ("A parte inteira desse numero é {}".format(math.trunc (num)))
nome = [] idade = [] sexo = [] soma = 0 maior = 0 mulh_menos_vinte = 0 nome_mais_velho = '' for i in range (1, 5): print ("-"*5, i, "ª PESSOA","-"*5) nome.append(str(input("Qual o nome da pessoa: ").strip())) idade.append(int(input("Qual a idade da pessoa: "))) sexo.append(str(input("Qual o sexo da pessoa [m ou f]: ").lower().strip())) print ("\n") soma += idade[i-1] if idade[i-1] > maior and sexo[i-1] == 'm': maior = idade[i-1] nome_mais_velho = nome[i-1] idade_m_velho = idade[i-1] if idade[i-1] < 20 and sexo[i-1] == 'f': mulh_menos_vinte += 1 if mulh_menos_vinte == 1: s = '' else: s = 'es' print ("A média de idade do grupo é:", soma/len(idade),"anos") if nome_mais_velho != '': print ("O homem mais velho é:", nome_mais_velho, "com", idade_m_velho,"anos") else: print("Não foi cadastrado nenhum homem") print(f"Há no grupo {mulh_menos_vinte} mulher{s} com menos de 20 anos") print ("\n")
import random num_alunos = (int(input("Quantos alunos irão participar: "))) num_sorteados = (int(input("Quantos alunos deseja sortear: "))) i = 0 alunos = [] for i in range (1,num_alunos+1): alunos.append (input(f"Digite o nome do aluno {i}: ")) selected = random.sample (alunos, k=num_sorteados) ordem = 1 print ("\nOrdem de apresentação:") for k in selected: print (f"{ordem}°: {k} \n") ordem +=1
from datetime import date dia_nasc = int(input("Qual o dia de nascimento do atleta? ")) mes_nasc = int(input("Qual o mês de nascimento do atleta? (em numero): ")) ano_nasc = int(input("Qual o ano de nascimento do atleta? ")) ano_atual = int(date.today().year) mes_atual = int(date.today().month) dia_hoje = int(date.today().day) idade = ano_atual-ano_nasc if mes_atual < mes_nasc: idade = idade - 1 if mes_atual == mes_nasc and dia_hoje < dia_nasc: idade = idade - 1 if idade <= 9: print(f"O atleta tem {idade} anos e está na categoria MIRIM") elif idade <= 14: print(f"O atleta tem {idade} anos e está na categoria INFANTIL") elif idade <= 19: print(f"O atleta tem {idade} anos e está na categoria JUNIOR") elif idade <= 25: print(f"O atleta tem {idade} anos e está na categoria SÊNIOR") else: print(f"O atleta tem {idade} anos e está na categoria MASTER")
usertime = float(input("Tell me a word in english: ")) if usertime = cat: print("gato") elif usertime = dog: print("perro") elif usertime = horse: print("caballo") else print("no entiendo")
# Check memory with sys.getsizeof() import sys mylist = range(0, 10000) print(sys.getsizeof(mylist)) # Woah… wait… why is this huge list only 48 bytes? # It’s because the range function returns a class that only behaves like a list. A range is a lot more memory efficient than using an actual list of numbers. # You can see for yourself by using a list comprehension to create an actual list of numbers from the same range: myreallist = [i for i in range(0, 10000)] print(sys.getsizeof(myreallist))
""" Students have become secret admirers of SEGP. They find the course exciting and the professors amusing. After a superb Mid Semester examination its now time for the results. The TAs have released the marks of students in the form of an array, where arr[i] represents the marks of the ith student. Since you are a curious kid, you want to find all the marks that are not smaller than those on its right side in the array. Input Format The first line of input will contain a single integer n denoting the number of students. The next line will contain n space separated integers representing the marks of students. Output Format Output all the integers separated in the array from left to right that are not smaller than those on its right side. """ l1 = [16, 17, 4, 3, 5, 2, 29, 8, 1, 4, 2, 5] def bigger_than_right(l1): bigger = [] index = 0 for grade in l1: for i in range(index+1, len(l1)): if grade <= l1[i]: print(grade, " is smaller than ", l1[i]) break if i == len(l1) - 1 and grade >= l1[i]: bigger.append(grade) index = index + 1 bigger.append(grade) return bigger print(bigger_than_right(l1))
#!/usr/bin/python import RPi.GPIO as GPIO import time import requests #GPIO SETUP sensor_pin = 20 relay_pin = 21 GPIO.setmode(GPIO.BCM) GPIO.setup(sensor_pin, GPIO.IN) GPIO.setup(relay_pin, GPIO.OUT) # test the sensor to find out if the soil is moist def get_sensor(sensor_pin): # see if sensor has detected moisture if GPIO.input(sensor_pin): r = False else: r = True # returns true or false return r def turn_on(relay_pin): GPIO.output(relay_pin, GPIO.LOW) # out GPIO.output(relay_pin, GPIO.HIGH) # on def turn_off(relay_pin): GPIO.output(relay_pin, GPIO.LOW) # out GPIO.output(relay_pin, GPIO.LOW) # off # a stupid way to do a loop def main(): while True: # checks the sensor if moisture level is over the specific limit result = get_sensor(sensor_pin) if result == True: # if water is detected then it will make sure the relay is off print("Water Detected") turn_off(relay_pin) # time to wait in seconds time.sleep(10) else: # if no moisture is detected it will turn the relay on print("No Water Detected") turn_on(relay_pin) # how long the relay is on for till it reaccesses the situation time.sleep(10) main()
""" argdeco.main -- the main function This module provides :py:class:`~argdeco.main.Main`, which can be used to create main functions. For ease it provides common arguments like `debug`, `verbosity` and `quiet` which control whether you want to print stacktraces, and how verbose the logging is. These arguments will not be passed to command handlers or main function handler. Usually you will import the global main instance provided in argdeco:: from argdeco import main In this case, `main.command` is also provided as global symbol:: from argdeco import main, command @main.command(...) def cmd(...): ... # is equivalent to @command(...) def cmd(...): ... Bug you can also create an own instance:: from argdeco.main import Main main = Main() @main.command('foo', ...) def my_cmd(...): ... If you want to make use of the predefined (global) args:: if __name__ == '__main__': main(verbosity=True, debug=True, quiet=True) """ import argdeco.command_decorator as command_decorator import sys, logging from inspect import isfunction import argparse import os from os.path import expanduser from .arguments import arg from .command_decorator import NoAction PY3 = sys.version_info > (3, 0) try: an_exception = StandardError except: an_exception = Exception class ArgParseExit(an_exception): def __init__(self, error_code, message): self.error_code=error_code self.message = message def __str__(self): if self.message: return self.message.strip() else: return '' class Main: """Main function provider An instance of this class can be used as main function for your program. It provides a :py:attribute: :param debug: Set True if you want main to manage the debug arg. (default: False). Set global logging levels to DEBUG and print out full exception stack traces. :param verbosity: Control global logging log levels (default: False) If this is turned on, default log level will be set to ``ERROR`` and following argument are provided: .. option:: -v, --verbose set log level to level ``WARNING`` .. option:: -vv, -v -v, --verbose --verbose Set log level to level ``INFO`` .. option:: -vvv, -v -v -v Set log level to level ``DEBUG`` :param quiet: If you set this to ``True``, argument :option:`--quiet` will be added: .. option:: --quiet If this option is passed, global log level will be set to ``CRITICAL``. :param command: CommandDecorator instance to use. This defaults to None, and for each main instance there will be created a :py:class:`~argdeco.command_decorator.CommandDecorator` instance. :param compile: This parameter is passed :py:class:`~argdeco.command_decorator.CommandDecorator` instance and controls, if arguments passed to handlers are compiled in some way. :param compiler_factory: This parameter is passed :py:class:`~argdeco.command_decorator.CommandDecorator` instance and defines a factory function, which returns a compile function. You may either use ``compile`` or ``compiler_factory``. :param log_format: This parameter is passed to :py:func:`logging.basicConfig` to define log output. (default: ``"%(name)s %(levelname)s %(message)s"``) :param error_code: This is the error code to be returned on an exception (default: 1). :param error_handler: Pass a function, which handles errors. This function will get the error code returned from a command (or main) function and do something with it. Default is :py:func:`sys.exit`. If you do not want to exit the program after running the main funtion you have to set ``error_handler`` to ``None``. If you want to access the managed arguments (quiet, verbosity, debug), you can access them as attributes of the main instance:: if not main.quiet: print("be loud") if main.debug: print("debug is on") """ def __init__(self, debug = False, verbosity = False, quiet = False, compile = None, compiler_factory = None, command = None, log_format = "%(name)-20.20s %(levelname)-10.10s %(message)s", error_handler = sys.exit, error_code = 1, catch_exceptions = (SystemError, AssertionError, ArgParseExit), **kwargs ): # initialize logging logging.basicConfig(format=log_format) logger = logging.getLogger() logger.setLevel(logging.ERROR) # initialize error_handler and error_code self.error_handler = error_handler self.error_code = error_code # initialize managed argument indicators self.arg_debug = debug self.arg_quiet = quiet self.arg_verbosity = verbosity self.debug = False self.verbosity = 0 self.quiet = False self.print_traceback = False # #self.compiled_args = compiled # initialize command if command is None: command = command_decorator.factory(**kwargs) #if command_decorator.command_inst is None: #command_decorator.command_inst = \ #command_decorator.factory(**kwargs) # #command = command_decorator.command_inst self.command = command self.compile = compile self.compiler_factory = compiler_factory self.main_function = None self.catch_exceptions = catch_exceptions def configure(self, debug=None, quiet=None, verbosity=None, traceback=None, compile=None, compiler_factory=None, catch_exceptions=None, **kwargs): """configure behaviour of main, e.g. managed args """ if debug is not None: self.arg_debug = debug if quiet is not None: self.arg_quiet = quiet if verbosity is not None: self.arg_verbosity = verbosity if compile is not None: self.compile = compile if compiler_factory is not None: self.compiler_factory = compiler_factory if traceback is not None: self.print_traceback = traceback if catch_exceptions is not None: self.catch_exceptions = catch_exceptions if kwargs: # other keyword arguments update command attribute self.command.update(**kwargs) def init_managed_args(self): logger = logging.getLogger() _main = self _main.verbosity = 0 if self.arg_debug: @arg('--debug', help="print debug output", metavar='', nargs=0) def debug_arg(self, parser, namespace, values, option_string=None): _main.debug = True logger.setLevel(logging.DEBUG) try: self.command.add_argument(debug_arg) except argparse.ArgumentError: pass if self.arg_verbosity: @arg('-v', '--verbosity', help="verbosity: set loglevel -v warning, -vv info, -vvv debug", nargs=0, metavar=0) def verbosity_arg(self, parser, namespace, values, option_string=None): _main.verbosity += 1 if _main.verbosity == 1: logger.setLevel(logging.WARNING) if _main.verbosity == 2: logger.setLevel(logging.INFO) if _main.verbosity == 3: logger.setLevel(logging.DEBUG) try: self.command.add_argument(verbosity_arg) except argparse.ArgumentError: pass if self.arg_quiet: @arg('--quiet', help="have no output", metavar='', nargs=0) def quiet_arg(self, parser, namespace, values, option_string=None): logger.setLevel(logging.CRITICAL) _main.quiet = True try: self.command.add_argument(quiet_arg) except argparse.ArgumentError: pass def store_args(self, args): if self.arg_debug: del args.debug if self.arg_quiet: del args.quiet if self.arg_verbosity: del args.verbosity self.args = args logger = logging.getLogger('argdeco.main') logger.debug("args: %s", args) if not hasattr(args, 'action'): if self.main_function: args.action = self.main_function else: raise NoAction("You have to specify an action by either using @command or @main decorator") def uninstall_bash_completion(self, script_name=None, dest="~/.bashrc"): '''remove line to activate bash_completion for given script_name from given dest You can use this for letting the user uninstall bash_completion:: from argdeco import command, main @command("uninstall-bash-completion", arg('--dest', help="destination", default="~/.bashrc") ) def uninstall_bash_completion(dest): main.uninstall_bash_completion(dest=dest) ''' if 'USERPROFILE' in os.environ and 'HOME' not in os.environ: os.environ['HOME'] = os.environ['USERPROFILE'] dest = expanduser(dest) if script_name is None: script_name = sys.argv[0] lines = [] remove_line = 'register-python-argcomplete %s' % script_name with open(dest, 'r') as f: for line in f: if line.strip().startswith('#'): lines.append(line) continue if remove_line in line: continue lines.append(line) with open(dest, 'w') as f: f.write(''.join(lines)) def install_bash_completion(self, script_name=None, dest="~/.bashrc"): '''add line to activate bash_completion for given script_name into dest You can use this for letting the user install bash_completion:: from argdeco import command, main @command("install-bash-completion", arg('--dest', help="destination", default="~/.bashrc") ) def install_bash_completion(dest): main.install_bash_completion(dest=dest) ''' if 'USERPROFILE' in os.environ and 'HOME' not in os.environ: os.environ['HOME'] = os.environ['USERPROFILE'] dest = expanduser(dest) if script_name is None: script_name = sys.argv[0] self.uninstall_bash_completion(script_name=script_name, dest=dest) with open(dest, 'a') as f: f.write('eval "$(register-python-argcomplete %s)"\n' % script_name) def add_arguments(self, *args): """Explicitely add arguments:: main.add_arguments( arg('--first'), arg('--second') ) This function wraps :py:meth:`argdeco.command_decorator.C` :param \*args: arguments to be added. """ self.command.add_arguments(*args) def __call__(self, *args, **kwargs): """ You can call :py:class:`~argdeco.main.Main` instance in various ways. As function or as decorator. As long you did not have decorated a function with this :py:class:`~argdeco.main.Main` instance, you can invoke it as function for confiugration. As soon there is defined some action, invoking the instance, will execute the actions. Configure some global arguments:: main( arg('--global', '-g', help="a global argument"), ) Decorate a function to be called as main function:: @main def my_main(): return 0 if __name__ == "__main__": main() Decorate a function to be main function and define arguments of it:: @main( arg('--first', '-f', help="first argument"), arg('--second', '-s', help="second argument"), ) def main(first, second): return 0 # successful if __name__ == "__main__": main(debug=True) :param \*args: All arguments of type :py:class:`~argdeco.command_decorator.arg` are filtered out and added as global argument to underlying :py:class:`~argdeco.command_decorator.CommandDecorator` instance. All other arguments are collected -- if any to be `argv`. If there are any other parameters, this function switches into regular `main` mode and will execute the main function passing `argv`. If there are no arguments defined, :py:attr:`sys.argv` is used as default. :param \*\*kwargs: You can pass various keyword arguments to tweak behaviour of the main function. :argv: You can set explicitly the ``argv`` vector. This becomes handy, if you want to pass an empty ``argv`` list and do not want to use the default sys.argv. :debug: Turn on debug argument, see :py:class:`~argdeco.main.Main` for more info. :verbosity: Turn on verbose argument, see :py:class:`~argdeco.main.Main` for more info. :quiet: Turn on quiet argument, see :py:class:`~argdeco.main.Main` for more info. :error_handler: Tweak the error handler. This will be only local to this call. :compile: Set compile for this call. :compiler_factory: Set compiler_factory for this call. :return: :Decorator mode: Returns the instance itself, to be invoked as decorator. :Run mode: Returns whatever error_handler returns, when getting the return value of the invoked action function """ error_handler = kwargs.pop('error_handler', self.error_handler) compile = kwargs.pop('compile', self.compile) compiler_factory = kwargs.pop('compiler_factory', self.compiler_factory) def default_error_handler(result): if isinstance(result, int): return result if result is False: return self.error_code return 0 if error_handler is None: error_handler = default_error_handler if hasattr(self, 'arg_debug') and 'debug' in kwargs: setattr(self, 'arg_debug', kwargs.pop('debug')) if hasattr(self, 'arg_verbosity') and 'verbosity' in kwargs: setattr(self, 'arg_verbosity', kwargs.pop('verbosity')) if hasattr(self, 'arg_quiet') and 'quiet' in kwargs: setattr(self, 'arg_quiet', kwargs.pop('quiet')) argv=None if 'argv' in kwargs: argv = kwargs.pop('argv') # other keyword arguments update command attribute self.command.update(**kwargs) # set a custom exit function def _exit(result=0, message=None): raise ArgParseExit(result, message) #return error_handler(result) self.command.update(exit=_exit) # handle case if called as decorator if len(args) == 1 and isfunction(args[0]): self.main_function = args[0] return args[0] # filter out argument definitions from posional arguments and create # argv list, if any for a in args: if isinstance(a, arg): self.command.add_argument(a) else: if argv is None: argv = [] argv.append(a) # if there were no argv args and there is not yet defined a main, # function defined and there are no commands defined yet. Return # this object, that there may be defined a function in a subsequent # call (this is the case if @main(args...) is used). if argv is not None and self.main_function is None and not self.command.has_action(): raise ValueError("Main cannot handle any arguments, when main_function is not yet defined") # at this point we are still in decorating mode if argv is None and self.main_function is None and not self.command.has_action(): return self self.exception = None # right before doing the command execution add the managed args self.init_managed_args() try: return error_handler(self.command.execute(argv, compile=compile, preprocessor=self.store_args, compiler_factory=compiler_factory)) except self.catch_exceptions as e: logger = logging.getLogger() logger.debug("caught exception (self.debug: %s)", self.debug, exc_info=1) if self.verbosity or self.print_traceback: import traceback traceback.print_exc() elif not self.quiet: if PY3: sys.stderr.write("%s\n" % e) else: sys.stderr.write((u"%s\n" % e).encode('utf-8')) self.exception = e if hasattr(e, 'error_code'): return error_handler(e.error_code) else: return error_handler(self.error_code)
from XmlGenerator import XmlGenerator from CalculateAlpha import CalculateAlpha import math class Controller (object): """ Controller acts as the singleton class that hides implementation details of the alpha and pi. It generates the XML file and create DTD. In encapsulate the object of class CalculateAlpha """ def get_length(self): """ This method takes radius as an input from the user and computes the distance and return it as the output """ try: # Taking radius as input from the user radius = float(input("Enter the radius of the circle :")) # Calculating the distance using the formula l = 2R(1 – cos(α/2)) distance = 2 * radius * (1 - math.cos(alpha_calculator.get_alpha() / 2.0)) print("The length of the segment X1-X2 is", distance, "units") xml = XmlGenerator() xml.generate_xml(radius, distance) xml.create_dtd() print("XML and DTD has been created") return distance # Handling Exception except Exception as e: print("Error, There is an exception", e) alpha_calculator = CalculateAlpha() controller = Controller() controller.get_length()
class calculator(): def __init__(self): self.user_input1 = 0 self.user_input2 = 0 self.calc_total = 0 self.running = True def ask_user_input(self): user_input_1 = int(input('Enter a number: ')) self.input1 = user_input_1 user_input_2 = int(input('Enter a number: ')) self.input2 = user_input_2 def multiplication(self): m = self.calc_total = self.input1 * self.input2 return ("Multiplication result: ", m) def addition(self): a = self.calc_total = self.input1 + self.input2 return ("Addition result: ", a) def subtraction(self): s = self.calc_total = self.input1 - self.input2 return ("Subtraction result: ", s) def division(self): d = self.calc_total = self.input1 / self.input2 return ("Division result: ", d) def main(self): while self.running == True: self.ask_user_input() print(self.multiplication()) print(self.addition()) print(self.subtraction()) print(self.division()) self.calculate_again() def calculate_again(self): again = input("y/n: ") if again == "y": self.main() elif again =="n": print("goodbye...") play = calculator() play.main() #play.user_input1 #check input #play.user_input2 #check input
# -*- coding: utf-8 -*- """ mnist_loader ----------------------------- A library to load the MNIST image data. For detail of the data structures that ara returned, see the doc string for "load_data" and "load_data_wrapper". In practice "load_data_wrapper" is the function usually by our neural network code """ import pickle import gzip import numpy def load_data(dataName): f = gzip.open(dataName, 'rb') training_data,validation_data,test_data=pickle.load(f,encoding="iso-8859-1") f.close() return(training_data,validation_data,test_data) def load_data_wrapper(dataName): tr_d,va_d,te_d = load_data(dataName) training_inputs = [numpy.reshape(x,(784,1)) for x in tr_d[0]] training_results = [vectorized_results(y) for y in tr_d[1]] training_data = list(zip(training_inputs,training_results)) validation_inputs = [numpy.reshape(x,(784,1)) for x in va_d[0]] validation_data = list(zip(validation_inputs,va_d[1])) test_inputs = [numpy.reshape(x,(784,1)) for x in te_d[0]] test_data = list(zip(test_inputs,te_d[1])) print('%d train, %d test, %d validation' % (len(training_inputs), len(test_inputs), len(validation_inputs))) return(training_data,validation_data,test_data) def vectorized_results(j): e = numpy.zeros((10,1)) e[j] = 1.0 return e # try: # training_data, validation_data, test_data = load_data_wrapper() # except Exception as e: # pass
from tetris_lookahead import possible_locations from tetris_board import * def score(board, hold, queue, active, can_hold, board_func, place_func, depth): if depth == 0: return board_func(board) moves = [] for x, y, s, m in possible_locations(TetrisPiece(active, 4, 19, 0), board): test_board = TetrisBoard(board.width, board.height) test_board.board = [line[:] for line in board.board] new_piece = TetrisPiece(active, x, y, s) h = place_func(test_board, new_piece) test_board.piece_add(new_piece) test_board.check_clear() moves.append((test_board, h, 'move')) if can_hold: moves.append((board, 0, 'hold')) record = None for test_board, h, action in moves: if action == 'move': s = h + score(test_board, hold, queue[1:], queue[0], True, board_func, place_func, depth - 1) elif action == 'hold': s = score(board, active, queue, hold, False, board_func, place_func, depth - 1) if record is None or s > record: record = score return record
import MapReduce import sys """ Assymetric Relationships in the Simple Python MapReduce Framework """ mr = MapReduce.MapReduce() # ============================= # Do not modify above this line # Implement the MAP function def mapper(record): # YOUR CODE GOES HERE ori_record=record[:] record.sort() key = "{} {}".format(str(record[0]),str(record[1])) value = ori_record mr.emit_intermediate(key, value) # Implement the REDUCE function def reducer(key, list_of_values): # YOUR CODE GOES HERE if len(list_of_values) == 1: mr.emit((list_of_values[0][1], list_of_values[0][0])) # Do not modify below this line # ============================= if __name__ == '__main__': inputdata = open(sys.argv[1]) mr.execute(inputdata, mapper, reducer)
# iamprudhvi class BSTNode: def __init__(self, data=None): self.data = data self.left = None self.right = None def insert_node(root, data): if root is None: node = BSTNode(data) root = node else: if data < root.data: if root.left is None: node = BSTNode(data) root.left = node else: insert_node(root.left, data) else: if root.right is None: node = BSTNode(data) root.right = node else: insert_node(root.right, data) def inorder(root): if not root: return else: inorder(root.left) print(root.data, end=" ") inorder(root.right) def preorder(root): if root is None: return else: print(root.data, end=" ") preorder(root.left) preorder(root.right) def postorder(root): if root is None: return else: postorder(root.left) postorder(root.right) print(root.data, end=" ") def levelorder(root): if root is None: return q = [root] while len(q) != 0: node = q.pop(0) print(node.data, end=" ") if node.left is not None: q.append(node.left) if node.right is not None: q.append(node.right) print() def find(root, data): if root is None: print("Empty Tree") return while root: if root.data == data: return root elif root.data > data: root = root.left else: root = root.right return None def find_max(root): if root is None: print("Empty Tree Return") if root.right == None: return root else: return find_max(root.right) def find_min(root): if root is None: print("Empty Tree") return if root.left == None: return root else: return find_min(root.left) def predecessor(root): if root is None: print("Empty Tree") return if root.left is not None: return find_max(root.left) else: print("No Predecessor for given root") return def successor(root): if root is None: print("Empty Tree") return if root.right is not None: return find_min(root.right) else: print("No Successor for given root") return # Delete Function is Complex Function of Tree DS. I Will write it later def delete_node(root): pass def lca(root, a, b): while (root): if (a <= root.data <= b) or (a >= root.data >= b): return root if a < root.data: root = root.left else: root = root.right return None def is_bst(root, min=float('-inf'), max=float('inf')): if root is None: return 1 if root.data <= min or root.data >= max: return 0 t1 = is_bst(root.left, min, root.data) t2 = is_bst(root.right, root.data, max) res = t1 and t2 return res # For Diagram of Tree Refer Karumanchi Page : 179 root = BSTNode(45) insert_node(root, 33) insert_node(root, 71) insert_node(root, 30) insert_node(root, 35) insert_node(root, 67) insert_node(root, 79) insert_node(root, 19) insert_node(root, 40) insert_node(root, 55) insert_node(root, 69) insert_node(root, 75) insert_node(root, 100) insert_node(root, 10) insert_node(root, 70) insert_node(root, 77) insert_node(root, 97) insert_node(root, 264) insert_node(root, 3) insert_node(root, 15) print("InOrder") inorder(root) print() print("PreOrder") preorder(root) print() print("PostOrder") postorder(root) print() print("LevelOrder") levelorder(root) print("Find My Element") k = find(root, 264) if k != None: print(k.data) else: print("Not Found") print("Max Element") k = find_max(root) print(k.data) print("Min Element") print(find_min(root).data) print("Find My Predecessor") k = predecessor(root) print(k.data) print("Find My Successor") k = successor(root) print(k.data) print("Our Least Common Ancestor") k = lca(root, 10, 45) if k is None: print("No Such Nodes or Node") else: print(k.data) print("Checking our Tree is bst Or not") k = is_bst(root) if k==1: print("Yes, It is BST") else: print("No! Oops not a BST")
# You are in an infinite 2D grid where you can move in any of the 8 directions # (x,y) to # (x-1, y-1), # (x-1, y) , # (x-1, y+1), # (x , y-1), # (x , y+1), # (x+1, y-1), # (x+1, y) , # (x+1, y+1) # You are given a sequence of points and the order in which you need to cover the points.. Give the minimum number of steps in which you can achieve it. You start from the first point. # Example Input # Input 1: # A = [0, 1, 1] # B = [0, 1, 2] # Example Output # Output 1: # 2 #Here we are taking max(|x1-x2|,|y1-y2|) as the distance travelled to get from point(x1,y1) to (y1,y2) class Solution: # @param A : list of integers # @param B : list of integers # @return an integer def coverPoints(self, A, B): x = A[0] y = B[0] res = 0 for i in range(len(A)): res+=max(self.modulus(x,A[i]),self.modulus(y,B[i])) x = A[i] y = B[i] return res def modulus(self,a,b): res = a-b if res>0: return res else: return res*-1
# https://programmers.co.kr/learn/courses/30/lessons/42626?language=python3# # 1차 풀이 (정확성 통과, 효율성 전부 실패) -> 소트에서 문제가 생기는 것으로 판단됨.. def solution(scoville, K): def _make_two_to_one(a, b): return a+(b*2) if min(scoville) > K: return 0 _shuffle = 0 scoville.sort() while scoville[0] < K: if len(scoville) == 1: return -1 new = _make_two_to_one(scoville[0], scoville[1]) scoville = [new] + scoville[2:] scoville.sort() _shuffle += 1 return _shuffle # heapq # 아예 생각도 못해봤던 자료구조.. 입출력 타임에 소팅을 해주는게 엄청난 장점이고, 리스트 인터페이스를 그대로 가져가는게 신기.. # https://docs.python.org/ko/3/library/heapq.html import heapq def solution(scoville, K): heap = [] [heapq.heappush(heap, i) for i in scoville] def _make_two_to_one(a, b): return a+(b*2) _shuffle = 0 while heap[0] < K: if len(heap) == 1: return -1 elif len(scoville) == 2: if _make_two_to_one(heap[0], heap[1]) > K: return _shuffle + 1 else: return -1 a = heapq.heappop(heap) b = heapq.heappop(heap) new = _make_two_to_one(a, b) heapq.heappush(heap, new) _shuffle += 1 return _shuffle
def cons(x, y): """s = list([x]) + list([y])""" return [x] + list(y) def car(x): return x[0] def cdr(x): return x[1:] def cadr(x): return x[1] def caddr(x): return x[2] def cadddr(x): return x[3]
import sqlite3 DATABASE = 'companydb.db' def insertproduct(sellerid, itemid, qty, unit): con1 = sqlite3.connect(DATABASE) cur1 = con1.cursor() cur1.execute("INSERT INTO availproducts (sellerid, itemid, qty, unit) values (?,?,?,?)", (sellerid, itemid, qty, unit)) con1.commit() con1.close() def fetchitemid(category,item): con2 = sqlite3.connect(DATABASE) cur2 = con1.cursor() cur2.execute("SELECT itemid from items where items.category=category and items.item=item") data=cur2.fetchall() con2.close() def fetchproducts(): con3 = sqlite3.connect(DATABASE) cur3 = con3.cursor() cur3.execute("SELECT * from availproducts") datapro=cur3.fetchall() print datapro con3.close()
import timeit import numpy as np def bubbleSort(arr): if len(arr) == 1: return arr else: for i in range(len(arr)-1): if arr[i] > arr[i+1]: arr[i+1], arr[i] = arr[i], arr[i+1] return [arr[-1]] + bubbleSort(arr[:-1]) def test(): arr = list(np.random.randint(1, 1000, 10)) #over 800 exceeds recursion limit print(arr) print(bubbleSort(arr)) def main(): start_time = timeit.default_timer() test() print(timeit.default_timer() - start_time) if __name__ == '__main__': main()
# if condition: # statement # else: # statement #nested if exampal( if within "if") user=input('Enter user name : ') passward=input('Enter passward : ') if user.upper()=='Ifte'.upper(): if passward=='123': print('wellcome') else: print('invalid passward') else: print('invalid user name')
print('Main Menu') print('='*20) print('1. Additon') print('2. Subtraction') print('3. Multification') print('4. Division') print('5. Exit') print('Enter Your Selection :',end=' ') ch=input() if ch=='1': print('you have selected addition') elif ch=='2': print('you have selected subtraction') elif ch=='3': print('you have selected Multification') elif ch=='4': print('you have selected Division') elif ch=='5': print('Thank You for using this program')
# Quiz Quest Component 1 - have an integer checking function # Int_check Function goes here def int_check(question): while True: try: response = int(input(question)) return response # Error message except ValueError: print("Please enter an integer\n") continue number = int_check("Number: ") print(number)
import math class CSensor(object): sensor_number = 0 # the base class for the sensor def __init__(self, name='sensor', x=0, y=0, heading=0): self.name = name self.x_base = x self.y_base = y if heading == 0: self.heading = math.pi - math.atan2(self.x_base, self.y_base) else: self.heading = heading self.price = 1 CSensor.sensor_number += 1 def __str__(self, print_all=False): if print_all: return " ".join(str(items) for items in (self.__dict__.items())) else: return self.name # Tip: Use NotImplementedError to remind you for override the virtual function def detection(self, human, plt): raise NotImplementedError def plot(self, fig): raise NotImplementedError def cover_area(self): raise NotImplementedError def coverage_dangerous_zone(self, coverage_dict, dangerous_zone_radius=1.5): raise NotImplementedError
""" The labyrinth has no walls, but pits surround the path on each side. If a players falls into a pit, they lose. The labyrinth is presented as a matrix (a list of lists): 1 is a pit and 0 is part of the path. The labyrinth's size is 12 x 12 and the outer cells are also pits. Players start at cell (1,1). The exit is at cell (10,10). You need to find a route through the labyrinth. Players can move in only four directions--South (down [1,0]), North (up [-1,0]), East (right [0,1]), West (left [0, -1]). The route is described as a string consisting of different characters: "S"=South, "N"=North, "E"=East, and "W"=West N W E S """ maze_map = [ [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], [1, 1, 1, 0, 1, 1, 1, 1, 0, 1, 1, 1], [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], [1, 0, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1], [1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1], [1, 1, 0, 1, 1, 1, 1, 1, 1, 0, 1, 1], [1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1], [1, 1, 1, 1, 1, 0, 1, 0, 0, 1, 0, 1], [1, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1], [1, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1] ] def labyrinth_map(maze_map): #replace this for solution #This is just example for first maze row=1 col=1 solve_path = "" solve_path_arry = [] # south = False # north = False # easth = False # west = False #direction = 0b0000 # last_direction = 0b1111 # cout = 0 while(not row == 10 and not col == 10): start = True direction = 0b0000 print "present_row:%s, present_col:%s"%(row,col) if(maze_map[row+1][col]==0 and last_direction != 0b1000): # south = True direction = direction | 0b0010 #^ last_direction print "south" if(maze_map[row-1][col]==0 and last_direction != 0b0010): # north = True direction = direction | 0b1000 #^ last_direction print "north" if(maze_map[row][col+1]==0 and last_direction != 0b0001): # easth = True direction = direction | 0b0100 #^ last_direction print "easth" if(maze_map[row][col-1]==0 and last_direction != 0b0100): # west = True direction = direction | 0b0001 #^ last_direction print "west" if(direction == 0b0000): print "wall infront of me" if(last_direction == 0b0010): direction = 0b1000 if(last_direction == 0b1000): direction = 0b0010 if(last_direction == 0b0001): direction = 0b0100 if(last_direction == 0b0100): direction = 0b0001 row = last_row col = last_col print "direction1:"+ bin(direction) while(start): if(direction == 0b0010): row = row+1 #south start = False dir = 'S' solve_path_arry.append(dir) last_direction = 0b0010 # print "solve_path:%s"%solve_path elif(direction == 0b1000): row = row-1 #north start = False dir = 'N' last_direction = 0b1000 solve_path_arry.append(dir) # print "solve_path:%s"%solve_path elif(direction == 0b0100): col = col+1 #easth start = False dir = 'E' last_direction = 0b0100 solve_path_arry.append(dir) # print "solve_path:%s"%solve_path elif(direction == 0b0001): col = col-1 #west start = False dir = 'W' last_direction = 0b0001 solve_path_arry.append(dir) # print "solve_path:%s"%solve_path else: print "choosen direction" direction = last_direction >> 1 if(direction == 0b00000): print "entre!!" direction = 0b1000 start = True last_row = row last_col = col print "last_row:%s, last_col:%s"%(last_row,last_col) # print "cout:%s"%cout # if(cout == 0 and direction != 0b0010 and direction != 0b1000): # solve_path_arry.append(dir) # cout = cout + 1 cout = 0 print solve_path_arry #solve_path = solve_path + dir print "solve_path:%s"%solve_path print "direction2:" + bin(direction) print "next_row:%s, next_col:%s"%(row,col) raw_input() return solve_path def labyrinth_map2(maze_map): """ "EESSWWSSESSWEEESSWWWWSN" """ #replace this for solution #This is just example for first maze debug = True row=1 col=1 solve_path = "" solve_path_arry = [] # south = False # north = False # easth = False # west = False # define_dir = False #direction = 0b0000 # last_dir_bifurcation = 0b0000 last_direction = 0b1111 cout = 0 state = 'define_state' while(True): if debug: raw_input() if(row == 10 and col == 10): if debug: print "TERMINE." break if debug: print solve_path_arry direction = 0b0000 if debug: print "present_row:%s, present_col:%s"%(row,col) if debug: print "STATE: %s"%state if(state=='define_state'): if(maze_map[row+1][col]==0 and last_direction != 0b1000): state = 'south' direction = direction | 0b0010 # if debug: print "south" if(maze_map[row-1][col]==0 and last_direction != 0b0010): state = 'north' direction = direction | 0b1000 # if debug: print "north" if(maze_map[row][col+1]==0 and last_direction != 0b0001): state = 'easth' direction = direction | 0b0100 # if debug: print "easth" if(maze_map[row][col-1]==0 and last_direction != 0b0100): state = 'west' direction = direction | 0b0001 # if debug: print "west" if(direction == 0b0000): if debug: print "wall infront of me" state = 'return_path' row = last_row col = last_col elif(direction != 0b1000 and direction != 0b0100 and direction != 0b0010 and direction != 0b0001): if debug: print "choose path" state = 'multi_path' continue if(state=='south'): row = row+1 #south dir = 'S' solve_path_arry.append(dir) last_direction = 0b0010 state = 'define_state' # print "solve_path:%s"%solve_path if debug: print "next_row:%s, next_col:%s, cout:%s"%(row,col,cout) continue if(state=='north'): row = row-1 #north dir = 'N' last_direction = 0b1000 solve_path_arry.append(dir) state = 'define_state' # print "solve_path:%s"%solve_path if debug: print "next_row:%s, next_col:%s, cout:%s"%(row,col,cout) continue if(state=='easth'): col = col+1 #easth dir = 'E' last_direction = 0b0100 solve_path_arry.append(dir) state = 'define_state' # print "solve_path:%s"%solve_path if debug: print "next_row:%s, next_col:%s, cout:%s"%(row,col,cout) continue if(state=='west'): col = col-1 #west dir = 'W' last_direction = 0b0001 solve_path_arry.append(dir) state = 'define_state' # print "solve_path:%s"%solve_path if debug: print "next_row:%s, next_col:%s, cout:%s"%(row,col,cout) continue if(state=='multi_path'): if debug: print "choosen direction" while True: direction = last_direction >> 1 if(direction == 0b0000): if debug: print "entre!!" direction = 0b1000 state = dir_binary2state(direction) if debug: print "direction: " + bin(direction) + " last_direction: " + bin(last_direction) + " last_dir_bifurcation: " + bin(last_dir_bifurcation) if debug: raw_input() if(last_dir_bifurcation != direction): if debug: print "fueraa" break else: last_direction = direction last_row = row last_col = col last_dir_bifurcation = direction if debug: print "last_row:%s, last_col:%s, last_bifurcation:%s"%(last_row,last_col,last_dir_bifurcation) if debug: print "direction2:" + bin(direction) continue if(state == 'return_path'): if(last_direction == 0b0010): #south direction = 0b1000 #north if(last_direction == 0b1000): #north direction = 0b0010 #south if(last_direction == 0b0001): #west direction = 0b0100 #easth if(last_direction == 0b0100): #easth direction = 0b0001 #west state = dir_binary2state(direction) continue cout = cout + 1 if debug: print solve_path_arry #solve_path = solve_path + dir #print "solve_path:%s"%solve_path if debug: print "direction2:" + bin(direction) if debug: print "STATE2:%s"%state if debug: print "next_row:%s, next_col:%s, cout:%s"%(row,col,cout) if debug: raw_input() return solve_path def dir_binary2state(direction): if(direction == 0b0010): state = 'south' if(direction == 0b1000): state = 'north' if(direction == 0b0100): state = 'easth' if(direction == 0b0001): state = 'west' return state maze_map = [ [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], [1, 1, 1, 0, 1, 1, 1, 1, 0, 1, 1, 1], [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], [1, 0, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1], [1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1], [1, 1, 0, 1, 1, 1, 1, 1, 1, 0, 1, 1], [1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1], [1, 1, 1, 1, 1, 0, 1, 0, 0, 1, 0, 1], [1, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1], [1, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1] ]
import torch "defines modules, which are like functions, some has trainable parameters" import torch.nn as nn "defines functions, equivalent to non-trainable modules" import torch.nn.functional as F class myModel(nn.Module): "store all the trainable layers here" def __init__(self): nn.Module.__init__(self) self.conv1 = nn.Conv2d(in_channels=3, out_channels=8, kernel_size=(5,5), stride=(2,2), padding=(2,2)) self.bn1 = nn.BatchNorm2d(8) self.conv2 = nn.Conv2d(in_channels=8, out_channels=8, kernel_size=(3,3), stride=(2,2), padding=(1,1)) self.bn2 = nn.BatchNorm2d(8) self.fc1 = nn.Linear(8*5*10, 1) "The define the computational flow of our model here" def forward(self, x): x = self.conv1(x) x = self.bn1(x) x = F.max_pool2d(x, kernel_size=(2,2), stride=(2,2)) x = F.relu(x) x = self.conv2(x) x = self.bn2(x) x = F.max_pool2d(x, kernel_size=(2,2), stride=(2,2)) x = F.relu(x) x = x.view(-1,8*5*10) x = F.dropout(x, p=0.3) x = self.fc1(x) return x if __name__ == '__main__': example = myModel() ipt = torch.rand(10, 3, 80, 160) from torch.autograd import Variable # Defines Variable class, which is Tensor plus Gradient ipt = Variable(ipt) print(ipt) opt = example.forward(ipt) print(opt)
import sys def parse_params(filename): """ Function to parse parameter file :param filename: Parameter filename :return: parameter values """ all_dicts = [] with open(filename) as f: for line in f: params = line.strip().split() temp_dict = {"die": float(params[0])} temp_dict.update({i: float(params[i]) for i in range(1, 7)}) all_dicts.append(temp_dict) f.close() return all_dicts def probability(series, params): """ Helper function to compute probabilities :param series: series of values :param params: parameter dictionary :return: probability """ prob = 1 for result in series: prob *= params[result] return prob * params["die"] def bayes(filename, params_a, params_b): """ Function to compute optimal probability for a given die using Bayes rule :param filename: data filename :param params_a: a parameters :param params_b: b parameters :return: lines to print out to a file with posterior probabilities """ roll_results = [] with open(filename) as f: for line in f: rolls = [int(i) for i in line.strip()] marg_a = probability(rolls, params_a) marg_b = probability(rolls, params_b) prob_a = marg_a / (marg_a + marg_b) prob_b = marg_b / (marg_a + marg_b) if prob_a > prob_b: roll_results.append(("A", prob_a)) else: roll_results.append(("B", prob_b)) f.close() return roll_results def output(results): """ Function to write results to a file :param results: lines of posterior probabilities :return: none """ text_file = open("problem_1_B_output.txt", "w") out = "" for i, line in enumerate(results): string = "Sample {}: {}, posterior probability of {:.4f}".format(i + 1, line[0], line[1]) out += (string + "\n") text_file.write(out) text_file.close() def main(): file_param = sys.argv[1] file_counts = sys.argv[2] params_a, params_b = parse_params(file_param) results = bayes(file_counts, params_a, params_b) output(results) if __name__ == "__main__": main()
""" Date management """ from datetime import datetime from typing import Sequence from arrow import arrow def relevant_days_between(start_date: datetime, end_date: datetime) -> Sequence[datetime]: """ Get the list of dates representing the weekdays between (including) two dates :param start_date: Starting date :param end_date: Ending date :return: The list of dates """ WEEKDAY_SATURDAY = 5 return [d.datetime for d in arrow.Arrow.range('day', start_date, end_date) if d.weekday() < WEEKDAY_SATURDAY] def jira_date(d: datetime) -> str: """ Transforms a datetime into a string representing a date in a JQL query :param d: The date :return: A string """ return arrow.Arrow.fromdatetime(d).strftime('%Y/%m/%d')
def main(): lista = [] brEl = int(input("Unesite broj elemenata: ")) for i in range(0, brEl): unos = input(f"Unesite element {i}: ") try: lista.append(int(unos)) except: print("Pogresan unos.") lista.sort() print(lista) if __name__ == '__main__': main()
from math import sin, cos, sqrt from random import uniform import numpy as np from calie.aux import angles class Se2A(object): """ Class for algebra se2 quotient over equivalent relation given by exp. To respect camel case convention and avoid confusion class for se(2) is called Se2A. It is the quotient algebra in which exp is well defined. Quotient projection is applied to each new instance by default, to have exp map bijective. """ def __init__(self, theta, tx, ty): self.rotation_angle = angles.mod_pipi(theta) if self.rotation_angle == theta: self.tx = tx self.ty = ty else: modfact = self.rotation_angle / theta self.tx = modfact * tx self.ty = modfact * ty def __quotient_projection__(self): """ Maps the elements of se2_a in the quotient over the equivalence relation defined by exp, in order to have exp well defined. a ~ b iff exp(a) == exp(b) Here se2_a is intended as the quotient se2_a over the above equivalence relation. :param self: element of se2_a """ theta_quot = angles.mod_pipi(self.rotation_angle) if self.rotation_angle == theta_quot: tx_quot = self.tx ty_quot = self.ty else: modfact = angles.mod_pipi(self.rotation_angle) / self.rotation_angle tx_quot = self.tx * modfact ty_quot = self.ty * modfact return Se2A(theta_quot, tx_quot, ty_quot) quot = property(__quotient_projection__) def __get_matrix__(self): # using the quotient data to create the matrix. theta = self.quot.rotation_angle tx = self.quot.tx ty = self.quot.ty a1 = [0, -theta, tx] a2 = [theta, 0, ty] a3 = [0, 0, 0] return np.array([a1, a2, a3]) get_matrix = property(__get_matrix__) def __get_restricted__(self): # get rotation and translation in a list from quotient. theta = self.quot.rotation_angle tx = self.quot.tx ty = self.quot.ty return [theta, tx, ty] get = property(__get_restricted__) def __add__(self, element2): alpha1 = self.rotation_angle x1 = self.tx y1 = self.ty alpha2 = element2.rotation_angle x2 = element2.tx y2 = element2.ty alpha_sum = alpha1+alpha2 return Se2A(alpha_sum, x1 + x2, y1 + y2).quot def __sub__(self, element2): alpha1 = self.rotation_angle x1 = self.tx y1 = self.ty alpha2 = element2.rotation_angle x2 = element2.tx y2 = element2.ty alpha_subs = alpha1 - alpha2 return Se2A(alpha_subs, x1 - x2, y1 - y2).quot def __rmul__(self, scalar): """ Alternative for the scalar product """ tx = self.tx ty = self.ty alpha = self.rotation_angle return Se2A(scalar * alpha, scalar * tx, scalar * ty).quot def scalarprod(self, const): """ :param const: scalar float value :return: const*element as scalar product in the Lie algebra """ alpha = self.rotation_angle x = self.tx y = self.ty return Se2A(const * alpha, const * x, const * y) def norm(self, norm_type='standard', lamb=1): """ norm(self, typology, lamb for the standard norm type) norm_type get the type of the norm we want to deal with: norm_type in {'', 'vector_len'} :param norm_type: :param lamb: :return: """ if norm_type == 'lamb': ans = sqrt(self.rotation_angle**2 + lamb*(self.tx**2 + self.ty**2)) # lamb has to be modified in aux_func elif norm_type == 'translation': ans = sqrt(self.tx ** 2 + self.ty ** 2) elif norm_type == 'fro': ans = sqrt(2*self.rotation_angle**2 + self.tx ** 2 + self.ty ** 2) else: ans = -1 return ans def se2a_randomgen(intervals=(0, 10), norm_type='fro', lamb=1): """ Montecarlo sampling to build a random element in Se2A. it uses 3 possible norm_type, lamb, translation, or fro :param intervals: :param norm_type: :param lamb: weight of the radius: sqrt(theta**2 + lamb * rho**2) :return: se2_a(theta, tx, ty) such that a < se2_a(theta, tx, ty).norm(norm_type) < b """ # montecarlo sampling to get a < se2_a(theta, tx, ty).norm(norm_type) < b norm_belongs_to_interval = False num_attempts = 0 a = intervals[0] b = intervals[1] theta, tx, ty = 0, 0, 0 if norm_type == 'lamb': while not norm_belongs_to_interval and num_attempts < 1000: num_attempts += 1 theta = uniform(-np.pi + np.abs(np.spacing(-np.pi)), np.pi) rho = uniform(a, b) if a <= sqrt(theta**2 + lamb * rho**2) <= b: # keep theta, compute tx ty according to rho and a new eta eta = uniform(-np.pi + np.abs(np.spacing(-np.pi)), np.pi) tx = rho * cos(eta) ty = rho * sin(eta) norm_belongs_to_interval = True elif norm_type == 'translation': # we pick rho to satisfy the condition a < se2_a(theta, tx, ty).norm(norm_type) < b # where norm is the the norm of the translation. # no Montecarlo is needed. theta = uniform(-np.pi + np.abs(np.spacing(-np.pi)), np.pi) rho = uniform(a, b) eta = uniform(-np.pi + np.abs(np.spacing(-np.pi)), np.pi) tx = rho * cos(eta) ty = rho * sin(eta) elif norm_type == 'fro': while not norm_belongs_to_interval and num_attempts < 1000: num_attempts += 1 theta = uniform(-np.pi + np.abs(np.spacing(-np.pi)), np.pi) rho = uniform(a, b) if a <= sqrt(2*theta**2 + rho**2) <= b: # keep theta, compute tx ty according to rho and a new eta eta = uniform(-np.pi + np.abs(np.spacing(-np.pi)), np.pi) tx = rho * cos(eta) ty = rho * sin(eta) norm_belongs_to_interval = True if num_attempts == 1000 and not norm_belongs_to_interval: raise Exception("randomgen_standard_norm in se2_g with lambda = 1: safety recursion number has been reached" "montecarlo method has failed in finding an element after 1000 attempt.") else: return Se2A(theta, tx, ty) def is_a_matrix_in_se2a(m_input, relax=False): ans = False if type(m_input) == np.ndarray and m_input.shape == (3, 3): m = m_input.copy() if relax: m = np.around(m, 6) if m[0, 0] == m[1, 1] == 0 and m[1, 0] == -m[0, 1] and m[2, 0] == m[2, 1] == m[2, 2] == 0: ans = True return ans def se2a_lie_bracket(element1, element2): """ lie_bracket(A,B) \n :param element1 : :param element2 : elements of se2 already in the quotient :return: their Lie bracket Note: no need to put quotient. The resultant angle is zero. """ # if str(type(element1))[-5:] != str(type(element2))[-5:] != 'se2_a': # raise TypeError('warning: wrong input data format, 2 se2_a elements expected.') element1 = element1.quot element2 = element2.quot alpha1 = element1.rotation_angle alpha2 = element2.rotation_angle x1 = element1.tx y1 = element1.ty x2 = element2.tx y2 = element2.ty return Se2A(0, alpha2 * y1 - alpha1 * y2, alpha1 * x2 - alpha2 * x1) def se2a_lie_multi_bracket(l): """ lie_bracket(l) \n :param l: L list of element of se2 :return: [L0 ,[L1,[L2, [... [L(n-1),Ln]...] """ if len(l) <= 1: return 0 elif len(l) == 2: return se2a_lie_bracket(l[0], l[1]) else: le = len(l) return se2a_lie_multi_bracket(l[0:le - 2] + [se2a_lie_bracket(l[le - 2], l[le - 1])]) def matrix2se2a(a, eat_em_all=False): """ matrix2se2(a, relax = False) \n :param a: matrix of se(2) np.array([[0,0,0],[tx,0,-theta],[ty,theta,0]]) optional relax, if it relax the input condition, allowing any kind of matrix :param eat_em_all: if True, any kind of matrix can be utilized and converted into se2, cutting the extra info. :return: corresponding element in SE2 . """ if not eat_em_all and not is_a_matrix_in_se2a(a): raise Exception("matrix2se2_a in se2_a: the inserted element is not a matrix in se2_a ") else: theta = a[1, 0] x = a[0, 2] y = a[1, 2] return Se2A(theta, x, y) def list2se2a(a): if not type(a) == list or not len(a) == 3: raise TypeError("list2se2_g in se2_g: list of dimension 3 expected") return Se2A(a[0], a[1], a[2]) def se2a_exp(element): """ exp(element) \n algebra exponential :param element: instance of se2 :return: corresponding element in Lie group SE2, se2_g.matrix2se2_g(lin.expm(m_element), True) """ element = element.quot theta = element.rotation_angle v1 = element.tx v2 = element.ty esp = np.abs(np.spacing([0]))[0] if abs(theta) <= 10*esp: factor1 = 1 - (theta**2)/6.0 factor2 = theta/2.0 else: factor1 = sin(theta)/theta factor2 = (1 - cos(theta))/theta x1 = factor1*v1 - factor2*v2 x2 = factor2*v1 + factor1*v2 return Se2G(theta, x1, x2) def se2a_exp_matrices(m, eat_em_all=True): """ exp_m(m) \n algebra exponential for matrices :param m: instance of se2 in matrix form :param eat_em_all: if any matrix can be its input. It will be forced to be exponentiated, cutting the extra info. :return: corresponding element in Lie group SE2, matrix form again """ if not eat_em_all and not is_a_matrix_in_se2a(m): raise Exception("exp_for_matrices in se2_a: the inserted element is not a matrix in se2_a ") # first step is to quotient the input element (if the input is a sum) ans = se2a_exp(Se2A(m[1, 0], m[0, 2], m[1, 2])) return ans.get_matrix def se2a_lie_bracket_for_matrices(m1, m2, eat_em_all=True): """ Compute lie bracket for matrices :param m1: :param m2: :param eat_em_all: how strict we are on input! :return: """ if not eat_em_all: if not (is_a_matrix_in_se2a(m1) and is_a_matrix_in_se2a(m2)): raise Exception("bracket_for_matrices in se2_a: the inserted element is not a matrix in se2_a ") return m1*m2 - m2*m1 def se2a_lie_multi_bracket_for_matrices(l): """ lie_bracket(L) \n :param l: list of matrices :return: [L0 ,[L1,[L2, [... [L(n-1),Ln]...] """ if len(l) <= 1: return 0 elif len(l) == 2: return se2a_lie_bracket_for_matrices(l[0], l[1]) else: num = len(l) return se2a_lie_multi_bracket_for_matrices(l[0:num - 2] + [se2a_lie_bracket(l[num - 2], l[num - 1])]) """ Lie group """ class Se2G(object): """ Class for group of SE(2) Lie group of rotations and translation in 2 dimensions. To respect camel case convention and avoid confusion class for SE(2) is called Se2G. """ def __init__(self, theta, tx, ty): self.rotation_angle = angles.mod_pipi(theta) self.tx = tx self.ty = ty def __get_matrix__(self): a1 = [cos(self.rotation_angle), -sin(self.rotation_angle), self.tx] a2 = [sin(self.rotation_angle), cos(self.rotation_angle), self.ty] a3 = [0, 0, 1] return np.array([a1, a2, a3]) get_matrix = property(__get_matrix__) def __get_restricted__(self): return [self.rotation_angle, self.tx, self.ty] get = property(__get_restricted__) def __mul__(self, element2): x1 = self.tx x2 = element2.tx y1 = self.ty y2 = element2.ty theta_1 = angles.mod_pipi(self.rotation_angle) c1 = cos(theta_1) s1 = sin(theta_1) alpha = angles.mod_pipi(self.rotation_angle + element2.rotation_angle) x = x1 + x2 * c1 - y2 * s1 y = y1 + x2 * s1 + y2 * c1 return Se2G(alpha, x, y) def inv(self): alpha = self.rotation_angle xv = self.tx yv = self.ty xn = - cos(alpha)*xv - sin(alpha)*yv yn = + sin(alpha)*xv - cos(alpha)*yv return Se2G(-alpha, xn, yn) def norm(self, norm_type='standard', lamb=1): """ norm(self, typology, order = None, axes = None) norm_type get the type of the norm we want to deal with: norm_type in {'', 'vector_len'} """ if norm_type == 'standard' or norm_type == 'group_norm': ans = sqrt(self.rotation_angle**2 + lamb*(self.tx**2 + self.ty**2)) elif norm_type == 'translation': ans = sqrt(self.tx ** 2 + self.ty ** 2) elif norm_type == 'fro': ans = sqrt(3 + self.tx ** 2 + self.ty ** 2) else: ans = -1 return ans def se2g_randomgen_custom(interval_theta=(), interval_tx=(), interval_ty=(), avoid_zero_rotation=True): """ GIGO method. :param interval_theta: (interval_theta[0], interval_theta[1]) :param interval_tx: (interval_tx[0], interval_tx[1]) :param interval_ty: (interval_ty[0], interval_ty[1]) :param avoid_zero_rotation: :return: se2_g(uniform(interval_theta[0], interval_theta[1]), uniform(interval_tx[0], interval_tx[1]), uniform(interval_ty[0], interval_ty[1]) ) """ # avoid theta = zero theta = uniform(interval_theta[0], interval_theta[1]) if avoid_zero_rotation: if interval_theta[0] < 0 < interval_theta[1]: epsilon = 0.001 # np.spacing(0) theta = np.random.choice([uniform(interval_theta[0], 0 - epsilon), uniform(0 + epsilon, interval_theta[1])]) if len(interval_tx) == 1: tx = interval_tx[0] else: tx = uniform(interval_tx[0], interval_tx[1]) if len(interval_ty) == 1: ty = interval_ty[0] else: ty = uniform(interval_ty[0], interval_ty[1]) return Se2G(theta, tx, ty) def se2g_randomgen_custom_center(interval_theta=(-np.pi / 2, np.pi / 2), interval_center=(1, 6, 1, 6), avoid_zero_rotation=True, epsilon_zero_avoidance=0.001): """ An element of SE(2) defines a rotation (from SO(2)) away from the origin. The center of the rotation is the fixed point of the linear map. This method provides an element of SE(2), random, with rotation parameter sampled over a uniform distribution in the interval interval_theta, and with center of rotation in the squared subset of the cartesian plane (x0,x1)x(y0,y1) :param interval_theta: :param interval_center: :param avoid_zero_rotation: :param epsilon_zero_avoidance: :return: """ theta = uniform(interval_theta[0], interval_theta[1]) if avoid_zero_rotation: if interval_theta[0] < 0 < interval_theta[1]: epsilon = epsilon_zero_avoidance # np.spacing(0) theta = np.random.choice([uniform(interval_theta[0], 0 - epsilon), uniform(0 + epsilon, interval_theta[1])]) x_c = uniform(interval_center[0], interval_center[1]) if len(interval_center) == 4: y_c = uniform(interval_center[2], interval_center[3]) else: y_c = uniform(interval_center[0], interval_center[1]) tx = (1 - np.cos(theta)) * x_c + np.sin(theta) * y_c ty = -np.sin(theta) * x_c + (1 - np.cos(theta)) * y_c return Se2G(theta, tx, ty) def se2g_randomgen(intervals=(), lamb=1): if len(intervals) == 2: a = intervals[0] b = intervals[1] if b < a or a < 0 or b < 0: raise Exception("randomgen_standard_norm in se2_g " "given interval (a,b) must have a < b for a, b positive ") elif len(intervals) == 0: a = 0 b = 10 else: raise Exception("randomgen_standard_norm in se2_g: " "the list of intervals inserted must have dimension 2 or 0") if lamb < 0: raise Exception("randomgen_standard_norm in se2_g with lambda < 0: " "negative lambda is not accepted. ") elif lamb == 0: if a > np.pi: raise Exception("randomgen_standard_norm in se2_g with lambda = 0: " "intervals (a,b) and (-pi, pi) can not be disjoint ") else: a_theta_pos = a b_theta_pos = min(b, np.pi) a_theta_neg = -a b_theta_neg = max(-b, -np.pi + np.abs(np.spacing(-np.pi))) theta = np.random.choice([uniform(a_theta_pos, b_theta_pos), uniform(a_theta_neg, b_theta_neg)]) rho = uniform(0, 10) eta = uniform(-np.pi + np.abs(np.spacing(-np.pi)), np.pi) tx = rho * cos(eta) ty = rho * sin(eta) else: a_theta = max(-a, -np.pi + np.abs(np.spacing(-np.pi))) b_theta = min(a, np.pi) theta = uniform(a_theta, b_theta) rho = uniform(sqrt((a**2 - theta**2)/lamb), sqrt((b**2 - theta**2)/lamb)) eta = uniform(-np.pi + np.abs(np.spacing(-np.pi)), np.pi) tx = rho * cos(eta) ty = rho * sin(eta) return Se2G(theta, tx, ty) def se2g_randomgen_translation(intervals=()): if len(intervals) == 2: a = intervals[0] b = intervals[1] if b < a or a < 0 or b < 0: raise Exception("randomgen_standard_norm in se2_g with: " "given interval (a,b) must have a < b for a, b positive ") elif len(intervals) == 0: a = 0 b = 10 else: raise Exception("randomgen_translation_norm in se2_g: " "the list of intervals inserted must have dimension 2 or 0") theta = uniform(-np.pi + np.abs(np.spacing(-np.pi)), np.pi) rho = uniform(a, b) eta = uniform(-np.pi + np.abs(np.spacing(-np.pi)), np.pi) tx = rho * cos(eta) ty = rho * sin(eta) return Se2G(theta, tx, ty) def se2g_randomgen_fro(intervals=()): if len(intervals) == 2: a = intervals[0] b = intervals[1] if b < a or a < sqrt(3): raise Exception("randomgen_fro_norm in se2_g with: given interval (a,b) " "must have a < b for a, b positive greater than sqrt(3) ") elif len(intervals) == 0: a = sqrt(3) b = 10 else: raise Exception("randomgen_translation_norm in se2_g: " "the list of intervals inserted must have dimension 2 or 0") theta = uniform(-np.pi + np.abs(np.spacing(-np.pi)), np.pi) rho = uniform(sqrt(round(a**2 - 3, 15)), sqrt(round(b**2 - 3, 15))) eta = uniform(-np.pi + np.abs(np.spacing(-np.pi)), np.pi) tx = rho * cos(eta) ty = rho * sin(eta) return Se2G(theta, tx, ty) def is_a_matrix_in_se2g(m_input, relax=False): ans = False if type(m_input) == np.ndarray: m = m_input.copy() if relax: m = np.around(m, 6) if m.shape == (3, 3) and m[0, 0] == m[1, 1] and m[1, 0] == -m[0, 1] \ and m[2, 0] == m[2, 1] == 0 and m[2, 2] == 1: ans = True return ans def matrix2se2g(A, eat_em_all=False): """ matrix2se2_g(M) \n :param: matrix of SE(2) np.array([[1,0],[t,R]]). t translation (in IR^(2x1)), R rotation (in SO(2)) optional relax, if it relax the input condition, allowing any kind of matrix Relax, if we want some relaxation in the input. :return: corresponding element in SE2 . """ if not eat_em_all and not is_a_matrix_in_se2g(A): raise Exception("matrix2se2_g in se2_g: the inserted element is not a matrix in se2_g ") else: theta = np.arctan2(A[1, 0], A[0, 0]) x = A[0, 2] y = A[1, 2] return Se2G(theta, x, y) def list2se2g(a): if not type(a) == list or not len(a) == 3: raise TypeError("list2se2_g in se2_g: list of dimension 3 expected") return Se2G(a[0], a[1], a[2]) def se2g_log(element): """ log(element) \n group logarithm :param: instance of SE2 :return: corresponding element in Lie algebra se2 """ theta = angles.mod_pipi(element.rotation_angle) v1 = element.tx v2 = element.ty c = cos(theta) prec = np.abs(np.spacing([0.0]))[0] if abs(c - 1.0) <= 10*prec: x1 = v1 x2 = v2 theta = 0 else: factor = (theta / 2.0) * sin(theta) / (1.0 - c) x1 = factor * v1 + (theta / 2.0) * v2 x2 = factor * v2 - (theta / 2.0) * v1 return Se2A(theta, x1, x2)
import fractions as fr from scipy import misc # ------------- auxiliary method for the BCH formula ---------------- def fact(n): """ Covers the predefined function factorial from scipy.misc :param n: :return: factorial of n type float """ return float(misc.factorial(n, True)) def bern(n): """ bern(n) \n :param n: integer n :return: nth Bernoulli number (type Fraction) (iterative algorithm, do not uses polynomials) """ if n == 1: ans = fr.Fraction(1, 2) elif n % 2 == 1: ans = fr.Fraction(0, 1) else: n += 1 a = [0] * (n + 1) for m in range(n + 1): a[m] = fr.Fraction(1, m + 1) for j in range(m - 1, 0, -1): a[j - 1] = j * (a[j - 1] - a[j]) ans = a[0] return ans # type Fraction. # return float(ans) # type Float def bernoulli_poly(x, n): """ bernoulli_poly(x,n) \n :param x: value for the unknown. :param n: degree of the polynomial. :return: j-th bernoulli polynomial evaluate at x (unknown of the poly). """ return sum([misc.comb(n, k) * bern(n - k) * (x ** k) for k in range(n)]) # comb = binomial def bernoulli_numb_via_poly(n): """ bernoulli_numb(n) \n :param n: integer n :return: nth Bernoulli number (uses first type bernoulli polynomials) """ return bernoulli_poly(0, n)
#coding:utf-8 ''' 去掉重复的字母,使用lexicographical order找出最短的字串 ''' class Solution(object): def removeDuplicateLetters(self, s): """ :type s: str :rtype: str """ rs = {x:i for i, x in enumerate(s)} res = '' for j, y in enumerate(s): if y not in res: while y < res[-1:] and j < rs[res[-1]]: res = res[:-1] res += y return res S = Solution() s1 = 'bcabc' s2 = 'cbacdcbc' assert 'abc' == S.removeDuplicateLetters(s1) assert 'acdb' == S.removeDuplicateLetters(s2)
digimon_stats=[["Attack",7], ["Defense",10],["S",4]] #Use the Analyzer to get Digimon details. print(digimon_stats[1]) #Use the Analyzer to get the numerical value for the Digimon's Speed (S) #[2][1] is the 2nd list & 1st value inside digimon_stats, where counting is 0-based. print(digimon_stats[2][1]) #Display all of the statistics at once. print("Full Battle Statistics:") for digimon in digimon_stats: print(digimon) #Reveal the numeric statistic for each attribute. print("Value per attribute:") for digimon in digimon_stats: print(digimon[1])
# -*- coding: utf-8 -*- """ Dado un mensaje y un alfabeto, dar su codificación usando la técnica de 'Move to Front'. mensaje='mi mama me mima mucho' alfabeto=[' ', 'a', 'c', 'e', 'h', 'i', 'm', 'o', 'u'] MtFCode(mensaje,alfabeto)=[6, 6, 2, 2, 3, 1, 1, 2, 2, 5, 2, 2, 4, 1, 4, 3, 2, 8, 6, 7, 8] """ def MtFCode(mensaje,alfabeto): codigo = [] for simbolo in mensaje: index = alfabeto.index(simbolo) codigo.append(index) letra_extraida = alfabeto.pop(index) alfabeto.insert(0,letra_extraida) return codigo mensaje='mi mama me mima mucho' alfabeto=[' ', 'a', 'c', 'e', 'h', 'i', 'm', 'o', 'u'] print("MtFCode() ",MtFCode(mensaje,alfabeto) ==[6, 6, 2, 2, 3, 1, 1, 2, 2, 5, 2, 2, 4, 1, 4, 3, 2, 8, 6, 7, 8]) """ Dado un mensaje, aplicar la transformación de Burrows-Wheeler devolviendo la última columna y la posición. mensaje='cadacamacasapasa' BWT(mensaje)=('sdmccspcaaaaaaaa', 8) """ def BWT(mensaje): """Apply Burrows-Wheeler transform to input string.""" table = sorted(mensaje[i:] + mensaje[:i] for i in range(len(mensaje))) # Table of rotations of string ultima_columna = [row[-1:] for row in table] # Last characters of each row ultima_columna = "".join(ultima_columna) posicion = table.index(mensaje) return ultima_columna, posicion mensaje='cadacamacasapasa' print("BWT() ", BWT(mensaje)) """ 1. Hallar la tabla de frecuencias asociada a los símbolos del fichero que contiene el texto de 'La Regenta' y calcular la entropía. mensaje='La heroica ciudad dormía la siesta. El viento Sur, caliente y perezoso, empujaba las nubes blanquecinas que se rasgaban al correr hacia el Norte.' tabla_frecuencias=[' ', 23], [',', 2], ['.', 2], ['E', 1], ['L', 1], ['N', 1], ['S', 1], ['a', 18], ['b', 4], ['c', 6], ['d', 3], ['e', 15], ['g', 1], ['h', 2], ['i', 7], ['j', 1], ['l', 7], ['m', 2], ['n', 6], ['o', 7], ['p', 2], ['q', 2], ['r', 9], ['s', 8], ['t', 4], ['u', 6], ['v', 1], ['y', 1], ['z', 1], ['í', 1]] Entropía: 4.224930298009863 """ import math def H1(p): entropia = 0 for i in range (len(p)): if (p[i] != 0): entropia += p[i] * math.log(1/p[i],2) return entropia def H2(n): longitud = sum(n) ddp = [x/longitud for x in n] return H1(ddp) def tablaFrecuencias(mensaje): frecuencias=[] for letra in set(mensaje): frecuencias.append(mensaje.count(letra)) return frecuencias ''' def tablaFrecuencias(mensaje,numero_de_simbolos=1): while len(mensaje)%numero_de_simbolos != 0: mensaje+=mensaje[-1] frecuencias = {} q = [i*numero_de_simbolos for i in range(int((len(mensaje)/numero_de_simbolos)))] for i in q: aux = "" for j in range(numero_de_simbolos): if(i+j < len(mensaje)): aux += mensaje[i+j] if aux not in frecuencias: frecuencias[aux] = 1 else: frecuencias[aux] += 1 return frecuencias with open("la_regenta_utf8.txt", "r") as my_file: mensaje = my_file.read() ''' mensaje='La heroica ciudad dormía la siesta. El viento Sur, caliente y perezoso, empujaba las nubes blanquecinas que se rasgaban al correr hacia el Norte.' t_frec = tablaFrecuencias(mensaje) entropia_original = H2(t_frec) print ('Entropía: ', entropia_original) """ 2. A continuación aplicar la transformación de Burrows-Wheeler al fichero (primero probad con una parte antes de hacerlo con el fichero entero) y a continuación aplicar MtFCode a la última columna obtenida. Hallar la tabla de frecuencias del resultado obtenido y calcular la entropía. mensaje='La heroica ciudad dormía la siesta. El viento Sur, caliente y perezoso, empujaba las nubes blanquecinas que se rasgaban al correr hacia el Norte.' BWT(mensaje)='.lons,alda,raaasyseealeroae . ciLíbltjghd cbllnraau i ae au suttu iirphbirs colvsccueaE b aeraiaee tsrdcNz m neu reoeooeaa a oesnrnniqqpS em' alfabeto=[' ', ',', '.', 'E', 'L', 'N', 'S', 'a', 'b', 'c', 'd', 'e', 'g', 'h', 'i', 'j', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'y', 'z', 'í'] MtFCode(BWT(mensaje),alfabeto)=[2, 16, 19, 19, 23, 6, 11, 5, 14, 2, 3, 23, 2, 0, 0, 5, 27, 1, 17, 0, 3, 7, 2, 5, 9, 4, 3, 11, 11, 1, 0, 17, 20, 15, 29, 19, 11, 26, 23, 22, 23, 19, 11, 11, 8, 8, 0, 20, 17, 16, 0, 27, 7, 15, 1, 3, 17, 2, 0, 2, 4, 2, 19, 2, 15, 0, 1, 3, 0, 6, 0, 7, 26, 14, 12, 4, 4, 8, 6, 0, 13, 20, 14, 28, 5, 4, 0, 11, 14, 14, 24, 9, 12, 1, 3, 4, 11, 2, 12, 1, 3, 0, 4, 15, 10, 6, 17, 11, 25, 29, 7, 28, 1, 20, 10, 15, 3, 9, 3, 18, 1, 1, 0, 1, 13, 0, 4, 1, 1, 3, 3, 12, 7, 6, 1, 0, 14, 29, 0, 21, 29, 9, 0, 8, 12] Nuevo_alfabeto=[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29] Nueva_tabla_frecuencias=[[0, 18], [1, 13], [2, 9], [3, 11], [4, 8], [5, 4], [6, 5], [7, 5], [8, 4], [9, 4], [10, 2], [11, 9], [12, 5], [13, 2], [14, 6], [15, 5], [16, 2], [17, 5], [18, 1], [19, 5], [20, 4], [21, 1], [22, 1], [23, 4], [24, 1], [25, 1], [26, 2], [27, 2], [28, 2], [29, 4]] Nueva entropía: 4.507878869023793 Observar qué pasa a medida que el mensaje se acerca al texto entero. """ mensaje='La heroica ciudad dormía la siesta. El viento Sur, caliente y perezoso, empujaba las nubes blanquecinas que se rasgaban al correr hacia el Norte.' resultadoBWT = BWT(mensaje) print(resultadoBWT) alfabeto = set() for i in mensaje: alfabeto.add(i) alfabeto = sorted(alfabeto) resultadoMtF = MtFCode(resultadoBWT[0],alfabeto) print(resultadoMtF) t_frec = tablaFrecuencias(resultadoMtF) entropia_original = H2(t_frec) print ('Nueva entropía: ', entropia_original) print("") print("----EXAMEN-----") mensaje = "gffbehfhhgfc" resultadoBWT = BWT(mensaje) print(resultadoBWT)
import sys import copy def handle_repeat(list_all): first_list = list(copy.copy(list_all[0])) for line in first_list: if is_repeat_3(line,list_all): first_list.remove(line) return first_list def file2list(vcf): file_list = [] with open(vcf) as f: for line in f: line = line.strip('\n') if line: file_list.append(line) return file_list #def merge(list_all): # list_merge = [] # for i in list_all: # list_merge.extend(i) # set_merge = set(list_merge) def be_list(argvs): list_all = [] for vcf in argvs: list_all.append(set(file2list(vcf))) return list_all def is_repeat_3(line,list_all): num = 0 for vcf in list_all: if line in vcf: num += 1 if num > 1: return True else: return False def main(): argvs = sys.argv[1:] list_all = be_list(argvs) first_list = handle_repeat(list_all) print ('\n'.join(first_list)) if __name__ == '__main__': main()
from datetime import datetime fecha = "10 days 2021" try: objeto_fecha = datetime.strptime(fecha, '%d days after %Y') fecha_normalizada = datetime.strftime(objeto_fecha, '%d/%m/%Y') print("Funcionó el método 1") print(fecha,'->', objeto_fecha, '->', fecha_normalizada) except ValueError: objeto_fecha = datetime.strptime(fecha, '%d days %Y') fecha_normalizada = datetime.strftime(objeto_fecha, '%d/%m/%Y') print("Funcionó el método 2") print(fecha,'->', objeto_fecha, '->', fecha_normalizada)
import itertools def permutations(string): res = itertools.permutations(string) print (res) return [''.join(str) for str in (set(res))] permutations('aabb')
def perimeter(n): #Fibonacci sequence a=[] a.append(1) a.append(1) for i in range(2,n+1): a.append(a[i-1]+a[i-2]) # return int(4*sum(a))
prime_numbers = 0 number = 2 while(prime_numbers <= 25): counter = 0 for i in range(2,number): if(number%i == 0): counter = counter + 1 if(counter == 0): prime_numbers = prime_numbers + 1 print(number) number = number + 1
# ИКНиТО, 2-ой курс, ИВТ, Лазарев Игорь x = [] y = [] n = int(input("Введите количество элементов: ")) for i in range(n): x.append(float(input("Введите " + str(i + 1) + " элемент Х: "))) y.append(float(input("Введите " + str(i + 1) + " элемент Y: "))) print(x) print(y) x_sr = sum(x) / n y_sr = sum(y) / n x_kv_sr = sum(list(map(lambda p: p*p, x))) / n x_y_sr = sum(list(map(lambda p,k: p*k, x,y))) / n b1 = (x_y_sr - x_sr * y_sr) / (x_kv_sr - x_sr * x_sr) b0 = y_sr - b1 * x_sr print("b0 = " + str(b0)) print("b1 = " + str(b1)) Xo = [] Yo = [] n = int(input("Введите количество элементов, которые вы хотите вычислить: ")) for i in range(n): Xo.append(float(input("Введите " + str(i + 1) + " элемент Х: "))) Yo.append(b0 + Xo[i] * b1) print(Xo) print(Yo)
# This Program caluclates howmany tiles you will need # When tiling a wall or floor in metres squared length = float(input ("Enter Room Length: ")) width = float(input ("Enter Room Width: ")) #length = 4.3 #1width = 2.2 Area = length * width needed = Area * 1.05 print ("You need ", needed ,"Tiles in metres squared")
from datetime import date today = int(date.today().weekday()) print(today) if today < 4: print('Yes, unfortunately today is a weekday.') else: print('It is the weekend, yay!')
def anagrams1(words): anagrams = {} for word in words: alphaform = "".join(sorted(word.lower())) #print(f'{word} {alphaform}') if alphaform not in anagrams: anagrams[alphaform] = [] anagrams[alphaform].append(word) for key in anagrams: print(anagrams[key]) f = open('words.txt', 'r') words = f.read().split("\n") f.close() anagrams1(words)
#Excercise : Dead Code 작성 주의!! #Exception Handling : try/except 문 사용 astr = 'Hello bob' #istr = int(astr) # 에러발생 : 형변환 불가능함 : int는 unsafe : ok,error 동시 존재 : error의 가능성이 있으면 error핸들링을 해줘야 함 try: #에러발생 여지가 있으면 넣어준다 istr = int(astr) except: #에러발생시 적용 istr = -1 print('Fisrt', istr) # try 중간 에러 발생 case astr = 'Bob' try: print('Hello') istr = int(astr) print('There') except: istr = -1 print('Done', istr) # Functions : def 명령어 사용해서 생성 x = 1 # variable = name of value # function = name of code # 이름짓기 : 중요한 개념! : def thing(): print('Hello') thing() # 함수 호출 : 프로그램은 반복적 코드를 매우 싫어함 -> 추상화함(Abstract) -> 함수생성 # -> print('Hello') 10번 쓰는 것 보다 thing() 10번 쓰는게 나음 # -> 수정점이 적기 때문에! : 추상화(abstration) ! : 함수도 그중 한 방법 # while or for 사용해서 반복 가능 i = 0 while i < 10: thing() i = i+1 # if loop fuc <- class, Pointer, structure 등 구현 가능 # 파이썬 펑션 두가지 : 빌트인펑션(기본제공- inpu(),type() 등), 사용자정의펑션 def f(x): # name of 'parameterized' code : 파라미터에 의해 바뀌는 코드 : x:parameter or formal parameter or formal argument 등으로 부름 print(x) return x # 되돌려 줄 수 있음 --> 변수에 담을 수 있다 f("Hello") # context 1 : context : 함수가 호출되는 지점 f("World") # context 2 : call 호출 argument : 아규먼트 : 실제 콜할때 들어가는 값 y = f("Hello") # return 값을 받아서 저장 z = f("World") print(y,z) big = max('Hello world') #max 함수로 인해 문자열중 가장 큰 시퀀스 값 선택 print(big) # To Function or Not To Function : 로지컬한 단위별로 만들면 편하다 # Excercise : 견고한 코딩은 예외처리 필수! Robust하게! def pay(a, b): return a*b + b / 2 *( a - 30 ) # input 함수로 인한 주석 처리 # try: # hours = int(input('Enter Hours? : ')) # except: # hours = -1 # try: # rate = int(input('Enter Rate? : ')) # except: # rate = -1 # if hours > 0 and rate > 0: # 둘다 이상이 없을 경우 출력 # print("Pay",pay(hours, rate)) # else: # print("Not make sense") # Loop : 반복문 : 무한루프 주의 n = 10 while n > 0: # print(n) n = n - 1 # 무한루프 등 케이스 주의
a=1 b=1 con=1 d=1 while con<=10: while d<=10: c=b/a print c b=b+con d=d+1 print("la tabla de dividir es la siguiente:") con=con+1 b=con d=1
print("el inciso c del ejercicio 1") def suma(x, y): return x + y a=raw_input("ingrese el primer numero") b=raw_input("ingrese el segundo numero") value=int(a) value1=int(b) print suma(value, value1) print " "
# ------------------------------------------------------------------------------ # Name: CS_U2_Assg2.py # Purpose: List Checker # Author: Maryil.H # Created: 27/03/2017 # ------------------------------------------------------------------------------ #Remove Redundants function def remove_redundants(og_list): items = input("Please enter an item: ") if items not in og_list: og_list.append(items) print(og_list) elif items in og_list: print(og_list) return #Has duplicates function def has_duplicates(og_list): items = input("Please enter an item: ") if items not in og_list: og_list.append(items) print("true") elif items in og_list: print("false") return #The list og_list = [] #While loop to cycle through items that are added to the list while True: #user input of an item items = input("Please enter an item: ") #if the item is already there print false and print the clean list if items in og_list: print("false", og_list) continue #if the item is unique add it to the list and print the list if items not in og_list: og_list.append(items) print("true", og_list)
# # Description: Find the collisions between birds # # Author: Ninad Dipal Zambare # level_one_birds = ["A", "B", "C", "D", "E"] level_two_birds = ["B", "A", "E", "D", "C"] collisions = {} i=0 for bird1 in level_one_birds: for bird2 in level_one_birds: if bird1 != bird2 and not level_one_birds.index(bird2)< level_one_birds.index(bird1): if level_one_birds.index(bird1) < level_one_birds.index(bird2): if level_two_birds.index(bird1) > level_two_birds.index(bird2): collisions[i] = bird1 + " " + bird2 i+=1 elif level_one_birds.index(bird1) > level_one_birds.index(bird2): if level_two_birds.index(bird1) < level_two_birds.index(bird2): collisions[i] = bird1 + " " + bird2 i += 1 for i in list(collisions.keys()): print(collisions[i].split(" ")[0] + " collided with " + collisions[i].split(" ")[1]) print(collisions)
import unittest from Trees.printTree import TreeNode, Solution class TestPrintTree(unittest.TestCase): def testCase1: #single node as tree root = TreeNode(1) self.answer = [['1']] solution = Solution() self.input = solution.printTree(root) assert self.input == self.answer def testCase2: #2. full balanced tree root = TreeNode(1) root.left = TreeNode(2) root.right = TreeNode(3) root.left.left = TreeNode(4) root.left.right=TreeNode(5) root.right.left=TreeNode(6) root.right.right=TreeNode(7) self.answer = [['|', '|', '|', '1', '|', '|', '|'], ['|', '2', '|', '|', '|', '3', '|'], ['4', '|', '5', '|', '6', '|', '7']] solution = Solution() self.input = solution.printTree(root) assert self.input == self.answer def testCase3: #3. left branches tree root=TreeNode(1) root.left=TreeNode(2) root.left.left=TreeNode(3) root.left.left.left=TreeNode(4) self.answer = [['|', '|', '|', '|', '|', '|', '|', '1', '|', '|', '|', '|', '|', '|', '|'], ['|', '|', '|', '2', '|', '|', '|', '|', '|', '|', '|', '|', '|', '|', '|'], ['|', '3', '|', '|', '|', '|', '|', '|', '|', '|', '|', '|', '|', '|', '|'], ['4', '|', '|', '|', '|', '|', '|', '|', '|', '|', '|', '|', '|', '|', '|']] solution = Solution() self.input = solution.printTree(root) assert self.input == self.answer def testCase4: #4. irregular tree root =TreeNode(1) root.left=TreeNode(2) root.right=TreeNode(3) root.left.right=TreeNode(4) root.right.left=TreeNode(5) root.right.left.right=TreeNode(6) self.answer = [['|', '|', '|', '|', '|', '|', '|', '1', '|', '|', '|', '|', '|', '|', '|'], ['|', '|', '|', '2', '|', '|', '|', '|', '|', '|', '|', '3', '|', '|', '|'], ['|', '|', '|', '|', '|', '4', '|', '|', '|', '5', '|', '|', '|', '|', '|'], ['|', '|', '7', '|', '8', '|', '|', '|', '|', '|', '6', '|', '|', '|', '|']] solution = Solution() self.input = solution.printTree(root) assert self.input == self.answer
from numpy import sin, cos, pi ''' Classic Cartpole Task Reference: Bartol, A., Sutton, R. S., & Anderson, C. W. (1983). Neuro-like adaptive elements that can solve difficult learning problems. IEEE Trans. Syst., Man, Cybern, 13, 834-846.''' num_actions = 2 class Cartpole: ''' states: [x, theta, dx, dtheta] actions: [-10., +10] (Forces in Newton. Actual actions might be indexed [0, 1]) Transition is simulated by a simplified physics ''' dt = .02 GRAVITY = -9.8 # gravitational acceleration [m * s ** -2] CART_MASS = 1. # Mass of cart [kg] POLE_MASS = .1 # Mass of pole [kg] HALF_POLE_LENGTH = .5 # Half-pole length [m] FRICTION_CART = .0005 # Coefficient of friction of cart on track FRICTION_POLE = .000002 # Coefficient of friction of pole on cart AVAIL_FORCE = [-10., +10.] # Available force applied to the center of the cart [Newton] MAX_TRACK_LENGTH = 2.4 # Max length of track; Considered failure if cart moves beyong this range [m] MAX_THETA = 12 * (2 * pi / 360) # Max angle of pole; Considered failure if pole falls over this angle [radian] def __init__(self): # The cart starts at the middle of the track and the pole starts upright self._state = [0., 0., 0., 0.] def step(self, action): x, theta, dx, dtheta = self._state force = self.AVAIL_FORCE[action] g = self.GRAVITY mc = self.CART_MASS m = self.POLE_MASS l = self.HALF_POLE_LENGTH muc = self.FRICTION_CART mup = self.FRICTION_POLE ddtheta = (g * sin(theta) + cos(theta) * ((-force - m * l * dtheta ** 2 * sin(theta) + muc * sgn(dx)) / (mc + m)) - (mup * dtheta / (m * l))) \ / (l * (4 / 3 - (m * cos(theta) ** 2) / (mc + m))) ddx = (force + m * l * (dtheta ** 2 * sin(theta) - ddtheta * cos(theta)) - muc * sgn(dx)) / (mc + m) # Kinematics: Euler integration x += dx * self.dt theta += dtheta * self.dt dx += ddx * self.dt dtheta += ddtheta * self.dt self._state = [x, theta, dx, dtheta] reward = +1. done = self._terminal() return self._state, reward, done def reset(self): self.__init__() return self._state def get_state(self): return self._state def set_state(self, state): self._state = state return self._state # Determine whether self.state has reached the goal def _terminal(self): s = self._state done = s[0] < -self.MAX_TRACK_LENGTH \ or s[0] > self.MAX_TRACK_LENGTH \ or s[1] < -self.MAX_THETA \ or s[1] > self.MAX_THETA return bool(done) # Extract sign of input scaler x (a real number) def sgn(x): if x > 0: return 1 elif x < 0: return -1 else: return 0
# The definition for GridWorld -- the environment that the agent will continuously interact with import numpy as np class GridWorld: def __init__(self): self._num_rows = 5 self._num_cols = 5 self._state = (0, 0) self._t = 0 self._terminal_states = {(self._num_rows - 1, self._num_cols - 1)} # A list of terminal states self._actions = [0, 1, 2, 3] # 0, 1, 2, 3 represents 'up', 'right', 'down', 'left' respectively # Interface methods def step(self, action): self._state = self._get_next_state(self._state, action) reward = self._reward(self._state) done = self._state in self._terminal_states # The termination state is at the top-right corner of the grid world self._t += 1 return self._state, reward, done def reset(self): self._state = (0, 0) self._t = 0 return self._state def get_num_rows(self): return self._num_rows def get_num_cols(self): return self._num_cols def get_actions(self): return self._actions # Helper method for implementing the functions inside the class def _get_next_state(self, current_state, action): if action == 0: if self._state[0] == self._num_rows - 1: return current_state else: return (current_state[0] + 1, current_state[1]) elif action == 1: if self._state[1] == self._num_cols - 1: return current_state else: return (current_state[0], current_state[1] + 1) elif action == 2: if self._state[0] == 0: return current_state else: return (current_state[0] - 1, current_state[1]) else: if self._state[1] == 0: return current_state else: return (current_state[0], current_state[1] - 1) def _reward(self, state): return -1 if state in self._terminal_states else -1
# 2-D tile coding # It is used to construct (binary) features for 2-D continuous state/input space + 1-D discrete action spacce # for linear methods to do function approximation import math import numpy as np # The following three lines are subject to change according to user need # -- numTilings, x_start, x_range, y_start, y_range, num_actions # Number of total tilings numTilings = 8 # The starting point of each component of input and its range # Please enter FLOATS (e.g use 0.0 for 0) x_start, x_range = -1.2, 1.7 y_start, y_range = -0.07, 0.14 # Number of tiles per tiling in each dimension dimension # (e.g. 8 means each tile covers 1/8 of the bounded distance in x-dimension) x_num_partition = 7 y_num_partition = 7 # Number of actions available for each state num_actions = 3 # Number of total tiles per tiling # Notice we need one more in each dimension to ensure all tilings cover the input space num_tiles_per_tiling = (x_num_partition + 1) * (y_num_partition + 1) # Find the active tile indices of input (in1, in2) and store it to tileIndices def tilecode(in1, in2, tileIndices): assert len(tileIndices) == numTilings # Change coordinate of input to be based on the first tiling, where the origin is set to # the left-bottom point of the first tiling in1 = in1 - x_start in2 = in2 - y_start # Compute the offset in each dimension per tiling x_offset_per_tiling = x_range / x_num_partition / numTilings y_offset_per_tiling = y_range / y_num_partition / numTilings # The height and width of each tile y_tile = y_range / y_num_partition x_tile = x_range / x_num_partition # Compute active tile indices for each tiling for idx in range(numTilings): # Compute the coordiate of input under the new tiling coordinate system x_offset, y_offset = idx * x_offset_per_tiling, idx * y_offset_per_tiling x, y = in1 + x_offset, in2 + y_offset # index = base + num_rows * 11/row + num_col index = idx * num_tiles_per_tiling + math.floor(y / y_tile) * (x_num_partition + 1) + math.floor(x / x_tile) # A sanity check: the index of tile ranges from 0 (the first tile in the first tiling) # to numTilings * num_tiles_per_tiling - 1 (the last tile in the last tiling) assert 0 <= index <= numTilings * num_tiles_per_tiling - 1 # Write result back to tileIndices tileIndices[idx] = int(index) # Get the feature vector of a single input=(in1, in2, action) def feature(state, action): # Precondition check assert x_start <= state[0] <= (x_start + x_range) and y_start <= state[1] <= (y_start + y_range) and action in {-1, 0, 1}, 'input out of space' in1, in2 = state[0], state[1] tileIndices = [-1] * numTilings tilecode(in1, in2, tileIndices) result = np.zeros(num_tiles_per_tiling * numTilings * num_actions) for index in tileIndices: result[index + num_tiles_per_tiling * numTilings * (action+1)] += 1 return result # Test Code def printTileCoderIndices(in1, in2, action): tileIndices = [-1] * numTilings tilecode(in1, in2, tileIndices) print('Active tile indices for input (' + str(in1) + ',' + str(in2) + ', ' + str(action) + ') are : ' + str(tileIndices)) print('feature for this input is: ' + str(feature([in1,in2,action]))) if __name__ == '__main__': printTileCoderIndices(0.2, 0.01, 0) printTileCoderIndices(0.0, 0.07, 0) printTileCoderIndices(-0.5, 0.03, 1) printTileCoderIndices(-0.25, -0.01, 0)
score =int (input('请输入一个分数:')) if 100 >=score>=90: print('A') elif 90 >score>=80: print('B') elif 80>score>=60: print('C') elif 60>score>=0: print('D') else: print('输入错误!')
#!/usr/local/bin/python3 # Write a function that reverses characters in (possibly nested) parentheses # in the input string. # Input strings will always be well-formed with matching ()s. # Example # For inputString = "(bar)", the output should be # reverseInParentheses(inputString) = "rab"; # For inputString = "foo(bar)baz", the output should be # reverseInParentheses(inputString) = "foorabbaz"; # For inputString = "foo(bar)baz(blim)", the output should be # reverseInParentheses(inputString) = "foorabbazmilb"; # For inputString = "foo(bar(baz))blim", the output should be # reverseInParentheses(inputString) = "foobazrabblim". # Because "foo(bar(baz))blim" becomes "foo(barzab)blim" and then "foobazrabblim". # inputString = "foo(bar)baz", the output should be # reverseInParentheses(inputString) = "foorabbaz"; #### Using the python "eval" function.. #### Related video: https://realpython.com/lessons/python-eval-overview/ #### eval is a python built-in function that evaluates expressions #### #s = "foo(bar)baz" #s = "ab(cd)e" #print(s[4:]) # start at position X and print the rest #print(s[:4]) # start at beginning and print up and through position X #print(s[2:4]) # start to right of X and print up and through Y #Great site: https://pythex.org/ # regex notes: # /t[aeiou] -> brackets mean a range of values # [^a-zA-Z] not! # \([a-zA-Z]*\) # foo(bar)baz(blim) # matches (bar) and (blim) # Meta-characters , like white space # special meta-characters that represent a type of character like.. # Decimal digits, whitespace, words, etc. # [aeiou].[aeiou] "." means any character, except newline # Regex Anchors: # import re #You can use this, just put it above the function def. a_string = "this is a [ki_te] message" result = re.search(r"\[([A-Za-z0-9_]+)\]", a_string) print(result.group(1))
#!/usr/local/bin/python3 def shapeArea(n): sa = ((n -1) * (n -1)) + (n * n) return sa print(shapeArea(1))
def binaryToDecimal(binary): decimal = 0 index = 0 while binary > 0: lastDigit = binary % 10 binary = int(binary / 10) decimal += (lastDigit * (2**index)) index += 1 return decimal def decimalToBinary(decimal): binary = "" remainders = [] while decimal > 0: remainders.append(str(decimal % 2)) decimal /= 2 remainders.reverse() binary = "".join(remainders) return 0 if binary == "" else binary choice = int(input("Make a choice: ")) if choice == 1: binary = int(input("Binary to convert: ")) print("The binary number " + str(binary) + " in decimal is " + str(binaryToDecimal(binary))) elif choice == 2: decimal = int(input("Decimal to convert: ")) print("The decimal number " + str(decimal) + " in binary is " + str(decimalToBinary(decimal))) else: print("Invalid choice")
import json, urllib import requests import geopy.distance API_KEY = 'AIzaSyC8m1yNa6eDGE5VLR1GjQ-5Mz_WyoM-5Kc' #To be able to pass all locations in one call def addLocations(content): validArgument = '' for locations in content: validArgument += locations + '|' return validArgument #To return the latitude and longitude of a location def getLatLong(location): payload = {'address': location} response = requests.get('https://maps.googleapis.com/maps/api/geocode/json?', params = payload) parsed_json = response.json() if parsed_json['status'] == "OK": latitude = parsed_json['results'][0]['geometry']['location']['lat'] longitude = parsed_json['results'][0]['geometry']['location']['lng'] return latitude, longitude else: return "no", "no" #To calculae great circle distance def getBirdDist(lat_long): global IITB_latLong return (geopy.distance.vincenty(IITB_latLong, lat_long).meters)/1000 print "Sorted using distance by road: " #Array of lists to store locations with their distances locationDistances = [] #Araay of locations with not found locationNotFound = [] user_origin = "IIT Bombay" content = [line.rstrip('\n') for line in open('places.txt')] payload = {'origins': user_origin, 'destinations': addLocations(content), 'key': API_KEY} response = requests.get('https://maps.googleapis.com/maps/api/distancematrix/json?', params = payload) parsed_json = response.json() #A variable to increment with the loop i = 0 for row in parsed_json['rows'][0]['elements']: #If a valid path is found if row['status'] == "OK": locationDistances.append( { 'location': content[i], 'value': row['distance']['value'], 'distance': row['distance']['text'] } ) #If not else: locationNotFound.append(content[i]) i += 1 #To sort the list locationDistances.sort() sortedList = sorted(locationDistances, key= lambda locationDistances: locationDistances['value']) for i in sortedList: print i['location'] + ": " + i['distance'] for notFound in locationNotFound: print notFound + ": No path found" ################################################################################################################################# #To calculate the bird's line distance print " " print "Sorted using bird's line distance: " #To empty the lists del locationDistances[:] del locationNotFound[:] lat_long = [] IITB_latLong = getLatLong("IIT Bombay") i = 0 for place in content: latitude, longitude = getLatLong(place) #if valid latitude is there if latitude != "no": locationDistances.append( { 'value': getBirdDist((latitude, longitude)), 'location': content[i] } ) else: locationNotFound.append(content[i]) i += 1 locationDistances.sort() sortedList = sorted(locationDistances, key= lambda locationDistances: locationDistances['value']) for i in sortedList: print i['location'] + ": " + str(i['value']) + " km" for notFound in locationNotFound: print notFound + ": No path found"
import random import words words = open('words.py').read().strip().split('", "') word = random.choice(words) print(word) #On créer notre compteur pour chaque coup de l'utilisateur compteur = 20 #On demande à l'utilisateur de rentrer une lettre while compteur != 0 : for i in word : letter = input('Entrer une lettre :') if len(letter)<= 1: print("Vous avez mis 2 lettres tricheur !") if i == letter : print("Cette lettre appartient au mot",i) elif i != letter : #si la lettre n'est pas dans le mot print("_") #les lettres manquantes print("Cette lettre n'appartient pas au mot") compteur-=1 print("Il vous reste " + str(compteur) + " coup") if i == word : #s'il devine le mot print(word) print("Vous avez gagnée") if compteur == 0 : print("Vous avez perdu")
class EmotionData: def __init__(self, joy = -1, anger = -1, disgust = -1, sadness = -1, fear = -1): self.joy = joy # float between 0 and 1 self.anger = anger self.disgust = disgust self.sadness = sadness self.fear = fear class ReviewData: def __init__(self, score = -2, label = "", emotionData = EmotionData(), keywords = [], concepts = []): self.sentiment_score = score # float between -1 and 1 self.sentiment_label = label # positive or negative self.emotion_data = emotionData # new EmotionData object self.keywords = keywords # array of keyword objects self.concepts = concepts # array of concept objects referenced by the text that may not be explicitly there # Potential design decision: keyword and concept inherit from the same base class, # which reduces repetition but still makes it possible to add different fields in the future class Keyword: def __init__(self, text = "", relevance = -1): self.text = text self.relevance = relevance # float between 0 and 1 class Concept: def __init__(self, text = "", relevance = -1): self.text = text self.relevance = relevance # float between 0 and 1
import random from plane import Plane, sign class Environment: def __init__(self): self.plane = Plane() def turbulence(self): self.plane.current_angle += (random.random() -0.5) * 90 return self.plane.current_angle def flight(self): while True: self.turbulence() m_string = "Current angle: {} Correction: {}".format(self.plane.current_angle, self.plane.correction()) yield m_string self.plane.current_angle + self.plane.correction() def run(self,user_input): self.plane.current_angle = 90 new_flight = self.flight() while user_input in ['y', 'yes']: if self.plane.is_crashed(): print("Sorry, Your plane crashed!") break print(next(new_flight)) user_input = input("Do You want to continue flynig?\n\r") else: print("We are landing")
__author__ = 'warrickmoran' # # General Read/Write methods from Python 101 # def file_read(filename): """ Read File Contents """ try: with open(filename, 'r') as handler: data = handler.readlines() # read ALL the lines! print(data) except IOError: print("An IOError has occurred!") def file_write(filename): """ Write File """ try: with open(filename,'w') as handler: handler.write("This is a test!") except IOError: print("An IOError has occurred!") if __name__ == '__main__': file_read() file_write()
# -*- coding: utf-8 -*- """ Created on Wed Mar 28 18:19:15 2018 @author: Administrator """ class Tower: """Course-Week2:Simple Programs-4.Functions-Video:TowersofHanoi-method1 """ def __init__(self): self.counter = 0 def hanoi(self, n, a, c, b): if n == 1: self.counter += 1 print('count ' + str(self.counter) + ', move from {0}->{1}'.format(a, b)) else: self.hanoi(n-1, a, b, c) self.hanoi(1, a, c, b) self.hanoi(n-1, b, c, a) tower = Tower() tower.hanoi(4,"a", "c", "b") def Towers(n,fr,to ,spare): """Course-Week2:Simple Programs-4.Functions-Video:TowersofHanoi-method2 """ if n==1: printMove(fr,to) else: Towers(n-1,fr,spare,to) Towers(1,fr,to,spare) Towers(n-1,spare,to,fr) def printMove(fr,to): global count count+=1 print('count '+str(count)+", move from "+ str(fr)+" to "+str(to)) count = 0 Towers(4,'a','b','c')
import re, math from main import * from collections import Counter from start import * WORD = re.compile(r'\w+') def get_cosine(vec1, vec2): intersection = set(vec1.keys()) & set(vec2.keys()) numerator = sum([vec1[x] * vec2[x] for x in intersection]) sum1 = sum([vec1[x]**2 for x in vec1.keys()]) sum2 = sum([vec2[x]**2 for x in vec2.keys()]) denominator = math.sqrt(sum1) * math.sqrt(sum2) if not denominator: return 0.0 else: return float(numerator) / denominator def text_to_vector(text): words = WORD.findall(text) return Counter(words) text1 = summaries1 text2 = summaries2 text3 = summaries3 vector1 = text_to_vector(text1) vector2 = text_to_vector(text2) vector3 = text_to_vector(text3) cosinea = get_cosine(vector1, vector2) print 'Cosine12:', cosinea if cosinea > 0.5: result12 = summaries1 + summaries2 print Summarize("",result12) cosineb = get_cosine(vector2, vector3) print 'Cosine23:', cosineb if cosineb > 0.5: result23 = summaries3 + summaries2 print Summarize("",result23) cosinec = get_cosine(vector1, vector3) print 'Cosine13:', cosinec if cosinec > 0.5: result13 = summaries1 + summaries3 print Summarize("",result13)
board=["-","-","-", "-","-","-", "-","-","-"] game_still_going=True #who win winner=None #turn of player current_player="X" def display_board(): print(board[0]+"|"+board[1]+"|"+board[2]) print(board[3]+"|"+board[4]+"|"+board[5]) print(board[6]+"|"+board[7]+"|"+board[8]) def play_game(): #initail board display display_board() while game_still_going: player_turn(current_player) check_if_game_over() flip_player() if winner=="X" or winner=="O": print(winner+" won") elif winner==None: print("Tie!!") def player_turn(player): print(player+"'s turn") position=input("Enter the number from 1 to 9:") valid=False while not valid: while position not in ["1","2","3","4","5","6","7","8","9"]: position=input("Enter the number from 1 to 9:") position=int(position)-1 if board[position]=="-": valid=True else: print("Already occupied") board[position]=player display_board() def check_if_game_over(): check_if_win() check_if_tie() def check_if_win(): global winner if row_winner(): winner=row_winner() elif col_winner(): winner=col_winner() elif dgnal_winner(): winner=dgnal_winner() else: winner=None return def row_winner(): global game_still_going row_1=board[0]==board[1]==board[2]!="-" row_2=board[3]==board[4]==board[5]!="-" row_3=board[6]==board[7]==board[8]!="-" if row_1 or row_2 or row_3: game_still_going=False if row_1: return board[0] elif row_2: return board[3] elif row_3: return board[6] return def col_winner(): global game_still_going col_1=board[0]==board[3]==board[6]!="-" col_2=board[1]==board[4]==board[7]!="-" col_3=board[2]==board[5]==board[8]!="-" if col_1 or col_2 or col_3: game_still_going=False if col_1: return board[0] elif col_2: return board[1] elif col_3: return board[2] return def dgnal_winner(): global game_still_going diag_1=board[0]==board[4]==board[8]!="-" diag_2=board[6]==board[4]==board[2]!="-" if diag_1 or diag_2: game_still_going=False if diag_1: return board[0] elif diag_2: return board[2] return def check_if_tie(): global game_still_going if "-" not in board: game_still_going=False return def flip_player(): global current_player if current_player == "X": current_player="O" elif current_player == "O": current_player="X" return play_game()
A = [[0] * 10] * 10 # вроде бы это обычный список списков 10х10 состоящий из 0 A[0][0] = 1 # меняем элемент с индексом 0 в списке с индексом 0 print(A[1][0]) # печатаем элемент с индексом 0 в списке с индексом 1
# Ejercicio 024_Intro_BlockOrientation # Donde se muestra como cambiar la direccion o orientacion del voxel # Usamos de forma mas eficiente la variable blockType # Connect to Minecraft from mcpi.minecraft import Minecraft mc = Minecraft.create() # 53 es Oak Wood Stairs blockType = 53 # Coordenadas iniciales x = 10 y = 4 z = 10 # El bloque solo con su ID sin [data] despues de la coma mc.setBlock(x, y, z, blockType) # Direccion -X o OESTE # El bloque con [data] despues de la coma mc.setBlock(x, y, z+2, blockType,0) # Direccion -X o OESTE hacia donde se pone el Sol mc.setBlock(x, y, z+4, blockType,1) # Direccion +X o ESTE donde sale el Sol mc.setBlock(x, y, z+6, blockType,2) # Direccion -Z o NORTE mc.setBlock(x, y, z+8, blockType,3) # Direccion +Z o SUR mc.setBlock(x, y, z+10, blockType,4) # Direccion -X o OESTE Invetido mc.setBlock(x, y, z+12, blockType,5) # Direccion +X o ESTE Invertido mc.setBlock(x, y, z+14, blockType,6) # Direccion -Z o NORTE Invertido mc.setBlock(x, y, z+16, blockType,7) # Direccion +Z o SUR Invertido mc.setBlock(x, y, z+18, blockType,8) # Cualquier valor de [data] que no existe se convierte en 0 mc.setBlock(x, y, z+20, blockType,9) # y se pone el bloque hacia -X mc.setBlock(x, y, z+22, blockType,10) mc.setBlock(x, y, z+24, blockType,11) mc.setBlock(x, y, z+26, blockType,12) mc.setBlock(x, y, z+28, blockType,13) mc.setBlock(x, y, z+30, blockType,14) mc.setBlock(x, y, z+30, blockType,15)
## Basic feature extraction using text data # Number of words # Number of characters # Average word length # Number of stopwords # Number of special characters # Number of numerics # Number of uppercase words import pandas as pd from nltk.corpus import stopwords stop = stopwords.words('english') ## to increase the display width and display it on the same line pd.set_option('display.max_rows', 500) pd.set_option('display.max_columns', 500) pd.set_option('display.width', 1000) ## function to calculate the average-word-length in a sentence def avg_word(sentence): words = str(sentence).split() return (sum(len(word) for word in words)/len(words)) ## to read the csv file train = pd.read_csv('./Inputs/Hoteldata.csv', low_memory=False) # train = pd.read_csv('sampleData.csv') # print(train) # print(train.head()) ## to calculate the word-Count in the comments train['word_Count'] = train['Comment'].apply(lambda x: len(str(x).split(" "))) ## to calculate the char-count in the comments train['char_Count'] = train['Comment'].str.len() #this will also include blank spaces ## to calculate the average word length of the sentence train['avg_word'] = train['Comment'].apply(lambda x: avg_word(x)) ## to count the stopwords # Some examples of stop words are: "a," "and," "but," "how," "or," and "what." train['stopwords'] = train['Comment'].apply(lambda x: len([x for x in str(x).split() if x in stop])) ## to count the number of special characters starting with hashtags. train['hashtags'] = train['Comment'].apply(lambda x: len([x for x in str(x).split() if x.startswith('#')])) ## to count the number of numerics train['numerics'] = train['Comment'].apply(lambda x: len([x for x in str(x).split() if x.isdigit()])) ## to count the number of Uppercase words train['upper'] = train['Comment'].apply(lambda x: len([x for x in str(x).split() if x.isupper()])) ## to print the array of all the pre-processes... print(train[['Comment','word_Count','char_Count','avg_word','stopwords','hashtags','numerics','upper']]) train.to_csv('./Outputs/output-main1.csv')
#!/usr/bin/env python3 """Learn how to use tuples Usage: python3 tuples.py """ # tuples are defined with (), are immutable # t is the global scoped object for this module t = ("Norway", 4.953, 3) def loop(tpl): for item in tpl: print(item) print("length of the tuple is ", len(tpl)) print(__name__) def main(): loop(t) if __name__ == "__main__": main() elif __name__ == "tuples": pass else: print("not called properly") # a, b = b, a is the idiomatic Python swap # "".join(["high", "way", "man"]) will produce "highwayman", another cool python property # "yaşım {kek[0]}, adım {kek[1]} , arkadaşımın adı {kek[2][0]}, yaşı {kek[2][1]}".format(kek = kek) # 'yaşım 123, adım ksdk , arkadaşımın adı hj, yaşı 23'
''' String 조작하기 1.글자합체 string + string 2.글자삽임(수술) 3.글자 자르기 ''' #1.글자합체 hphk ="happy" + "hacking" print(hphk) #2.글자삽입 name="hj" age=27 text="안녕하세요. 제이름은 {}입니다. 나이는 {}세 입니다.".format(name, age) print(text) f_text= f"제이름은 {name}입니다. 나이는 {age}세 입니다." print(f_text) #3. 글자자르기 #string> "어떠한 글자들"[start:end] text_name = text[:17] #처음부터 17까지 print(text_name) text_age = text[19:] #19부터 끝까지 print(text_age) text_split = text.split() print(text_split)
import os import csv # Path to collect data from the Resources folder election_csv = os.path.join('Resources', 'election_data.csv') #read in the csv file with open(election_csv,'r') as csvfile: csv_reader = csv.reader(csvfile,delimiter = ',') #skip header row csv_header = next(csvfile) #create lists and assign variables total_votes = 0 candidates = [] vote_counter = [] #loop through rows in csv file for row in csv_reader: #total votes counter total_votes += 1 #stores candidate names and vote counts into two lists name = str(row[2]) if name in candidates: #looks up index location of name in candidate list. Once you have that index number #you can use that to look up the corresponding value in the vote_counter list candidate_index = candidates.index(name) vote_counter[candidate_index] = vote_counter[candidate_index] + 1 else: #if name is not already in the list it adds it to candidates and adds 1 vote to vote_counter candidates.append(name) vote_counter.append(1) #create more lists and assign variables percentage = [] most_votes = vote_counter[0] winner = 0 for x in range(len(candidates)): #loops through and calculates vote % and stores in a new list called percentages vote_percentage = round(vote_counter[x] / total_votes * 100, 2) percentage.append(vote_percentage) #loop goes through vote_counter list and determines index location that has the most votes if vote_counter[x] > most_votes: most_votes = vote_counter[x] winner = x #returns the name of the winner in the candidates list. Use the index location determined in the if statement above^ election_winner = candidates[winner] #prints results print("Election Results") print("------------------------") print(f"Total Votes: {total_votes}") print("------------------------") for x in range(len(candidates)): print(f"{candidates[x]}: {percentage[x]}% ({vote_counter[x]})") print("------------------------") print(f"Winner: {election_winner}") print("------------------------") #specifies the file path for output txt file results_path = os.path.join("poll.txt") poll = open(results_path, "w+") #write output to txt file poll.write(f"Election Results" + "\n") poll.write(f"------------------------" + "\n") poll.write(f"Total Votes: {total_votes}" + "\n") poll.write(f"------------------------" + "\n") for x in range(len(candidates)): poll.write(f"{candidates[x]}: {percentage[x]}% ({vote_counter[x]})" + "\n") poll.write(f"------------------------" + "\n") poll.write(f"Winner: {election_winner}" + "\n") poll.write(f"------------------------" + "\n")
import unittest from app.models import News class NewsTest(unittest.TestCase): def setUp(self): ''' test to run before each test ''' self.news_sources=News('abc-au', "ABC News",'https://abcnews.go.com') def test_instance(self): ''' test case to confirm the object is an instance of the news ''' self.assertTrue(isinstance(self.news_sources,News)) def test_init(self): ''' test case to confirm the object is initialised correctly ''' self.assertEqual(self.news_sources.id,"abc-au") self.assertEqual(self.news_sources.name, "ABC News") self.assertEqual(self.news_sources.url, "https://abcnews.go.com")
# Python program for Dijkstra's single # source shortest path algorithm. The program is # for adjacency matrix representation of the graph # Library for INT_MAX import sys class Graph(): def __init__(self, ver): self.V = ver self.graph = [[0 for colu in range(ver)] for row in range(ver)] def printSolution(self, distanceance): print "Vertex tdistanceanceance from Source" for node in range(self.V): print node,"t",distanceance[node] # A utility function to find the vertex with # minimum distanceanceance value, from the set of ver # not yet included in shortest path tree def mindistanceanceance(self, distanceance, sptSet): # Initilaize minimum distanceanceance for next node min = sys.maxint # Search not nearest vertex not in the # shortest path tree for v in range(self.V): if distanceance[v] < min and sptSet[v] == False: min = distanceance[v] min_index = v return min_index # Funtion that implements Dijkstra's single source # shortest path algorithm for a graph represented # using adjacency matrix representation def dijkstra(self, src): distanceance = [sys.maxint] * self.V distanceance[src] = 0 sptSet = [False] * self.V for cout in range(self.V): # Pick the minimum distanceanceance vertex from # the set of ver not yet processed. # u is always equal to src in first iteration u = self.mindistanceanceance(distanceance, sptSet) # Put the minimum distanceanceance vertex in the # shotest path tree sptSet[u] = True # Update distanceance value of the adjacent ver # of the picked vertex only if the current # distanceanceance is greater than new distanceanceance and # the vertex in not in the shotest path tree for v in range(self.V): if self.graph[u][v] > 0 and sptSet[v] == False and distanceance[v] > distanceance[u] + self.graph[u][v]: distanceance[v] = distanceance[u] + self.graph[u][v] self.printSolution(distanceance)