text
stringlengths
37
1.41M
#print numbers in a Z within a NxN matrix def printz(n): num = 1 matrix = [[0]*n for i in xrange(n)] for i in xrange(n): for j in xrange(n): if i == 0 or i == n-1 or j == (n-i-1): if num > 9: for d in str(num): num = int(d[-1]) matrix[i][j] = num num += 1 for row in matrix: print row printz(5)
#Write a function that takes an array of unsorted integers & a sum. #Returns a boolean if 2 integers within the array sum to the given sum def array_sum(arr, summ): """ >>> array_sum([1, 5, 3], 8) True >>> array_sum([1, 5, 3], 9) False """ #sort an array O(nlogn) sorted_array = sorted(arr) for i in range(len(arr)): remain = summ - sorted_array[i] if binary_search(sorted_array, remain): return True return False #RunTime: O(logn) def binary_search(sorted_array, remain): """ >>> binary_search([1, 3, 5], 3) True >>> binary_search([1, 3, 5], 4) False """ if len(sorted_array) == 0: return False else: mid_point = len(sorted_array)//2 if sorted_array[mid_point] == remain: return True elif remain < sorted_array[mid_point]: lower = sorted_array[:mid_point] return binary_search(lower, remain) else: upper = sorted_array[mid_point+1:] return binary_search(upper, remain) if __name__ == '__main__': import doctest doctest.testmod()
""" Infix to Postfix Evaluation Count number of particles in a chemistry expression Input: '((H2O)300(AM4B)6)2000' '( ( H2O ) 300 ( AM4B ) 6 ) 2000' Output: 1,872,000 """ def infix(expr): input_list = expr.split() #['(', '(', 'H2O', ')', '300', '(', 'AM4B', ')', '6', ')', '2000'] output_list = [] i = 0 while i < len(input_list): if input_list[i] == ")": output_list.append(input_list[i]) output_list.append("*") elif input_list[i] == "(" and input_list[i-1] != "(" and i != 0: output_list.append("+") output_list.append(input_list[i]) else: output_list.append(input_list[i]) i += 1 return output_list #['(', '(', 'H2O', ')', '*', '300', '+', '(', 'AM4B', ')', '*', '6', ')', '*', '2000'] def postfix(expr2): prec = { '*': 3, '/': 3, '+': 2, '-': 2, '(': 1 } op_stack = [] postfix_list = [] for token in expr2: if token not in prec and token != ')': postfix_list.append(token) elif token == '(': op_stack.append(token) elif token == ')': top_token = op_stack.pop() while top_token != '(': postfix_list.append(top_token) top_token = op_stack.pop() else: while len(op_stack) != 0 and (prec[op_stack[-1]] >= prec[token]): postfix_list.append(op_stack.pop()) op_stack.append(token) while len(op_stack) != 0: postfix_list.append(op_stack.pop()) return postfix_list #['H2O', '300', '*', 'AM4B', '6', '*', '+', '2000', '*'] def eval_str(expr3): output_list = [] for element in expr3: if element == '*' or element == '+': output_list.append(element) elif element.isdigit() == True: output_list.append(int(element)) else: total_num = 0 char_num = 0 for i in range(len(element)): if element[i].isdigit(): char_num += 1 total_num += int(element[i]) output_list.append(len(element)-(char_num*2)+total_num) return output_list #[3, 300, '*', 6, 6, '*', '+', 2000, '*'] def postfix_eval_expr(expr4): #expr4 = [3, 300, '*', 6, 6, '*', '+', 2000, '*'] operand_stack = [] for element in expr4: if element != '*' and element != '+': operand_stack.append(element) else: if element == '*': new = operand_stack.pop() * operand_stack.pop() operand_stack.append(new) if element == '+': new = operand_stack.pop() + operand_stack.pop() operand_stack.append(new) return operand_stack[0] #1,872,000 expr2 = infix('( ( H2O ) 300 ( AM4B ) 6 ) 2000') expr3 = postfix(expr2) expr4 = eval_str(expr3) postfix_eval_expr(expr4)
#Exercise 2.7 of Cracking the Coding Interview #Given 2 singly linked lists, deterine if the 2 lists intersect. Return the intersecting node. #Note that the intersection is defined based on reference, not value. #That is, if the kth node of the 1st linked list is the exact same node as the jth node of the second linked list, then they are intersecting ################################################################################# #Initial Naive Solution (not shown): Reverse the linked lists and traverse backwards. Cannot reverse linked lists when reversing linked list 1, will alter linkedlist2 #Time: O(m*n) #Space: O(1) from linked_list import * def intersecting_node(ll1, ll2): """ Nested for loops >>> ll1 = LinkedList() >>> ll1.data_to_list([3, 6, 9, 15, 30]) >>> ll2 = LinkedList() >>> ll2.data_to_list([10, 15, 30]) >>> intersecting_node(ll1, ll2) Node(15) """ current1 = ll1.head current2 = ll2.head while current1 != None: while current2 != None: if current1.data == current2.data: return current1 current2 = current2.next current2 = ll2.head current1 = current1.next return None # CTCI Interview Solution # """ # 1. Run through each linked list to get lengths & tails # 2. Compare tails (by reference not value). If different, return False - do not intersect # 3. Set 2 pointers @ start of each linked list # 4. On longer linked list, advance pointer by diff of lengths # 5. Traverse until pointers are the same # """ def intersecting_node2(ll1, ll2): """ >>> ll1 = LinkedList() >>> ll1.data_to_list([3, 6, 9, 15, 30]) >>> ll2 = LinkedList() >>> ll2.data_to_list([10, 15, 30]) >>> intersecting_node(ll1, ll2) Node(15) """ current1 = ll1.head current2 = ll2.head len1 = 0 len2 = 0 while current1 != None: len1 += 1 current1 = current1.next while current2 != None: len2 += 1 current2 = current2.next if current1 is not current2: return False # there is no intersection current1 = ll1.head current2 = ll2.head if len1 > len2: for i in range(len1-len2): current1 = current1.next elif len2 > len1: for i in range(len2-len1): current2 = current2.next while current1.data != current2.data: current1 = current1.next current2 = current2.next return current1 ######################################################################################### if __name__ == "__main__": import doctest doctest.testmod()
grade = int(input("Input grade ")) ''' if (grade >= 70) : print("Pass") if (grade <70) : print("Fail") ''' if (grade<59) : print ("F") elif(grade<69) : print("D") elif(grade<79) : print("C") elif(grade<89) : print("B") elif(grade<100) : print("A")
#problem 1 raw_numbers = input ('''Input at least three numbers separated by a space >>>''') print('''These are your numbers ######################### ''' + raw_numbers) cooked_numbers = raw_numbers.split(" ") og_number = -1000000000000000000000000000000000 for number in cooked_numbers : if int(number) > og_number : og_number = int(number) print ('''This is your highest number ########################## ''' + str(og_number))
def find_min_val(values) : new_val = values[0] for value in values : if new_val > value : new_val = value return new_val def find_position(values, element): index = 0 for value in values: if value == element: return index index += 1 def selection_sort(values): count = 0 while (count < len(values)) : smallest_value = find_min_val(values[count: ]) position = find_position (values,smallest_value) values[position] = values[count] values[count] = smallest_value count += 1 return values unsorted = [7,3,6,4,9,1,0,23,4,5,100] print(selection_sort(unsorted))
""" Below functions are for exercise for sorting """ def load_data(file_name): """ Function for loading data """ try: with open(file_name, 'r') as raw_data: data = [] for items in raw_data: lines = list(items.strip().split(' ')) lines[0] = int(lines[0]) lines[1] = int(lines[1]) data.append(lines) return data except FileNotFoundError as error: print(error) def get_sorted_data(input_data, user_type, user_order): """ Function for get data in both ascending and descending """ if user_order == 'asc': sorted_data = sorted( input_data, key=lambda line: line[user_type], reverse=True) elif user_order == 'desc': sorted_data = sorted(input_data, key=lambda line: line[user_type]) return sorted_data def write_files(sorted_data, input_column): """ Function for write data """ try: with open(f'order_by_{input_column}.txt', 'w') as txt_file: for item in sorted_data: raw_data = ' '.join([str(elem) for elem in item]) txt_file.write(str(raw_data) + '\n') return except FileNotFoundError as error: print(error)
import students_manager as sm import sys STUDENTS_FILE_NAME = 'students.txt' STUDENTS_FINAL_FILE_NAME = 'final_students.txt' MAX_PASSWORD_TRAILS = 3 if __name__ == '__main__': # 1.Read and load the students in runtime memory sm.load_students(STUDENTS_FILE_NAME) # 2. Prompt for student ID student_id = input("Please enter your student ID: ") # 3. Check if the student id is valid if not sm.is_valid_id(student_id): print("The provided student id was not found!") sys.exit(1) # 4. Prompt for a valid password trials = 0 is_valid_password = False user_password = input("Please enter a valid password: ") is_valid_password = sm.is_valid_password(user_password) while not is_valid_password and trials < MAX_PASSWORD_TRAILS -1: user_password = input("Invalid password, please try again: ") is_valid_password = sm.is_valid_password(user_password) trials += 1 if not is_valid_password: print("You have exhausted your password trials." "Please restart again") sys.exit(1) # 5. Update the student record with the provided password student_record = sm.get_student_record(student_id) student_record = student_record.replace('\n', '') student_record = f'{student_record},password:{user_password}\n' if sm.update_final_list(STUDENTS_FINAL_FILE_NAME, student_id, student_record): print("Your record was successfully updated!") else: print("Relax, your record is already up to date!")
# Первая вариация цикла i = 1000 while i > 100: print(i) i /= 2 # Вторая вариация, данная конструкция перебирает строку for j in 'hello world': if j == 'w': # из цикла можно выйти break или пропустить итеррацию continue # end = '' позволяет написать все в одну строку print(j * 2, end = '') # если break и continue не сработали, то можно поставить оператор else после цикла (ровно под ним) # таким образом выполнится запасное действие
# def - обозачение начала функции def funk1(x, a): return x + a def funk2(x): def add(a): return x + a return add # передедовать, так и возвращать можно как списки, так и строки print(funk1(23, 12)) #в данном случае в переменную записыватеся первая функция funk2() #следующим действием мы передаем еще одно значение в test(), но это мы уже работаем #с внутренней функцией и выводим оезультат test = funk2(100) print(test(200)) # функции могут ничего не возвращать, чтобы это сделать, нало в конце ф-ии добавть словао pass, такакя # ф-я выведет None def funk3(): pass print(funk3()) # в ф-ю можно передавать параметры по умолчанию def funk4(r, w, y = 2): res = r + w res *= y return res print(funk4(2,4)) # в ф-ю можно передавать не ограниченное количество параметров, с помощью * # стоит учесть, что передается непосредственно кортеж, соответственно, его изменить нельзя def funk5(*args): return args print(funk5(2, 4, 5, 6)) #Чтобы передать словарь в качестве параметров, то нужно поставить ** def funk6(**args): return args print(funk6(a=2, b=4, c=5, d=6)) print(funk6(short='dict', longer='dictionary')) #анонимные функции, выводится в одну строку add = lambda x, y: x * y print(add(34, 23)) #без создания переменной print((lambda x, y: x * y)(45, 66))
""" 移动图形 """ from tkinter import * root = Tk() cv = Canvas(root, bg='white', width=200, height=120) rt1 = cv.create_rectangle(20, 20, 110, 110, outline='red', stipple='gray12', fill='green') cv.pack() rt2 = cv.create_rectangle(20, 20, 110, 110, outline='blue') # 移动rt1 cv.move(rt1, 20, -10) cv.pack() root.mainloop()
''' class: ADXL345 Purpose: This class is used to communicate through the SMbus and collect information from the accelerometer. Methods: Constants: These constants are used throughout the code of the ADXL345 class and have been provided by the manufacturer. __init__: constructor for the ADXL345 begin: Used to check that the accelerometer is connected properly to pi and the explorer hat and that eveything is communicating properly to each other. write_register: takes a value and gives it to the accelerometer through smbus methods while making sure to open and close lines of communication properly read_register: similar to previous method except it returns a value from the ADXL345 but it needs a register to be given to know which one to read from values for used registers are defined in the constants at the top of the class. read_16: used to read a word instead of just a byte by reading a byte, shifting it to the higher bits then reading another byte. get_x, get_y, get_z: returns properly formatted data from the accelerometer with the length of a word for each of the x, y, and z axes respectively. ''' import mySmbus class ADXL345: ADXL345_ADDRESS = 0x53 # Assumes ALT address pin low ADXL345_REG_DEVID = 0x00 # Device ID ADXL345_REG_POWER_CTL = 0x2D # Power-saving features control ADXL345_REG_DATAX0 = 0x32 # X-axis data 0 ADXL345_REG_DATAY0 = 0x34 # Y-axis data 0 ADXL345_REG_DATAZ0 = 0x36 # Z-axis data 0 def __init__(self): self.mySmbus = mySmbus # self.bus = smbus.SMBus() self.BUS_ID = 1 self.range = 0 def begin(self): # check connection self.mySmbus.my_my_init() device_id = self.read_register(self.ADXL345_REG_DEVID) if device_id != 0xe5: # No ADXL345 detected ... return false #print(format(device_id, '02x')) # print(device_id) return False # enable measurements self.write_register(self.ADXL345_REG_POWER_CTL, 0x08) self.mySmbus.my_my_uninit() return True def write_register(self, reg, value): # self.bus.open(self.BUS_ID) self.mySmbus.my_my_init() self.mySmbus.my_i2c_write_byte_data(self.ADXL345_ADDRESS, reg, value) self.mySmbus.my_my_uninit() # self.bus.close() def read_register(self, reg): # self.bus.open(self.BUS_ID) temp = self.mySmbus.my_my_init() reply = self.mySmbus.my_i2c_read_byte_data(self.ADXL345_ADDRESS, reg) self.mySmbus.my_my_uninit() # self.bus.close() return reply def read_16(self, reg): # self.bus.open(self.BUS_ID) self.mySmbus.my_my_init() reply = self.mySmbus.my_i2c_read_word_data(self.ADXL345_ADDRESS, reg) self.mySmbus.my_my_uninit() # self.bus.close() return reply def get_x(self): return self.read_16(self.ADXL345_REG_DATAX0) def get_y(self): return self.read_16(self.ADXL345_REG_DATAY0) def get_z(self): return self.read_16(self.ADXL345_REG_DATAZ0)
n=int(input()) name_number=[input().split() for _ in range(n)] phoneBook={k:v for k,v in name_number} while True: try: name=input() if name in phoneBook: print(str(name) +'=' + phoneBook[name]) else: print('Not found') except: break
def judge(moveA, moveB): if moveA == 'rock' and moveB == 'paper': return False elif moveA == 'rock' and moveB =='scissors': return True elif moveA == 'paper' and moveB == 'rock': return True elif moveA == 'paper' and moveB == 'scissors': return False elif moveA == 'scissors' and moveB == 'rock': return False else: return True
#def display_winner(winner, msg): # if winner == 'Player': # outcome = 'You win! ' # else: # outcome = 'Computer wins! ' # # print(outcome + '(' + msg + ')') # Test the function #display_winner('Player', 'You were closest to 21') # Expected: #You win! (You were closest to 21) #display_winner('Computer', 'It was closest to 21') # Expected: #Computer wins! (It was closest to 21) #display_winner('Computer', 'You busted') # Expected: Computer #wins! (You busted) # Import statements should always be at the top of your file, not in the body of functions #import random #def draw_random_card(): # cards = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 11] # random.shuffle(cards) # return cards.pop() # Test the function #print(draw_random_card()) # Expected: Random number b/n 1 & 11 #print(draw_random_card()) # Expected: Random number b/n 1 & 11 #print(draw_random_card()) # Expected: Random number b/n 1 & 11 #def multiply(a, b): # result = a * b # return result # Test the function: #solution = multiply(4, 5) # Invoke multiply giving it the arguments 4 and 5 #print(solution) # Expected: 20 #def mystery(x, y, z): # mystery = x + z * y # return mystery # Test this function: #print mystery('Hello', 3, '!') # Expected: 'Hello!!!' #print mystery('Goodbye', 2, '@') # Expected: 'Goodbye@@' def calculate_tip(meal_cost, rating): if rating == 'A': percentage = .20; elif rating == 'B': percentage = .18; else: percentage = .15; tip = meal_cost * percentage; return tip print(calculate_tip(30.50, 'C')) # Expected: 4.575 print(calculate_tip(15.00, 'B')) # Expected: 2.7 print(calculate_tip(20.00, 'A')) # Expected: 4 #print(multiply(4,5)) # Test the function #print(multiply(4,5)) # 20 #print(multiply(9,11)) # 99 #print(multiply(0,10)) # 0 #print(multiply(.5,9)) # 4.5 #print(multiply(-1,-55)) # 55 #print(multiply(3, 'Hello ')) # 'Hello Hello Hello' #def isPositive(a): # if a > 0: # return True # else: # return False #print(isPositive(-4)) # Expected: False #print(isPositive(4)) # Expected: True #print(isPositive(-9.9)) # Expected: False #print(isPositive(9.9)) # Expected: True
#Name: sliding_puzzle_3x3.py #Purpose: Play the 3x3 sliding puzzle #Author: Brian Dumbacher import random def isPuzzleSolved(puzzle): return puzzle == [["1","2","3"],["4","5","6"],["7","8"," "]] def slidesValid(puzzle): slides = [] iBlank = 0 jBlank = 0 for i in [0,1,2]: for j in [0,1,2]: if puzzle[i][j] == " ": iBlank = i jBlank = j for i in [n for n in [iBlank-1,iBlank+1] if n in [0,1,2]]: slides.append(puzzle[i][jBlank]) for j in [n for n in [jBlank-1,jBlank+1] if n in [0,1,2]]: slides.append(puzzle[iBlank][j]) return slides def randomPuzzle(): puzzle = [["1","2","3"],["4","5","6"],["7","8"," "]] numSlides = 0 while isPuzzleSolved(puzzle) or numSlides < 50: random.seed() slides = slidesValid(puzzle) slide = slides[random.randint(0, len(slides) - 1)] puzzle = updatePuzzle(puzzle, slide) numSlides += 1 return puzzle def printPuzzle(puzzle): print("") print("@@@@@@@@@@@@@@@@@@@") print("@ @ @ @") print("@ " + puzzle[0][0] + " @ " + puzzle[0][1] + " @ " + puzzle[0][2] + " @") print("@ @ @ @") print("@@@@@@@@@@@@@@@@@@@") print("@ @ @ @") print("@ " + puzzle[1][0] + " @ " + puzzle[1][1] + " @ " + puzzle[1][2] + " @") print("@ @ @ @") print("@@@@@@@@@@@@@@@@@@@") print("@ @ @ @") print("@ " + puzzle[2][0] + " @ " + puzzle[2][1] + " @ " + puzzle[2][2] + " @") print("@ @ @ @") print("@@@@@@@@@@@@@@@@@@@") print("") return def validSlide(puzzle, slide): return slide in slidesValid(puzzle) def updatePuzzle(puzzle, slide): iBlank = 0 jBlank = 0 iSlide = 0 jSlide = 0 for i in [0,1,2]: for j in [0,1,2]: if puzzle[i][j] == " ": iBlank = i jBlank = j elif puzzle[i][j] == slide: iSlide = i jSlide = j puzzle[iBlank][jBlank] = slide puzzle[iSlide][jSlide] = " " return puzzle def printEndPuzzle(numSlides): print("==================================================") print("You solved the 3x3 sliding puzzle in " + str(numSlides) + " slides.") print("==================================================") print("") return def playPuzzle(puzzleStart): #Parameters solveFlag = False puzzle = puzzleStart numSlides = 0 #Slide loop while solveFlag == False: printPuzzle(puzzle) slide = "" while not validSlide(puzzle, slide): slide = input("Slide: ") numSlides += 1 puzzle = updatePuzzle(puzzle, slide) solveFlag = isPuzzleSolved(puzzle) printPuzzle(puzzle) printEndPuzzle(numSlides) return def main(): #Global parameters loopFlag = True #Game loop while loopFlag: puzzleStart = randomPuzzle() playPuzzle(puzzleStart) newPuzzle = "" while newPuzzle not in ["n", "no", "y", "yes"]: newPuzzle = input("Another puzzle? Y/N: ") newPuzzle = newPuzzle.lower() if newPuzzle in ["n", "no"]: loopFlag = False print("") return if __name__ == "__main__": main()
animals = ['bear', 'python', 'peacock', 'kangaroo', 'whale', 'platypus'] python = animals[1] print python peacock = animals [2] print peacock bear = animals [0] print bear kangaroo = animals [3] print kangaroo whale = animals [4] print whale peacock = animals [2] print peacock platypus = animals[5] print platypus whale = animals [4] print whale
from turtle import * def yin(radius, color1, color2): width(3) color("black", color1) begin_fill() circle(radius/2., 180) end_fill() def main(): reset() yin(200, "black", "white") yin(200, "white", "black") ht() return "Done!" if __name__ == '__main__': main() mainloop()
""" 给定一个排序数组和一个目标值,在数组中找到目标值,并返回其索引。如果目标值不存在于数组中,返回它将会被按顺序插入的位置。 你可以假设数组中无重复元素。 示例 1: 输入: [1,3,5,6], 5 输出: 2 示例 2: 输入: [1,3,5,6], 2 输出: 1 示例 3: 输入: [1,3,5,6], 7 输出: 4 示例 4: 输入: [1,3,5,6], 0 输出: 0 """ def searchInsert(nums, target): if target in nums: for i in range(len(nums)): if target==nums[i]: return i else: for i in range(len(nums)): if target<=nums[i]: return i elif target>nums[-1]: return len(nums) nums=[1, 3, 5, 6] target = 2 print(searchInsert(nums, target))
import random angka = random.randint(1, 10) Max_Tebakan = 3 No_Tebakan = 0 Tebakan_true = False print('Program ini akan memilih angka secara acak dari 1 sampai 10') print('Anda harus menebak dalam {} percobaan'.format(Max_Tebakan)) petunjuk = 'Ini adalah tebakan ke {} anda. Masukkan angka lalu tekan enter \n' while not Tebakan_true and not No_Tebakan >= Max_Tebakan: No_Tebakan = No_Tebakan + 1 Tebakan = input(petunjuk.format(No_Tebakan)) Tebakan = int(Tebakan) if Tebakan == angka: Tebakan_true = True elif Tebakan > angka: print('Angka yang anda masukkan terlalu besar') else: print('Angka yang anda masukkan terlalu kecil') if Tebakan_true: print('Selamat anda berhasil menebak') else: print('GAME OVER!!!') print('Jawabannya adalah ',angka)
data = [['A1', 28], ['A2', 32], ['A3', 1], ['A4', 0], ['A5', 10], ['A6', 22], ['A7', 30], ['A8', 19], ['B1', 145], ['B2', 27], ['B3', 36], ['B4', 25], ['B5', 9], ['B6', 38], ['B7', 21], ['B8', 12], ['C1', 122], ['C2', 87], ['C3', 36], ['C4', 3], ['D1', 0], ['D2', 5], ['D3', 55], ['D4', 62], ['D5', 98], ['D6', 32]] # How many sites are there? field_list = [] for item in data: field_list.append(item[0]) print('The number of sites is:', len(field_list)) # How many birds were counted at the 7th site? print('The number of birds counted at the 7th site is:', data[6][1]) # How many birds were counted at the last site? print('The number of birds counted at last site is:', data[-1][1]) # What is the total number of birds counted across all sites? bird_list = [] for item in data: bird_list.append(item[1]) print('The total number of birds counted across all sites is:', sum(bird_list)) # What is the average number of birds seen on a site? average_bird = sum(bird_list) / len(bird_list) print('The average number of birds seen on a site is:', average_bird) # What is the total number of birds counted on sites with codes beginning with C? listed = [] for item in data: if item[0].startswith('C'): listed.append(item[1]) print('Total number of birds counted on sites with codes beginning with C is:', sum(listed))
# 3.1 my_name = "Tom" print(my_name.upper()) # 3.2 my_id = 123 print(my_id) # 3.3 # _123 = my_id my_id = your_id = 123 print(my_id) print(your_id) # 3.4 my_id_str = '123' print(my_id_str) # 3.5 # print(my_name + my_id) # 3.6 print(my_name + my_id_str) # 3.7 print(my_name*3) # 3.8 print('Hello World. This is my first python string.'.split('.')) # 3.9 message = "Tom's id is 123" print(message)
# lecture on list and set my_List = [1, 2, 3, 4, 5] print(my_List) my_nested_list = [1, 2, 3, my_List] print(my_nested_list) my_List[0] = 6 print(my_List) my_List.append(7) print(my_List) my_List.remove(7) print(my_List) my_List.sort() print(my_List) my_List.reverse() print(my_List) print(my_List + [8, 9]) my_List.extend(['a', 'b']) print(my_List) print('c' in my_List) print(len(my_List)) print(len('hello world')) # print(my_List[:]) # x, y = ['a', 'b'] # print(y)
#!/usr/bin/env python """ glob using regular expressions """ import os import re def irglob(d, r, with_matches=False): """ Return all files in a directory that match a regular expression. if with_matches is True, also return the re.match result: [(fn, re.match)...] kinda like glob.glob but with a regular expression """ if with_matches: for fn in os.listdir(d): m = re.search(r, fn) if m is not None: yield fn, m else: for fn in os.listdir(d): if re.search(r, fn) is not None: yield fn def rglob(d, r, with_matches=False): return list(irglob(d, r, with_matches))
""" 测试目标 1. r+和w+,a+的区别: 2。文件指针对数据读取的影响 """ # r+:没有文件的时候报错,文件指针在开头,所以能读出所有数据 # f = open('test.txt','r+') # # con = f.read() # print(con) # # f.close() # w+ 没有该文件会新建文件,文件指针也在开头,但是会用新内容覆盖原内容 # f = open('test.txt','w+') # # con = f.read() # print(con) # # f.close() # a+:如果没有文件会新建文件,文件指针在内容的末尾 f = open('test.txt','a+') con = f.read() print(con) f.close()
dict1 = {'name': 'Tom', 'age': 20, 'gender': '男'} # 字典序列[key] = 值 # id的值110 # 1、del # del(dict1) # print(dict1) # del dict1['name'] # print(dict1) # 2. clear() dict1.clear() print(dict1)
# reduce函数 reduce(fun,lst) # 需求:计算list1序列中各个数字的累加和 # 1.准备列表 import functools list1 = [1, 2, 3, 4, 5] # 2.定义函数 def func(a, b): return a + b # 3.调用函数 result = functools.reduce(func, list1) # 4.验收成果 print(result)
""" @Time : 2021/1/27 11:10 @Author : Steven Chen @File : 6多层继承.py @Software: PyCharm """ # 目标:体验多层继承 # 方法: # 1.师傅类 class Master(object): def __init__(self): self.kongfu = "[古法煎饼果子配方]" def make_cake(self): print(f'运用{self.kongfu}制作煎饼果子') # 2.创建学校类 class School(object): def __init__(self): self.kongfu = '[黑马煎饼果子配方]' def make_cake(self): print(f'运用{self.kongfu}制作煎饼果子') # 3.徒弟类继承school和Master两个父类的 优先继承第一个父类的属性和方法 class Prentice(School, Master): def __init__(self): self.kongfu = '[独创煎饼果子配方]' def make_cake(self): # 不调用则会使用上一次调用的属性值 self.__init__() print(f'运用{self.kongfu}制作煎饼果子') def make_master_cake(self): # 父亲类名,函数() # 再次调用初始化的原因,是要先初始化之后再能调用父亲的属性和方法 Master.__init__(self) Master.make_cake(self) def make_school_cake(self): School.__init__(self) School.make_cake(self) # 徒孙类 class Tusun(Prentice): pass # 4.用徒弟类创建对象,调用 实例属性和方法 xiaoqiu = Tusun() xiaoqiu.make_cake() xiaoqiu.make_master_cake() xiaoqiu.make_school_cake()
# 1.一个类创多个对象 class Washer(): def wash(self): print('洗衣服') def print_info(self): print(f'洗衣机的宽度{self.width}') print(f'洗衣机的高度{self.height}') haier1 = Washer() # 2.添加属性值 haier1.height = 800 haier1.width =600 # 3.获取对象的属性 haier1.print_info()
# 1.定交两个函数 2、函数1有返回值50作为函数2的输入值 def test1(): return 50 def test2(num): print(num) # 先得到函数1的返回值 result = test1() print(result) test2(result)
list1 = [10, 20, 30, 40, 50] s1 = {100,200,300,400,500} t1 = (100, 200, 300, 400) # 转成元组 # print(tuple(list1)) # print(tuple(s1)) #list() # print(list(s1)) # print(list(t1)) # set() print(list(list1)) print(list(t1))
# reduce函数 reduce(fun,lst) # 需求:筛选序列中的偶数 # 1.准备列表 list1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] # 2.定义函数 def func(x): return x % 2 == 0 # 3.调用函数 result = filter(func, list1) # 4.验收成果 print(list(result))
from google.cloud import translate import os import csv os.environ["GOOGLE_APPLICATION_CREDENTIALS"] = "ADD PATH TO YOUR GOOGLE CLOUD SERVICE ACCOUNT API KEY HERE" # https://cloud.google.com/translate/docs/basic/translating-text # Pull training questions from input_file_name and call the Google Translation API to return JSON response # Write translated text from JSON response to new CSV spreadsheet in the same order as the input file training questions # Will recieve an output of a csv file called translation_results.csv # Remember to set the source and target language, language code can be obtained from Google: https://developers.google.com/admin-sdk/directory/v1/languages client = translate.TranslationServiceClient() source_language = 'tr' target_language = 'en-CA' parent = client.location_path('tqtraining', 'global') input_file_format = 'text/plain' input_file_name = 'turkish_training_questions.csv' def translation_api(): with open(input_file_name) as training_questions: translation_file = csv.reader(training_questions) for tq in translation_file: print("Text being translated: {}".format(tq)) with open('translation_results.csv', 'a') as f: translation_output_file = csv.writer(f) translation_output = client.translate_text(mime_type = input_file_format, parent = parent, contents = tq, source_language_code= source_language, target_language_code = target_language) for translation in translation_output.translations: translated_text = translation.translated_text print(u"Translated text: {}".format(translated_text)) # print(type(translated_text)) translation_output_file.writerow(([translated_text])) translation_api()
import numpy as np from abc import ABCMeta from abc import abstractmethod class DataSampler(metaclass=ABCMeta): """ABC for data sampling""" @abstractmethod def sample(self, dataset): """Should return index samples of the dataset.""" class SequentialDataSampler(DataSampler): """Sequential sampler, implementation of ABC DataSampler""" def sample(self, dataset): """Samples a sequential order of data points.""" return np.array(range(dataset.size)) class RandomDataSampler(DataSampler): """Random sampler, implementation of ABC DataSampler""" def sample(self, dataset): """Samples a random permutation of the dataset points.""" return np.random.permutation(range(dataset.size)) class BatchDataSampler: """Batch sampler. Attributes: data_sampler (DataSampler): A data sampler batch_size (int, optional): The batch size, defaults to 1 drop_last (bool, optional): When True, keeps last index batch if smaller than batch size, defaults to False """ def __init__(self, dataset, data_sampler, batch_size=1, drop_last=True): self.dataset = dataset self.data_sampler = data_sampler self.batch_size = batch_size self.drop_last = drop_last def sample(self): """Samples batches of data point indices based on the `data_sampler`.""" sample = self.data_sampler.sample(self, dataset=self.dataset) if self.batch_size < len(sample): # Splitting the array to sub-arrays with batch-size size batch = np.array_split(sample, np.arange(self.batch_size, len(sample), self.batch_size)) # Dropping the last batch if we request for it return batch[:-1] if self.drop_last else batch else: return None
# -*- coding: utf-8 -*- """ Created on Mon Jul 12 19:12:26 2021 @author: User """ """ The 6x7 board: | | | | | | | | 1 ---------------------- 2 | | | | | | | | 3 ---------------------- 4 | | | | | | | | 5 ---------------------- 6 | | | | | | | | 7 ---------------------- 8 | | | | | | | | 9 ---------------------- 10 | | | | | | | | 11 ---------------------- 12 1 3 5 7 9 11 13 15 """ ##Still need to put it inside board def Board(rows,columns): print() for i in range(rows+1): if i%2 == 0: for j in range(0,columns+1): if j%2 == 1: if j != columns: print(" ",end="") else: print(" ") else: print("|",end="") else: print("----------------------") Board(11,15) currentField = [[" ", " "," "," "," "," "," "], [" ", " "," "," "," "," "," "], [" ", " "," "," "," "," "," "], [" ", " "," "," "," "," "," "], [" ", " "," "," "," "," "," "], [" ", " "," "," "," "," "," "]] Player = 1 CurrentRow = 5 print(currentField) while True: print("Player's turn: ", Player) ChosenColumn = int(input("Choose your column: ")) - 1 if Player == 1: if currentField[CurrentRow][ChosenColumn] == " ": currentField[CurrentRow][ChosenColumn] = "X" Player = 2 else: CurrentRow -= 1 currentField[CurrentRow][ChosenColumn] = "X" Player = 2 else: if currentField[CurrentRow][ChosenColumn] == " ": currentField[CurrentRow][ChosenColumn] = "O" Player = 1 else: CurrentRow -= 1 currentField[CurrentRow][ChosenColumn] = "O" Player = 1 print(currentField)
def em(): email=input("Ingresar Email: ") if "@" in email: Correo=email.split('@') usuario=Correo[0] desa=Correo[1] if "." in desa: txfin=desa.split('.') os=txfin[0] extencion=txfin[1] print ("El email " + email +" es valido") else: print ("El email " + email +" no es valido") else: print ("El email " + email +" no es valido") from time import time start =time() em() end=time()-start print(end)
#GAME from data import * from functions import * game_username = ask_username() game_scores = get_scores() if game_username not in game_scores.keys(): game_scores[game_username] = 0 continue_game = True while continue_game == True: print("Player {0}: {1} points\n".format(game_username,game_scores[game_username])) chances_left = chances letters_found = [] word_to_find = choose_word() word_found = get_hidden_word(word_to_find,letters_found) while chances_left > 0 and word_found != word_to_find: print("Word to find: {0} ({1} chances)".format(word_found,chances_left)) tried_letter = ask_letter().lower() if tried_letter in word_to_find: letters_found.append(tried_letter) word_found = get_hidden_word(word_to_find,letters_found) print("Good guess!\n") else: print("Try again!\n") chances_left-=1 if chances_left == 0 and word_found != word_to_find: print("You lost! The word was: ",word_to_find) elif word_found == word_to_find: print("You won!") game_scores[game_username] += chances_left print("You won {0} points. Your new score is: {1}".format(chances_left,game_scores[game_username])) play_choice = input("Would you like to play again? (yes/no)") if play_choice == "yes": print("Let's guess a new word!") elif play_choice == "no": save_scores(game_scores) print("Hope you had fun. See you very soon!") continue_game = False
#Create a class to build a new dictionary for answer number and play input number #import rand as r #secret=r.rnumlistwithoutreplacement(4,0,7) class dictionary(dict): # __init__ function def __init__(self): self = dict() # Function to add key:value def add(self, key, value): self[key] = value # Main Function #sdict = dictionary() #i=0 #j=len(secret)-1 #print(j) #for number in secret: # sdict.key=i # i=i+1 # sdict.value=number # j=j-1 # sdict.add(sdict.key, sdict.value) # #print(sdict)
import mainloop import color def defaultsetting(): digit=4 lower=0 upper=7 attempt=10 return (digit, lower, upper, attempt) player=input("----------Welcome to MasterMind Game-----------\nWhat's your name?") print("Hi,", player, "! Below is the Main Menu:") instru='''-------------------Main Menu------------------- In this Mastermind game, you are playing against the computer. You must guess the right number combinations within 10 attempts to win the game. Game default setting: 10 attempts to guess a four number combinations from 0~7. You can always change the difficulty of the game by yourself! ------------------------------------------------ Here are the options you can do during the game: 1.Start a new game ---Enter: "s" 2.Change the game difficulty ---Enter:"c" 3.Reset the game to default setting ---Enter:"r" 4.View your game score ---Enter: "v" 5.Exit the game ---Enter: "e" 6.See the menu ---Enter: "m" ------------------------------------------------ ''' color.printbold(instru) digit,lower,upper,attempt=defaultsetting() score_list=[] while True: option=input("What would you like to do? Enter:") if option=='s': #start a new game #start guessloop here score=mainloop.guessloop(digit,lower,upper,attempt) if score>0: color.printgreen("Bingo! You got it!") elif score==0: color.printred("You have reached the guess limits.") score_list.append(score) elif option=="c": #change difficulty digit=int(input("Enter the number digits: ")) lower=int(input("Enter the number the random number generator starts: ")) upper=int(input("Enter the number the random number generator ends: ")) attempt=int(input("Enter guess times: ")) elif option=='r': #reset game digit,lower,upper,attempt=defaultsetting() elif option=='v': #show scoreboard, keep the past scores s=player + ", your scores are:" + str(score_list) color.printpurple(s) elif option=='e': #exit the game s="See you next time," + player + "!" color.printpurple(s) break elif option=='m': color.printbold(instru) else: color.printred("Invalid input. Please enter again!")
#coding: utf-8 from datetime import datetime from datetime import date from datetime import timedelta class MyDateClass(object): def __init__(self): self.TDY = date.today() #self.TDY = datetime.today() self.YYYYMMDD = None self.MM = None self.YYYYMM = None self.ymd = None def getToday(self): return self.TDY def setDate(self,ustr): self.ymd = ustr.split('/') self.TDY = date(int(self.ymd[0]),int(self.ymd[1]),int(self.ymd[2])) return self.TDY def strYYYYMMDD(self): self.YYYYMMDD = self.TDY.strftime('%Y%m%d') return self.YYYYMMDD def strMM(self): self.MM = self.TDY.strftime('%m') return self.MM def strYYYYMM(self): self.YYYYMM = self.TDY.strftime('%Y-%m') return self.YYYYMM def timeDeltaDays(self,idays): try: dt = timedelta(days=idays) t = self.TDY - dt return t except: print " *** Unexpected error (MyDataClass - timeDeltaDays) *** :", sys.exc_info()[0] def dummy(): pass def main(): mObj = MyDateClass() print mObj.setStrDate('2014/01/05') if __name__ == '__main__': main()
n = int(input()) mydict = {} all_parents_dict = {} for i in range(n): str = input().split(':') print(str) if len(str) == 1: mydict[str[0]] = [] else: mydict[str[0].strip()] = str[1].strip().split() print(mydict) for key, value in mydict.items(): all_parents_dict[key] = [] if len(mydict[key]) == 0: continue else: for i in mydict[key]: all_parents_dict[key].append(i) if i in mydict.keys() and mydict[i] != [] and len(mydict[i]) == 1: all_parents_dict[key].append(*mydict[i]) elif i not in mydict.keys(): continue else: all_parents_dict[key].extend(mydict[i]) print('ALL ->', all_parents_dict) m = int(input()) for i in range(m): str = input().split() print(str) if str[1] not in all_parents_dict.keys(): print('No') elif str[0] in all_parents_dict[str[1]]: print(str[1], 'value--->', all_parents_dict[str[1]]) print('Yes') # elif mydict[str[0]] == []: # print(str[1], 'value--->', mydict[str[1]]) # print('Yes') else: print(str[1], 'value--->', all_parents_dict[str[1]]) print('No') """2 A : C B B : D E 1 E A 4 A B : A C : A D : B C 4 A B B D C D D A"""
def sort(a, p, r): if p < r: q = (p + r) // 2 sort(a, p, q) sort(a, q + 1, r) merge(a, p, q, r) def merge(a, p, q, r): left_copy = a[p:q + 1] right_copy = a[q + 1:r + 1] left_copy_index = 0 right_copy_index = 0 sorted_index = p while left_copy_index < len(left_copy) and right_copy_index < len(right_copy): if left_copy[left_copy_index] <= right_copy[right_copy_index]: a[sorted_index] = left_copy[left_copy_index] left_copy_index += 1 else: a[sorted_index] = right_copy[right_copy_index] right_copy_index += 1 sorted_index += 1 while left_copy_index < len(left_copy): a[sorted_index] = left_copy[left_copy_index] left_copy_index += 1 sorted_index +=1 while right_copy_index < len(right_copy): a[sorted_index] = right_copy[right_copy_index] right_copy_index += 1 sorted_index += 1 a = [5, 2, 4, 6, 1, 3, 2, 6] sort(a, 1, len(a)) print(a)
"""If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23. Find the sum of all the multiples of 3 or 5 below 1000.""" def multipliers(muls): arr=[]; for mul in range(1,muls+1): if((mul%3==0) or (mul%5==0)): arr.append(mul) print(sum(arr)) multipliers(999)
''' POWER DIGIT SUM 2**15 = 32768 and the sum of its digits is 3 + 2 + 7 + 6 + 8 = 26. What is the sum of the digits of the number 2**1000? ''' def pow_dig_sum(base,exp): add=0 a=(base**exp) while (a!=0): add=add+int(a%10) a=(a//10) return(add) if __name__=="__main__": print(pow_dig_sum(2,1000))
#!/usr/bin/python ''' quick inversion for specific element with tridiagonalized matrix. In the following description, we take p -> the block dimension, N -> the matrix dimension and n = N/p. *references*: * http://dx.doi.org/10.1137/0613045 * http://dx.doi.org/10.1016/j.amc.2005.11.098 ''' from numpy import * from scipy.sparse import bmat as sbmat import pdb __all__=['InvSystem','STInvSystem','BTInvSystem'] class InvSystem(object): ''' The abstract interface of inversion generator for tridiagonal matrix. ''' def __getitem__(self,indices): ''' Get specific item of the inverse matrix. indices: The row/column index. ''' raise Exception('Not Implemented') def toarray(self,*args,**kwargs): ''' Get the inverse of matrix. ''' raise Exception('Not Implemented') class STInvSystem(InvSystem): ''' Matrix Inversion Fast Generator for Scalar Tridiagonal Matrix. ul,vl: The u,v vectors defining this inversion. ''' def __init__(self,ul,vl): self.ul=ul self.vl=vl @property def n(self): '''The number of blocks.''' return len(self.ul) def __getitem__(self,indices): ''' Get specific item of the inverse matrix. indices: The row/column index. *return*: A number. ''' i,j=indices if i<=j: return self.ul[i]*vl[j] else: return self.ul[j]*vl[i] def toarray(self): ''' Get the inverse of matrix. *return*: A (N x N) array. ''' m=self.ul[:,newaxis].dot(self.vl[newaxis,:]) m=triu(m)+triu(m,1).T.conj() return m class BTInvSystem(InvSystem): ''' Fast Generator for the inversion of A Tridiagonal Matrix. seq_lt/seq_gt/seq_eq: sequence for i < j/i > j/i==j sequences are aranged in the order ''' def __init__(self,seq_lt,seq_gt,seq_eq): self.ll_lt,self.hl_lt,self.ul_lt,self.invhl_lt=seq_lt self.ll_gt,self.hl_gt,self.ul_gt,self.invhl_gt=seq_gt self.ll_eq,self.hl_eq,self.ul_eq,self.invhl_eq=seq_eq @property def is_scalar(self): '''True if functionning as scalar.''' return ndim(self.hl_lt)==1 def _get_L(self,i,j): '''Get L(i,j)''' if i<j: return self.ll_lt[i] elif i>j: return self.ll_gt[i] else: return self.ll_eq[i] def _get_H(self,i,j): '''Get H(i,j)''' if i<j: return self.hl_lt[i] elif i>j: return self.hl_gt[i] else: return self.hl_eq[i] def _get_invH(self,i,j): '''Get H(i,j)^{-1}''' if i<j: return self.invhl_lt[i] elif i>j: return self.invhl_gt[i] else: return self.invhl_eq[i] def _get_U(self,i,j): '''Get U(i,j)''' if i<j: return self.ul_lt[i] elif i>j: return self.ul_gt[i] else: return self.ul_eq[i] @property def n(self): '''The number of blocks.''' return len(self.hl_eq) @property def p(self): '''The block size''' if self.is_scalar: return 1 else: return shape(self.hl_eq)[-1] def get_twist_LU(self,j): ''' Get the twist LU decomposition of the original matrix. For the definnition of twist LU decomposition, check the references of this module. j: The twisting position. *return*: (L,U), each of which is a (N x N) sparse matrix. ''' n=self.n p=self.p L=ndarray((n,n),dtype='O') U=ndarray((n,n),dtype='O') I=identity(p) for i in xrange(n): L[i,i]=self._get_H(i,j) U[i,i]=I if i<j: L[i+1,i]=self._get_L(i,j) U[i,i+1]=self._get_U(i,j) elif i>j: L[i-1,i]=self._get_L(i-1,j-1) U[i,i-1]=self._get_U(i-1,j-1) L=sbmat(L) U=sbmat(U) return L,U def __getitem__(self,indices): ''' Get specific item of the inverse matrix. indices: The row/column index. *return*: Matrix element, A (p x p) array for block version or a number for scalar version. ''' i,j=indices if i==slice(None): return self._get_col(j) elif i==j: return self._get_invH(i,j) elif i<j: return dot(-self._get_U(i,j),self.__getitem__(i+1,j)) else: return dot(-self._get_U(i-1,j),self.__getitem__(i-1,j)) def _get_col(self,j): ''' Get the specific column of the inverse matrix. j: The column index. *return*: The specific column of the inversion of tridiagonal matrix, An array of shape (n*p x p) for block version or (n) for scalar version. ''' cjj=self.__getitem__((j,j)) cl=[cjj] ci=cjj n=len(self.hl_eq) for i in xrange(j+1,n): ci=dot(-self._get_U(i-1,j),ci) cl.append(ci) ci=cjj for i in xrange(j-1,-1,-1): ci=dot(-self._get_U(i,j),ci) cl.insert(0,ci) return cl def toarray(self): ''' Get the inverse of matrix. *return*: A (N x N) array. ''' n,p=self.n,self.p m=[] for j in xrange(n): m.append(self[:,j]) if self.is_scalar: m=transpose(m) else: m=transpose(m,axes=(1,2,0,3)).reshape([n*p,n*p]) return m
''' Linear algebra for block and tridiagonal matrices. In the following description, we take p -> the block dimension, N -> the matrix dimension and n = N/p. ''' from numpy.linalg import inv from numpy import * from scipy.sparse import coo_matrix,bsr_matrix,csr_matrix,block_diag from scipy.sparse import bmat as sbmat from invsys import STInvSystem,BTInvSystem from lusys import TLUSystem from futils.pywraper import get_tlu_seq,ind2ptr,get_dl,get_uv __all__=['trilu','triul','trildu','triudl','get_invh_system','get_inv_system','tinv'] def trilu(tridmat): ''' Get the LU decomposition for tridiagonal matrix, A=LU The complexity of this procedure is n*p^3. trdmat: A tridiagonal matrix, i.g. an instance of TridMatrix. *return*: A <TLUSystem> instance with order 'LU'. ''' al=tridmat.lower bl=tridmat.diagonal cl=tridmat.upper is_scalar=tridmat.is_scalar ll,ul,hl,invhl=get_tlu_seq(al=al,bl=bl,cl=cl,which='<') return TLUSystem(ll=ll,ul=ul,hl=hl,invhl=invhl,order='LU') def triul(tridmat): ''' Get the UL decomposition for tridiagonal matrix, A=UL The complexity of this procedure is n*p^3. *return*: A <TLUSystem> instance with order 'UL'. ''' al=tridmat.lower bl=tridmat.diagonal cl=tridmat.upper ll,ul,hl,invhl=get_tlu_seq(al=al,bl=bl,cl=cl,which='>') return TLUSystem(ll=ul,ul=ll,hl=hl,invhl=invhl,order='UL') def trildu(tridmat): ''' Get the LDU decomposition, A=LD^{-1}L^\dag The complexity of this procedure is n*p^3. trdmat: A tridiagonal matrix, i.g. an instance of TridMatrix. *return*: A <TLUSystem> instance with order 'LDU'. ''' dl,invdl=get_dl(al=tridmat.lower,bl=tridmat.diagonal,cl=tridmat.upper,order='LDU') res=TLUSystem(hl=dl,invhl=invdl,ll=tridmat.lower,ul=tridmat.upper,order='LDU') return res def triudl(tridmat): ''' Get the UDL decomposition, A=UD^{-1}U^\dag The complexity of this procedure is n*p^3. tridmat: The tridiagonal matrix. *return*: A <TLUSystem> instance with order 'UDL'. ''' dl,invdl=get_dl(al=tridmat.lower,bl=tridmat.diagonal,cl=tridmat.upper,order='UDL') return TLUSystem(hl=dl,invhl=invdl,ll=tridmat.lower,ul=tridmat.upper,order='UDL') def get_invh_system(tridmat): ''' Get the inversion generator for `hermitian` tridiagonal matrix. The Fortran version and python version are provided for block tridiagonal matrix. The complexity of this procedure is N. However, if you're going to generate the whole inversion elements through STInvSystem instance, the complexity is N^2. Reference -> http://dx.doi.org/10.1137/0613045 trdmat: A tridiagonal matrix, i.g. an instance of TridMatrix. *return*: A STInvSystem instance. ''' if tridmat.is_scalar: du,invdu=get_dl(al=tridmat.lower,bl=tridmat.diagonal,cl=tridmat.upper,order='UDL') dl,invdl=get_dl(al=tridmat.lower,bl=tridmat.diagonal,cl=tridmat.upper,order='LDU') u,v=get_uv(invdu=invdu,invdl=invdl,al=tridmat.lower,cl=tridmat.upper) res=STInvSystem(u,v) return res else: raise Exception('Not Implemented For block tridiagonal matrices!') def get_inv_system(tridmat): ''' Get the inversion generator for tridiagonal matrix. The Fortran version and python version are provided for block tridiagonal matrix. The complexity of this procedure is n*p^3. However, if you're going to generate the whole inversion elements through STInvSystem instance, the complexity is n^2*p^3. Reference -> http://dx.doi.org/10.1016/j.amc.2005.11.098 trdmat: A tridiagonal matrix, i.g. an instance of TridMatrix. *return*: a <BTInvSystem> instance. ''' ll1,ll2,ll3,ul1,ul2,ul3,hl1,hl2,hl3,invhl1,invhl2,invhl3=get_tlu_seq(al=tridmat.lower,bl=tridmat.diagonal,cl=tridmat.upper) return BTInvSystem((ll1,hl1,ul1,invhl1),(ll2,hl2,ul2,invhl2),(ll3,hl3,ul3,invhl3)) def tinv(tridmat): ''' Get the inversion of a tridiagonal matrix. trdmat: A tridiagonal matrix, i.g. an instance of TridMatrix. *return*: A two dimensional array, the inversion matrix of tridmat. ''' invs=get_inv_system(tridmat) return invs.toarray()
from reading import * from database import * # Below, write: # *The cartesian_product function # *All other functions and helper functions # *Main code that obtains queries from the keyboard, # processes them, and uses the below function to output csv results def split_query(user_input_query): '''(str) -> dict return the divided query into tokens >>> user_input_query = "select i.title,i.rating from imdb,oscar-film \ where f.year>2010,f.title=f.year" >>> split_query(user_input_query) {'select': ['i.title', 'i.rating'], 'where': ['f.year>2010', \ 'f.title=f.year'], 'from': ['imdb', 'oscar-film']} ''' # create an empty list and a dict query = [] input_dict = {} # split the input query by white space user_input_query = user_input_query.split(' ') # split the 'where' word if it exists in the input query by using coma if 'where' in user_input_query: # split where input_dict['where'] = user_input_query[5].split(',') # split select input_dict['select'] = user_input_query[1].split(',') # split from input_dict['from'] = user_input_query[3].split(',') # if not; else: # split from query_dict['from'] = query[3].split(',') # split where query_dict['select'] = query[1].split(',') # return the dict return input_dict def num_of_rows(table): '''(Table) -> int returns the number of the rows in a table. >>> t1 = Table() >>> t1.set_dict({'one':[1,2,3],'two':[4,5,6]}) >>> num_of_rows(t1) 3 ''' # parm1 = list(table._table_dict.keys())[0] rows = len(table._table_dict[parm1]) return rows def cartesian_product(table1, table2): '''(Table, Table) -> Table return a new table where each row in the first table is paired with every row in the second table. >>> table1 = {'A': ['B','C'], 'D': ['E', 'F']} >>> table2 = {'G': ['H', 'I'], 'J': ['K', 'L']} >>> cart_pro = cartesian_product(table1, table2) >>> cart_pro == {{'J': ['K', 'L', 'K', 'L'], 'G': ['H', 'I', 'H', 'I'], \ 'A': ['B', 'B', 'C', 'C'], 'D': ['E', 'E', 'F', 'F']}} True >>>table1 = {'A': [], 'B': []} >>>table2 = {'D': [], 'D': []} >>>cart_pro = cartesian_product(table1, table2) >>> cart_pro == {'D': [], 'A': [], 'B': []} True ''' # create a dictionary for the new table table = dict() # loop through the table1 for element in table1: table[element] = [] # find its length length_table1 = len(table1[element]) # loop through the other table for element in table2: table[element] = [] # find its length length_table2 = len(table2[element]) # go through the tables to pair it with the other table for element in range(length_table1): for i in range(length_table2): # pair the each row with the other one for elements in table1: table[elements].append(table1[elements][element]) for elements in table2: table[elements].append(table2[elements][i]) # return the dictionary that created initialy return table def after_from(tokens, pos_from): '''(list of str) -> list of str given the query return the tables after 'from' ''' # create an empty list res = [] # split the columns if there are more than one if (',' in tokens[pos_from]): # split it in list res = tokens[pos_from].split(',') # if not; else: # add it into the list directly res.append(tokens[pos_from]) # return result return result def from_token(Database, query): '''(Database,dict) -> Table Return a table that is in the from list and combine the tables with cartesian_product. ''' # find 'from' in the list query_from = query['from'] # use database class to get dictionary representation db = Database.get_dict() table1 = db[query_from[0]] # loop through the tables to get cartesian product, tables to combine # tables for element in range(1, len(query_from)): table2 = db[query_from[element]] # get the cartesian-product table1 = cartesian_product(table1, table2) # return result return table1 def token_select(cartesian_table, token_dict): '''(Table, dict) -> Table create a new table by finding the values of 'select' and find the index value to match them within the table. ''' list_token = token_dict["select"] # use cartesian table to get the dict cartesian_table = cartesian_table.get_dict() # create a new dict select_dict = {} # set a variable as a new table table = Table() if list_token == ["*"]: list_token = list(cartesian_table.keys()) for element in list_token: select_dict[element] = cartesian_table[element] # set dictionary to the table table.set_dict(select_dict) # return table return table def del_cols(table, column): '''(Table, int) -> Table Return a table with deleted colums which are not selected in the given\ query ''' if column[0] == '*': # set it as a list column = list(table._table_dict.keys()) # loop through the list for element in list(table._table_dict.keys()): # if the column is not in the column list if element not in column: # delete the columns table.delete_colm(element) # return result return table def run_query(database, user_input_query): '''(Database, str) -> Table Given user_input-query on the database, return the result table by using\ cartesian product ''' # get the divided tokens user_dict = split_query(query) # get the cartesian_table by using from_token function cartesian_table = from_token(Database, user_dict) # combine the functions result = token_select(cartesian_table, user_dict) # return result return result if(__name__ == "__main__"): ''' asks for queries and prints the table example form: select *column(s)* from *Tables* where *column>/=column*/*column>/=value* ''' # read the database database = read_database() # ask the input query = input("Enter a SQuEaL query, or a blank line to exit: ") # keep ask the input if the answer is not blank while (query != ''): # print the tables Table.print_csv(run_query(database, query)) # ask for input query = input("Enter a SQuEaL query, or a blank line to exit: ")
#crear una calculadora #numero uno input( "ingresa el numero 1: ") #numero dos numero2 = input("ingresa numero 2: ") #operaciones #resultados
def select(mat, point0, point1): xmax = max(point0[0], point1[0]) xmin = min(point0[0], point1[0]) ymax = max(point0[1], point1[1]) ymin = min(point0[1], point1[1]) print(xmin, ":", xmax) print(ymin, ":", ymax) return mat[ymin:ymax, xmin:xmax]
import sys if sys.argv[1] != "": print "hello " + sys.argv[1] a ={} a["the"] = 1 a["boy"] = 0 a["is"] = 2 a["the"] = 5 print a.keys() print a.values()
import pandas as pd import nltk from nltk.tokenize import RegexpTokenizer import io import dataLoadModule import constants def get_countries(): countries = set() with open(constants.country_list, 'r') as f: for country in f.readlines(): countries.add(country.strip()) return countries def get_political_figures(): political_figures = set() with open(constants.political_figures, 'r', encoding="utf-8") as f: for political_figure in f.readlines(): political_figures.add(political_figure.strip()) return political_figures ''' This method is needed for python 2.7 ''' def get_political_figures_legacy(): political_figures = set() with io.open(constants.political_figures, 'r', encoding="utf-8") as f: for political_figure in f.readlines(): political_figures.add(political_figure.strip()) return political_figures def filter_significant_email(data): """ We'll define any significant email any emails containg 500 characters or more. :param data: The Pandas dataframe containing all of Hillary Clinton's data :return: a filtered dataframe """ frame_to_choose = [] for ind, row in data.iterrows(): if len(row["RawText"]) > 500: frame_to_choose.append(True) else: frame_to_choose.append(False) return data[frame_to_choose] def count_mentioned_countries(data): """ Return the frequency of countries mentioned in Clinton's emails (is a map from country to integer how many emails the country is mentioned) :param data: email data as a Pandas data frame :return: Countries mentioned in the email """ countries_mentioned = {} countries = get_countries() for ind, row in data.iterrows(): subject_words = row["MetadataSubject"].lower() message_words = row["RawText"].lower() for country in countries: if country in (subject_words + message_words): if country in countries_mentioned: countries_mentioned[country] += 1 else: countries_mentioned[country] = 1 return pd.DataFrame.from_dict(countries_mentioned, orient="index") def count_mentioned_pol_figures(data): """ Return the frequency of political figures mentioned in Clinton's emails (is a map from country to integer how many emails the country is mentioned) :param data: email data as a Pandas data frame :return: pol figures mentioned in the email """ figures_mentioned = {} figures = get_political_figures() for ind, row in data.iterrows(): subject_words = row["MetadataSubject"].lower() message_words = row["RawText"].lower() for figure in figures: if figure + " " in (subject_words + message_words): if figure in figures_mentioned: figures_mentioned[figure] += 1 else: figures_mentioned[figure] = 0 return pd.DataFrame(figures_mentioned) ''' This method is neeeded for python 2.7 ''' def find_mentioned_pol_figures_legacy(data): """ Return the frequency of political figures mentioned in Clinton's emails (is a map from country to integer how many emails the country is mentioned) :param data: email data as a Pandas data frame :return: pol figures mentioned in the email """ figures_mentioned = {} figures = get_political_figures_legacy() for ind, row in data.iterrows(): subject_words = row["MetadataSubject"].lower() message_words = row["RawText"].lower() for figure in figures: if figure + " " in (subject_words + message_words): if figure in figures_mentioned: figures_mentioned[figure][0].append(ind) else: figures_mentioned[figure] = [[ind]] return pd.DataFrame(figures_mentioned) def basic_statistics_of_email(data): """ Print basic statistics of the email data :param data: Pandas dataframe for email data :return: None """ word_counts = [] character_count = 0 for ind, row in data.iterrows(): tokenizer = RegexpTokenizer(r'\w+') real_words = tokenizer.tokenize(row["RawText"].lower()) character_count += sum(map(len, real_words)) word_counts.append(len(real_words)) return character_count, pd.Series(word_counts) data = dataLoadModule.getFullEmailData() c_count, w_count = basic_statistics_of_email(data)
"""This class is used to represent how classy someone or something is. "Classy" is interchangable with "fancy". If you add fancy-looking items, you will increase your "classiness". A function is created in "Classy" that takes a string as input and adds it to the "items" list. Another function calculates the "classiness" value based on the items. The following items have classiness points associated with them: "tophat" = 2 "bowtie" = 4 "monocle" = 5 Everything else has 0 points. The test cases below demonstrate the above when run!""" class Classy(object): def __init__(self): self.items = [] def addItem(self,item): self.items.append(item) def getClassiness(self): self.Classiness = 0 for self.index in range(len(self.items)): if (self.items[self.index] == "tophat"): self.Classiness += 2 elif (self.items[self.index] == "bowtie"): self.Classiness += 4 elif (self.items[self.index] == "monocle"): self.Classiness += 5 return self.Classiness # Test cases me = Classy() # Should be 0 print me.getClassiness() me.addItem("tophat") # Should be 2 print me.getClassiness() me.addItem("bowtie") me.addItem("jacket") me.addItem("monocle") # Should be 11 print me.getClassiness() me.addItem("bowtie") # Should be 15 print me.getClassiness()
# O(n^2) time, O(1) space def longestPalindromicSubstring(string): if len(string) < 2: return string current_longest = [0, 0] for i in range(len(string)): odd = getPalindrome(string, i-1, i+1) even = getPalindrome(string, i-1, i) longer = max(odd, even, key=lambda x: x[1] - x[0]) current_longest = max(current_longest, longer, key=lambda x: x[1] - x[0]) return string[current_longest[0]: current_longest[1] + 1] def getPalindrome(string, left, right): while left >= 0 and right < len(string): if string[left] != string[right]: break left -= 1 right += 1 return [left + 1, right - 1]
class MyQueue: def __init__(self): self.inputStack = [] self.outputStack = [] def push(self, x: int) -> None: self.inputStack.append(x) def pop(self) -> int: if len(self.outputStack): return self.outputStack.pop() while len(self.inputStack): self.outputStack.append(self.inputStack.pop()) return self.outputStack.pop() def peek(self) -> int: if len(self.outputStack): return self.outputStack[-1] else: return self.inputStack[0] def empty(self) -> bool: if not len(self.inputStack) and not len(self.outputStack): return True else: return False
# O(n) time and space def balancedBrackets(string): stack = [] openBrackets = '([{' closingBrackets = ')}]' pairs = {')': '(', '}': '{', ']': '['} for char in string: if char in openBrackets: stack.append(char) elif char in closingBrackets: if not len(stack) or stack[-1] != pairs[char]: return False else: stack.pop() return not len(stack)
# O(n) time, O(h) space def is_symmetric(root): if not root: return True return check_symmetry(root.left, root.right) def check_symmetry(left_node, right_node): if not left_node and not right_node: return True elif (not left and right) or (left and not right): return False else: if left_node.val != right_node.val: return False else: outer = check_symmetry(left_node.left, right_node.right) inner = check_symmetry(left_node.right, right_node.left) return outer and inner
class MinMaxStack: def __init__(self): self.minValues = [float("inf")] self.maxValues = [float("-inf")] self.stack = [] def peek(self): if len(self.stack): return self.stack[-1] def pop(self): if len(self.stack): removed = self.stack.pop() if removed == self.minValues[-1]: self.minValues.pop() if removed == self.maxValues[-1]: self.maxValues.pop() return removed def push(self, number): minValue = self.minValues[-1] maxValue = self.maxValues[-1] if number >= maxValue: self.maxValues.append(number) if number <= minValue: self.minValues.append(number) self.stack.append(number) def getMin(self): if len(self.minValues) > 1: return self.minValues[-1] def getMax(self): if len(self.maxValues) > 1: return self.maxValues[-1]
# O(c) time | O(1) space: c= total length of all the words in the input list added together # build graph, char1->char2 # track in_Degree, unique chars # remove edges, no_dep_letters # check len(order) and len(chars) from collections import defaultdict class Solution: def alienOrder(self, words: List[str]) -> str: graph = defaultdict(list) in_degree = defaultdict(int) chars = {char for word in words for char in word} for word1, word2 in zip(words, words[1:]): for char1, char2 in zip(word1, word2): if char1 != char2: graph[char1].append(char2) in_degree[char2] += 1 break else: if len(word1) > len(word2): return "" no_prev_letter = [char for char in chars if in_degree[char] == 0] ordered_letters = [] while no_prev_letter: letter = no_prev_letter.pop() ordered_letters.append(letter) for c in graph[letter]: in_degree[c] -= 1 if in_degree[c] == 0: no_prev_letter.append(c) return "".join(ordered_letters) if len(ordered_letters) == len(chars) else ""
# O(n) time | O(1) space def bracket_match(text): closing_brackets = 0 opening_brackets = 0 for brackets in text: if brackets == '(': closing_brackets += 1 else: closing_brackets -= 1 if closing_brackets == -1: opening_brackets += 1 closing_brackets = 0 return opening_brackets + closing_brackets
class Node(object): def __init__(self,val): self.val = val self.next = None class SinglyLinkedList(object): def __init__(self): self.head = None self.tail = None self.size = 0 def length(self): return self.size # O(1) def insertAtStart(self,val): newNode = Node(val) if not self.head: self.head = self.tail = newNode else: newNode.next = self.head self.head = newNode self.size += 1 return self # O(1) def insertAtEnd(self,val): newNode = Node(val) if not self.tail: self.head = self.tail = newNode else: self.tail.next = newNode self.tail = newNode self.size += 1 return self # O(n) def remove(self): if not self.tail: return current = self.head previous = None while current.next: previous = current current = current.next if previous: previous.next = current.next self.tail = previous else: self.head = current.next current.next = None self.size -= 1 return current.val def traverse(self): if not self.tail: return [] nodes = [] current = self.head while current: nodes.append(current.val) current = current.next return nodes linkList = SinglyLinkedList() # linkList.insertAtStart(1) # linkList.insertAtStart(2) # linkList.insertAtStart(3) # linkList.insertAtStart(4) # linkList.insertAtStart(5) linkList.remove() # linkList.insertAtEnd(1) # linkList.insertAtEnd(2) # linkList.insertAtEnd(3) # linkList.insertAtEnd(4) # linkList.insertAtEnd(5) print(linkList.length()) print(linkList.traverse())
def merge(left, right): result = [] i, j = 0, 0 while (len(result) < len(left) + len(right)): if left[i].split(' ')[1] < right[j].split(' ')[1]: #sort by age first result.append(left[i]) i+= 1 elif left[i].split(' ')[1] == right[j].split(' ')[1]: #if the age are same, sort by name if left[i] < right[j]: result.append(left[i]) i+= 1 else: result.append(right[j]) j+= 1 else: result.append(right[j]) j+= 1 if i == len(left) or j == len(right): result.extend(left[i:] or right[j:]) break return result def mergesort(list): if len(list) < 2: return list middle = int(len(list)/2) left = mergesort(list[:middle]) right = mergesort(list[middle:]) return merge(left, right) # READ FILE file_object = open("PATH_TO_FILE/name_age.txt", "r") input_file = file_object.read() input_file = input_file.split('\n') input_file = list(map(str, input_file)) sorted_file = mergesort(input_file) # WRITE OUTPUT FILE file_output = open("PATH_TO_FILE/sorted_name_age.txt", "w") for i in range(0,len(sorted_file)): file_output.write(str(sorted_file[i])) file_output.write("\n") file_output.close()
import random EMPTY_MARK = 'empty' MOVES = { 'w': (lambda e: e // 4 == 0, -4), 's': (lambda e: e // 4 == 3, 4), 'd': (lambda e: e % 4 == 3, 1), 'a': (lambda e: e % 4 == 0, -1), } def shuffle_field(): numbers = list(range(16)) random.shuffle(numbers) empty_index = random.randint(0, 16) numbers[empty_index] = EMPTY_MARK return numbers def print_field(field): for i in range(0, 16, 4): print(field[i:i+4]) print('\n') def is_game_finished(field): try: for i in range(len(field) - 2): if int(field[i]) > int((field[i + 1])): return False return field[-1] == EMPTY_MARK except ValueError: return False def perform_move(field, key): key = key.lower() empty_spot = field.index(EMPTY_MARK) validation, vector = MOVES[key] if validation(empty_spot): raise IndexError("can't move %s" % key) to_change = empty_spot + vector field[empty_spot], field[to_change] = field[to_change], field[empty_spot] return field def handle_user_input(): try: input_f = raw_input except NameError: input_f = input allowed_moves = list(MOVES.keys()) message = 'Move %s: ' % ', '.join(allowed_moves) move = None while move not in allowed_moves: move = input_f(message).lower() return move def main(): field = [1, 3, 14, 8, 4, 5, 6, 13, 8, 11, 10, 'empty', 2, 12, 7, 9] steps = 0 while not is_game_finished(field): try: print_field(field) move = handle_user_input() field = perform_move(field, move) steps += 1 except IndexError as ex: print(ex) except KeyboardInterrupt: print('Shutting down.') quit() print('You have completed the game in {} steps.'.format(steps)) if __name__ == '__main__': main()
import datetime #This is the my mystery function that will give a score to each string def mystery_score(mystr): # z is the highest character we want - totalScore = ord("z") charsum = 1 for ch in mystr: charsum += ord(ch) return charsum/totalScore if __name__ == "__main__": string= raw_input("What is the string you want to score? ") print "Your score for '" + string + "' is "+ str(mystery_score(string))
# Danhel Alejandro Mercado Velasco # mision 10 equipos de football # liga BBVA import matplotlib.pyplot as plot # Mostrar el nombre de los equipos ordenadamente def listarEquiposOrdenados(nombreArchivo): entrada = open(nombreArchivo, "r") entrada.readline() entrada.readline() listaEquipos = [] for linea in entrada: datos = linea.split("&") listaEquipos.append(datos[0].upper()) listaEquipos.sort() entrada.close() return listaEquipos # Mostrar lista de equipos que han perdido 3 partidos o menos def listarEquiposPerdedores(nombreArchivo): entrada = open(nombreArchivo, "r", encoding="UTF-8") entrada.readline() entrada.readline() lista = [] for datos in entrada: fila = datos.split("&") Perdidas = int(fila[4]) if Perdidas <= 3: lista.append(fila[0].upper()) entrada.close() return lista # Mostrar a los equipos con sus respectivos puntos def listarEquiposPuntos(nombreArchivo): entrada = open(nombreArchivo, "r", encoding="UTF-8") entrada.readline() entrada.readline() listaPuntaje = [] for linea in entrada: datos = linea.split("&") puntos = int(datos[8]) equipos = datos[0].upper() dupla = equipos, puntos listaPuntaje.append(dupla) entrada.close() return listaPuntaje # Motrar equipos con mala puntaución def listarEquiposMalRepostados(nombreArchivo): entrada = open(nombreArchivo, "r") entrada.readline() entrada.readline() listaEquiposPuntos = [] for linea in entrada: datos = linea.split("&") equipo = (datos[0]) jg = int(datos[2]) je = int(datos[3]) pr = int(datos[8]) pc = jg * 3 + je * 1 if pr != pc: listaEquiposPuntos.append(equipo) entrada.close() return listaEquiposPuntos # Muestra grafica con respecto al archivo def graficarPuntos(nombreArchivo): entrada = open(nombreArchivo, "r") entrada.readline() entrada.readline() listaEquipos = [] listaPuntos = [] for linea in entrada: datos = linea.split("&") listaEquipos.append(datos[0]) listaPuntos.append(int(datos[8])) plot.plot(listaEquipos, listaPuntos) plot.show()
import re from parler.dataType.hashtags import Hashtags from parler.dataType.hashtag import Hashtag class HashtagsParser: ''' Parses all hashtags from the given text. ''' def __init__(self, text): self.text = text if text is not None else "" def parse(self): ''' Helper function to find all hashtags used inside the text. ''' # https://www.nltk.org/_modules/nltk/tokenize/casual.html#TweetTokenizer # Use the regex based on tweet tokenizer for handles and replace the starting @ with # hashtag_re = re.compile( r"(?<![A-Za-z0-9_!@#\$%&*])#(([A-Za-z0-9_]){20}(?!@))|(?<![A-Za-z0-9_!@#\$%&*])#(([A-Za-z0-9_]){1,19})(?![A-Za-z0-9_]*@)", re.UNICODE) hashtags = Hashtags() for match in hashtag_re.finditer(self.text): text = match.group().strip() end_index = match.end() start_index = end_index - len(text) hashtags.add(Hashtag(text=text[1:], indices=[ start_index, end_index])) return hashtags
import RPi.GPIO as GPIO import time # blinking function def blink(pin): GPIO.output(pin,GPIO.HIGH) time.sleep(1) GPIO.output(pin,GPIO.LOW) time.sleep(1) return # to use Raspberry Pi board pin numbers GPIO.setmode(GPIO.BOARD) # set up GPIO output channel GPIO.setup(38, GPIO.OUT) GPIO.setup(40, GPIO.OUT) # blink GPIO17 50 times for i in range(0,50): blink(38) #38 - RIGHT blink(40) #40 left GPIO.cleanup()
#!/usr/bin/env python3 # -*- coding: utf-8 -*- ''' This file contains the logic and scoring functions for each Pichu piece. Internally, we represented each bird as its equivalent Chess piece, but for the record, here is how we assigned each bird: P/p = Parakeet = Pawn R/r = Robin = Rook B/b = Bluejay = Bishop Q/q = Quetzal = Queen K/k = Kingfisher = King N/n = Nighthawk = Knight The first class is Piece which contains some of the basic functions for a Piece, such as defining its color, testing equivalence, and returning moves. Each bird then subclasses Piece and overrides some inherited functions, specifically moves() and score(). Below the Piece class are the classes for specific kinds of pieces, such as Kingfisher/King, Nighthawk/Knight, etc. Each piece contains a list of square values* and overrides __repr__, moves(), and score(). The __repr__ is a function to represent each piece as a chess piece from unicode, which makes viewing board states easier. The moves() function return all possible, legal moves that the piece can make given its current position. It is assumed that white parakeets starting on row 2 and black parekeets on row 7 are able to move two spaces. The score() function returns the piece's point value. For each piece, we assumed the following values: Parakeet = Pawn = 100 Robin = Rook = 500 Bluejay = Bishop = 330 Quetzal = Queen = 900 Kingfisher = King = 20000 Nighthawk = Knight = 320 Each piece also contains a square score that varies this score slightly. This encourage pieces to take more advantageous squares if possible and avoid squares that are not as valuable. For example, Quetzals/Queens and Nighthawk/Knights are more valuable towards the center of the board. Likewise, parakeets/pawns become more valuable as they approach the opposite side of the board and get closer to becoming a promoted Quetzal/Queen. References: The values of each piece and square was taken from: https://chessprogramming.wikispaces.com/Simplified+evaluation+function ''' import abc from Position import Position ''' Parent class Piece. All bird types inherit from this class. __init__: records the bird's color. moves(): returns the possible moves for the piece given the board state and the bird's color. score(): returns the value of the piece given a position on a board. __eq__(): equivalence test when comparing to other pieces. __ne__(): equivalence test when comparing to other pieces. ''' class Piece(): def __init__(self, color): self.color = color @abc.abstractmethod def moves(self, board, pos): return @abc.abstractmethod def score(self, board, pos): return def __eq__(self, other): if isinstance(other, self.__class__): return self.color == other.color else: return False def __ne__(self, other): return not self.__eq__(other) ''' King/Kingfisher class. The square values denote the value of each square for the king. The scoring assumes we're in the midgame rather than early/late game. The encouragement is to keep the king relatively safe on the back row and out of harms way towards the corners. Note that the values are considered from the piece's starting position - so black and white look at the list from the same perspective (both king's starting square value is 0 rather than 0 and -50). __repr__(): Returns a unicode string representing a black/white king. moves(): Returns a list of valid moves where each move represents a tuple of the piece's current position and its destination. Kings can move one square in any direction that is not occupied by a piece of the same color. score(): Returns the king's value given its position. Kings are assumed to be worth 20000. In practice, the king is worth much more as a capture is a terminal state resulting in the board state being worth an extreme value to encourage capture. ''' class King(Piece): square_values = [[-30,-40,-40,-50,-50,-40,-40,-30], \ [-30,-40,-40,-50,-50,-40,-40,-30], \ [-30,-40,-40,-50,-50,-40,-40,-30], \ [-30,-40,-40,-50,-50,-40,-40,-30], \ [-20,-30,-30,-40,-40,-30,-30,-20], \ [-10,-20,-20,-20,-20,-20,-20,-10], \ [20, 20, 0, 0, 0, 0, 20, 20], \ [20, 30, 10, 0, 0, 10, 30, 20]] def __repr__(self): if self.color == "w": return u'♔' else: return u'♚' def moves(self, board, pos): possible = [] for i in [1, -1]: #Up/Down valid, _ = ValidMove(board, self, pos.offset(i, 0)) if valid: possible.append((pos, pos.offset(i, 0))) #Left/Right valid, _ = ValidMove(board, self, pos.offset(0, i)) if valid: possible.append((pos, pos.offset(0, i))) #Up/Right and Down/Left valid, _ = ValidMove(board, self, pos.offset(i, i)) if valid: possible.append((pos, pos.offset(i, i))) #Up/Left and Down/Right valid, _ = ValidMove(board, self, pos.offset(i, -i)) if valid: possible.append((pos, pos.offset(i, -i))) return possible def score(self, board, pos): if self.color == 'w': points = 20000 + self.square_values[7 - pos.row][pos.col] else: points = -20000 - self.square_values[pos.row][7 - pos.col] return points ''' Knight/Nighthawk class. The square values denote the value of each square for a knight. The encouragement is to keep knights in the relative center of the board where they are able to attack more freely. __repr__(): Returns a unicode string representing a black/white knight. moves(): Returns a list of valid moves where each move represents a tuple of the piece's current position and its destination. Knights can move 2 spaces up/down and then 1 left/right or 2 spaces left/down and then 1 space up/down. Unlike other pieces, Knights are able to move over other pieces. This means we only have to check if the destination square is a valid square rather than every intermediate square. score(): Returns the knights's value given its position. Knights are assumed to be worth 320 points. ''' class Knight(Piece): move_r = [-2, -1, -2, 1, 2, -1, 2, 1] move_c = [-1, -2, 1, -2, -1, 2, 1, 2] square_values = [[-50,-40,-30,-30,-30,-30,-40,-50], \ [-40,-20, 0, 0, 0, 0,-20,-40], \ [-30, 0, 10, 15, 15, 10, 0,-30], \ [-30, 5, 15, 20, 20, 15, 5,-30], \ [-30, 0, 15, 20, 20, 15, 0,-30], \ [-30, 5, 10, 15, 15, 10, 5,-30], \ [-40,-20, 0, 5, 5, 0,-20,-40], \ [-50,-40,-30,-30,-30,-30,-40,-50]] def __repr__(self): if self.color == "w": return u'♘' else: return u'♞' def moves(self, board, pos): possible = [] for r, c in zip(self.move_r, self.move_c): valid, _ = ValidMove(board, self, pos.offset(r, c)) if valid: possible.append((pos, pos.offset(r, c))) return possible def score(self, board, pos): if self.color == 'w': points = 320 + self.square_values[7 - pos.row][pos.col] else: points = -320 - self.square_values[pos.row][7 - pos.col] return points ''' Rook/Robin class. The square values denote the value of each square for a rook. The encouragement is to keep rooks centered or towards the enemy's side of the board where they can capture unmoved pieces. The encouragement isn't very strong as rooks are capable of moving an entire board's width/length. __repr__(): Returns a unicode string representing a black/white rook. moves(): Returns a list of valid moves where each move represents a tuple of the piece's current position and its destination. Rooks can move up/down/left/right any number of squares until they run into another piece. If it's the same color, it must stop the square before. If it's a differnet color, then it can move into that square and capture the piece. score(): Returns the rook's value given its position. Rooks are assumed to be worth 500 points. ''' class Rook(Piece): square_values = [[0, 0, 0, 0, 0, 0, 0, 0], \ [5, 10, 10, 10, 10, 10, 10, 5], \ [-5, 0, 0, 0, 0, 0, 0, -5], \ [-5, 0, 0, 0, 0, 0, 0, -5], \ [-5, 0, 0, 0, 0, 0, 0, -5], \ [-5, 0, 0, 0, 0, 0, 0, -5], \ [-5, 0, 0, 0, 0, 0, 0, -5], \ [0, 0, 0, 5, 5, 0, 0, 0]] def __repr__(self): if self.color == "w": return u'♖' else: return u'♜' def moves(self, board, pos): possible = [] for i in [-1, 1]: possible += GoInDirection(board, self, pos, i, 0) #Up/Down possible += GoInDirection(board, self, pos, 0, i) #Left/Right return possible def score(self, board, pos): if self.color == 'w': points = 500 + self.square_values[7 - pos.row][pos.col] else: points = -500 - self.square_values[pos.row][7 - pos.col] return points ''' Bishop/Bluejay class. The square values denote the value of each square for a bishop. The encouragement is to keep bishops back and centered. __repr__(): Returns a unicode string representing a black/white bishop. moves(): Returns a list of valid moves where each move represents a tuple of the piece's current position and its destination. Bishops can move diagonally any number of squares until they run into another piece. If it's the same color, it must stop the square before. If it's a differnet color, then it can move into that square and capture the piece. score(): Returns the bishop's value given its position. Rooks are assumed to be worth 330 points. ''' class Bishop(Piece): square_values = [[-20,-10,-10,-10,-10,-10,-10,-20], \ [-10, 0, 0, 0, 0, 0, 0,-10], \ [-10, 0, 5, 10, 10, 5, 0,-10], \ [-10, 5, 5, 10, 10, 5, 5,-10], \ [-10, 0, 10, 10, 10, 10, 0,-10], \ [-10, 10, 10, 10, 10, 10, 10,-10], \ [-10, 5, 0, 0, 0, 0, 5,-10], \ [-20,-10,-10,-10,-10,-10,-10,-20]] def __repr__(self): if self.color == "w": return u'♗' else: return u'♝' def moves(self, board, pos): possible = [] for i in [-1, 1]: possible += GoInDirection(board, self, pos, i, i) #DownLeft/UpRight possible += GoInDirection(board, self, pos, i, -i) #DownRight/UpLeft return possible def score(self, board, pos): if self.color == 'w': points = 330 + self.square_values[7 - pos.row][pos.col] else: points = -330 - self.square_values[pos.row][7 - pos.col] return points ''' Queen/Quetzal class. The square values denote the value of each square for a queen. The encouragement is to keep queens relatively centered on the board and away from the corners/edges which minimize its movement potential. __repr__(): Returns a unicode string representing a black/white queen. moves(): Returns a list of valid moves where each move represents a tuple of the piece's current position and its destination. Queen can move in any direction any number of squares until they run into another piece. If it's the same color, it must stop the square before. If it's a differnet color, then it can move into that square and capture the piece. score(): Returns the queen's value given its position. Queens are assumed to be worth 900 points. ''' class Queen(Piece): square_values = [[-20,-10,-10, -5, -5,-10,-10,-20], \ [-10, 0, 0, 0, 0, 0, 0,-10], \ [-10, 0, 5, 5, 5, 5, 0,-10], \ [-5, 0, 5, 5, 5, 5, 0, -5], \ [0, 0, 5, 5, 5, 5, 0, -5], \ [-10, 5, 5, 5, 5, 5, 0,-10], \ [-10, 0, 5, 0, 0, 0, 0,-10], \ [-20,-10,-10, -5, -5,-10,-10,-20]] def __repr__(self): if self.color == "w": return u'♕' else: return u'♛' def moves(self, board, pos): possible = [] for i in [-1, 1]: possible += GoInDirection(board, self, pos, i, 0) #Up/Down possible += GoInDirection(board, self, pos, 0, i) #Left/Right possible += GoInDirection(board, self, pos, i, i) #DownLeft/UpRight possible += GoInDirection(board, self, pos, i, -i) #DownRight/UpLeft return possible def score(self, board, pos): if self.color == 'w': points = 900 + self.square_values[7 - pos.row][pos.col] else: points = -900 - self.square_values[pos.row][7 - pos.col] return points ''' Pawn/parakeet class. The square values denote the value of each square for a pawn. The scores are aimed at moving pawns forward towards the opponents side of the board. This encourages move towards the opposite side where a pawn can be promoted to a Quetzal/Queen. __repr__(): Returns a unicode string representing a black/white pawn. moves(): Returns a list of valid moves where each move represents a tuple of the piece's current position and its destination. Pawns are a bit tricky when it comes to movement. In the normal case, they can either move one square forward into an empty space or one square forward and diagonal to capture another piece. If they're in their initial starting square, pawns may move two squares forward so long as there is no piece in front of it. score(): Returns the pawn's value given its position. Pawns are assumed to be worth 100 points. ''' class Pawn(Piece): square_values = [[0, 0, 0, 0, 0, 0, 0, 0], \ [50, 50, 50, 50, 50, 50, 50, 50], \ [10, 10, 20, 30, 30, 20, 10, 10], \ [5, 5, 10, 25, 25, 10, 5, 5], \ [0, 0, 0, 20, 20, 0, 0, 0], \ [5, -5,-10, 0, 0,-10, -5, 5], \ [5, 10, 10,-20,-20, 10, 10, 5], \ [0, 0, 0, 0, 0, 0, 0, 0]] def __repr__(self): if self.color == "w": return u'♙' else: return u'♟' def moves(self, board, pos): possible = [] if self.color == "w": step = 1 else: step = -1 #Forward movement valid, cont = ValidMove(board, self, pos.offset(step, 0)) if valid and cont: # Moving into empty space possible.append((pos, pos.offset(step, 0))) # Opening move, verify if 2 steps can be made, step by step # We already know if we can do +2 via continue from the +1 movement... if cont and ((pos.row == 1 and self.color == "w") or (pos.row == 6 and self.color == "b")): valid, cont = ValidMove(board, self, pos.offset(step * 2, 0)) if valid and cont : possible.append((pos, pos.offset(step * 2, 0))) #Capture valid, cont = ValidMove(board, self, pos.offset(step, 1)) if valid and not cont: possible.append((pos, pos.offset(step, 1))) valid, cont = ValidMove(board, self, pos.offset(step, -1)) if valid and not cont: possible.append((pos, pos.offset(step, -1))) return possible def score(self, board, pos): if self.color == 'w': points = 100 + self.square_values[7 - pos.row][pos.col] else: points = -100 - self.square_values[pos.row][7 - pos.col] return points ''' This is a helper function for piece movement. It returns two values: Valid: whether or not the piece can move into the proposed square. Continue: whether or not the piece has moved into this square by capture. A move can be valid (either the square is empty or the square was captured) and then continue can be true or false. True if the square was empty and a piece that can move unlimited squares may continue and false if the square was captured and a piece that is able to move unlimited squares must stop. If a move is not valid then continue does not matter and is always false. ''' def ValidMove(board, piece, pos): if not pos: #Out of Bounds return False, False elif board[pos.row][pos.col] == "": #Move into empty space. return True, True elif board[pos.row][pos.col].color != piece.color: #Capture return True, False else: return False, False ''' This is a helper function for pieces that can move an unlimited number of squares in a direction (queen, rook, etc.). The function takes in a board, a piece, its position, and the direction represented by row and column increments (1 or 0). Starting at the given position, it moves the piece in the given direction until it cannot move anymore (runs into a border, captures a piece, etc.) ''' def GoInDirection(board, piece, pos, row_incr, col_incr): moves = [] r_off = row_incr c_off = col_incr cont = True while cont: valid, cont = ValidMove(board, piece, pos.offset(r_off, c_off)) if valid: moves.append((pos, pos.offset(r_off, c_off))) r_off += row_incr c_off += col_incr return moves
def addspace(x): k = 0 length = len(x) currentstring = "" while k < length: currentstring = str(x[k]) + " " + currentstring k = k + 1 print(currentstring)
""" start point = 문제 = https://programmers.co.kr/learn/courses/30/lessons/42578# 정답 = https://programmers.co.kr/learn/courses/30/lessons/42578/solution_groups?language=python3 포모도로 = 4 결국 남의 코드 보고 품... 근데 코드작성 문제가 아니라 문제 자체를 어렵게 생각해서 그런거같음 내가 논리적으로 풀이를 못하네. 수학을 공부해야하나.. 너무 어려운걸, 문제를 쉽게 생각하자 쉽게게 """ clothesA = [["yellow_hat", "headgear"], ["blue_sunglasses", "eyewear"], ["green_turban", "headgear"]] returnA = 5 clothesB = [["crow_mask", "face"], ["blue_sunglasses", "face"], ["smoky_makeup", "face"]] returnB = 3 clothes = clothesA answer = 0 import collections # 경우에 수 # 첫번째 각 아이템 한번 씩 착용 answer += len(clothes) # 두번째 중복되는 아이템은 교차로 착용 가능 type_list = [] for e in clothes: type_list.append(e[-1]) # 경우의 수 계산 mul = 1 lst = list(collections.Counter(type_list).values()) if len(lst) <= 1: mul = 0 elif len(lst) > 1: for i in range(len(lst)): mul *= lst[i] print(answer + mul) def solution1(clothes): """28.6점 나옴""" answer = 0 import collections # 경우에 수 # 첫번째 각 아이템 한번 씩 착용 answer += len(clothes) # 두번째 중복되는 아이템은 교차로 착용 가능 type_list = [] for e in clothes: type_list.append(e[-1]) # 경우의 수 계산 mul = 1 lst = list(collections.Counter(type_list).values()) if len(lst) <= 1: mul = 0 elif len(lst) > 1: for i in range(len(lst)): mul *= lst[i] return answer + mul """ 1. 전체 의상을 하나씩 입을 때(의상 이름 기준) - len(clothes) (의상 종류 기준, 의상이 2개 이상인 종류가 존재) 2. 2개씩 입을 때 - nC2 * 중복된 개수 3. 3개씩 입을 때 - nC3 * 중복된 개수 4. n개씩 입을 때(n은 전체 의상종류) - 1 * 의상이 2개인 개수 최대 n개씩, 최소1 개씩 입음 n = 전체 의상종류 if n=5, 중복 2개, 2개, n = len(dic.keys()) 최소 1개씩 = len(clothes) 2개씩 = 5C2 * 2 * 2 3개씩 = 5C3 * 2 * 2 4개씩 = 5C4 * 2 * 2 n개씩 = 5C5 = 1 * 2 * 2 sum() nCr = n! / r!(n-r)! 1, 1+1 , 1+1+1, if n > len(dic.keys()) -> break """ answer = 0 dic = dict() for e in clothes: if e[1] not in dic.keys(): dic[str(e[1])] = { 'lst': [e[0]], 'above': False, 'count': 1 } else: dic[str(e[1])]['lst'].append(e[0]) dic[str(e[1])]['count'] = len(dic[str(e[1])]['lst']) dic[str(e[1])]['above'] = True # 1번, 각 의상을 한번 씩 입는 수 answer += len(clothes) # 2번 ~ n번까지 exn = len(dic.keys()) # 전체 의상종류 dpn = [] # 전체 의상 중 중복 되는 수 for key in list(dic.keys()): if dic[key]['above']:dpn.append(dic[key]['count']) from math import factorial as fact for i in range(exn)[1:]: answer += fact(exn)/fact(i+1)*fact(exn-(i+1)) * sum(dpn) # nCr * 중복수 # print(i+1) #2,3,4,5 def solution2(clothes): """14.3점 나옴""" answer = 0 dic = dict() for e in clothes: if e[1] not in dic.keys(): dic[str(e[1])] = { 'lst': [e[0]], 'above': False, 'count': 1 } else: dic[str(e[1])]['lst'].append(e[0]) dic[str(e[1])]['count'] = len(dic[str(e[1])]['lst']) dic[str(e[1])]['above'] = True # 1번, 각 의상을 한번 씩 입는 수 answer += len(clothes) # 2번 ~ n번까지 exn = len(dic.keys()) # 전체 의상종류 dpn = [] # 전체 의상 중 중복 되는 수 for key in list(dic.keys()): if dic[key]['above']: dpn.append(dic[key]['count']) from math import factorial as fact for i in range(exn)[1:]: answer += fact(exn) / fact(i + 1) * fact(exn - (i + 1)) * sum(dpn) # nCr * 중복수 # print(i+1) #2,3,4,5 return int(answer) print(solution2(clothesB)) def solution3(clothes): from collections import Counter as con answer = 1 counter = con([value for _, value in clothes]) for key in counter: answer *= (counter[key] + 1) return answer - 1 """************************************""" """다른 사람 풀이""" """ https://itholic.github.io/kata-camouflage/ 각 아이템에는 해당하는 카테고리가 있고, 카테고리별로 아이템을 한 개씩 조합해야 하는 문제이다. 단순히 생각하면 다음과같이 각 카테고리별 아이템 갯수를 구해서 다 곱하면 될 것 같다. (모자의갯수) * (바지의갯수) * (안경의갯수) 하지만 이렇게하면 각 카테고리의 아이템이 “하나씩은 반드시 포함”되는 경우만 계산된다. 예를들어 모자는 쓰지 않고 바지만 입는다거나 하는 경우는 고려되지 않는다. 모자랑 안경만 쓰고 바지는 입지 않는 경우도 고려되지 않는다. 하지만 우리는 이러한 경우도 모두 고려해야한다. 따라서 각 카테고리별로 다음과 같이 “해당 카테고리의 아이템을 장착하지 않는 경우” 한개를 더 추가해서 계산해야한다. (모자의갯수 + 1) * (바지의갯수 + 1) * (안경의갯수 + 1) 이렇게하면 특정 카테고리가 제외되는 경우까지 모두 고려된다. 하지만 여기서 끝내면 안된다. 스파이는 반드시 한 개의 아이템은 장착해야 하므로, 어떤 아이템도 장착하지 않는 한 개의 경우는 결과에서 빼줘야한다. 즉, 최종 계산은 다음과 같은 형태가 된다. (모자의갯수 + 1) * (바지의갯수 + 1) * (안경의갯수 + 1) - 1 """ from collections import Counter def kata_solution(clothes): counter_each_category = Counter([cat for _, cat in clothes]) all_possible = 1 for key in counter_each_category: all_possible *= (counter_each_category[key] + 1) return all_possible - 1
""" Rabbit MQ server - tutorial first part of this using RabbitMQ and send a single message to queue To do these, we need to establish a connection with Rabbit MQ sever *Description RabbitMQ server : Broker between producer(sender) and customer(reciever) pika : protocol """ import pika connection = pika.BlockingConnection(pika.ConnectionParameters('localhost')) channel = connection.channel() """ if we wanted to connect to a broker on a different machine we'd simply specify its name or IP address here instaed of localhost """ channel.queue_declare(queue='hello') channel.basic_publish(exchange='', routing_key='hello', #<- The queue name body='Hello World!') """making queue""" print(" [x] Sent 'Hello World!'") connection.close()
# D. verbing # Given a string, if its length is at least 3, # add 'ing' to its end. # Unless it already ends in 'ing', in which case # add 'ly' instead. # If the string length is less than 3, leave it unchanged. # Return the resulting string. def verbing(s): # +++your code here+++ i = 'ing' y = 'ly' return s if len(s) < 3 else ("".join((s, i)) if s[-3:] != i else "".join((s, y))) def test(got, expected): if got == expected: prefix = ' OK ' else: prefix = ' X ' print('%s got: %s expected: %s' % (prefix, repr(got), repr(expected))) def main(): print('verbing') test(verbing('hail'), 'hailing') test(verbing('swiming'), 'swimingly') test(verbing('do'), 'do') test(verbing('paingt'), 'paingting') if __name__ == '__main__': main()
def mix_up(a, b): return " ".join(("".join((b[:2], a[2:])), "".join((a[:2], b[2:])))) def test(got, expected): if got == expected: prefix = ' OK ' else: prefix = ' X ' print('%s got: %s expected: %s' % (prefix, repr(got), repr(expected))) # Provided main() calls the above functions with interesting inputs, # using test() to check if each result is correct or not. def main(): print('mix_up') test(mix_up('mix', 'pod'), 'pox mid') test(mix_up('dog', 'dinner'), 'dig donner') test(mix_up('gnash', 'sport'), 'spash gnort') test(mix_up('pezzy', 'firm'), 'fizzy perm') # Standard boilerplate to call the main() function. if __name__ == '__main__': main()
# PR hitung julah huruf 'c' dan kata 'startup' nama = 'Purwadhika Startup & Coding School' countc = nama.count('c') countstartup = nama.count('Startup') findc = nama.find('h') countspace = nama.count(' ') print (str(countstartup)*3) print (countc) print (findc) print (countspace) ####################### #Jumlah huruf #1st method - For Loop count = 0 for i in nama.lower(): if(i == 'c'): count = count + 1 print('Jumlah c : ', count) #2nd method - Count count = 0 count = nama.lower().count('c') print('Jumlah c 2nd method: ', count) #3rd method - If Expression count = 0 temp = nama.lower().index('c') if(temp > 0): count = count + 1 temp = nama[temp:len(nama)].index('c') if(temp > 0): count = count + 1 print('Jumlah c 3rd method: ', count) #4th method cari = 'c' x = nama.lower().replace(cari, '') print(x) jumlahCari = len(nama) - len(x) print(f'Jumlah huruf \'{cari}\' ada = {jumlahCari}') #Jumlah kata startup #1st method wordCounter = nama.lower().count('startup') print('Jumlah kata startup :', wordCounter) #2nd method yangDicari = 'startup' x = nama.lower().replace(yangDicari, '') jumlahCari = len(nama) - len(x) print(f'Jumlah kata \'{yangDicari}\' ada = {int(jumlahCari/len(yangDicari))}') ''' def cariIndex(list, i): return [x for x, y in enumerate(list) if y == i] print(cariIndex(a, 3)) '''
''' class X: def __init__ (self, nama): self.nama = nama class Y(X): def __init__ (self,nama,gelar): X.__init__(self,nama) class Y(X): def __init__ (self,nama,gelar, univ): X.__init__(self,nama) self.gelar = gelar self.kampus = univ # class Y(X): # def __init__ (self, nama, gelar): # super().__init__(nama, gelar) objX = X('Andi') objY = Y('Budi', 'Dr', 'AtmaJaya') objZ = Y('Ujang','S1', 'UI') objZ.pacar = 'jomblo' setattr(objZ, 'alamat', 'BSD') print (objY.kampus) print (getattr(objY, 'nama')) print (hasattr(objY, 'pacar')) from pprint import pprint pprint (vars(objY)) print (vars(objY)) print (vars(objZ)) # delete delattr(objZ, 'alamat') print (vars(objZ)) del Y.nama #hapus attribute pada class, bukan object ya! print (objY.kampus) ''' # _________________ class student: def __init__(self, nama, usia, status): self.nama = nama self.usia = usia self.status = status data = [ {'nama':'Andi', 'usia': 21, 'status': 'jomblo'}, {'nama':'Budi', 'usia': 21, 'status': 'jomblo'}, {'nama':'Caca', 'usia': 21, 'status': 'jomblo'}, {'nama':'Deni', 'usia': 21, 'status': 'jomblo'} ] # dataA = [] # for a in data: # A= a.values() # nama = a.get('nama') # usia = a.get('usia') # status = a.get('status') # print (status) # def createObj(x): # nama = x['nama'] # vars()[nama]=student(x['nama'],x['usia'], x['status']) # return vars()[nama] # def createObj(x): # return student(x['nama'], x['usia'], x['status']) #simplifikasi # dataNew = map (func, iterable) # dataNew = list(map (createObj, data)) dataNew = list(map( lambda x : student(x['nama'], x['usia'], x['status']), data)) #pake lambda function # print (dataNew[0].nama) #pangggil namanya siapa print (dataNew[0].nama) # namaz = 'ultraman' # ultraman adalah isi variabel # vars()[namaz] = 12345 #isi variabel diambil dijadikan variabel # print (ultraman)
import pandas import pandasql weather_data = pandas.read_csv('../podaci/weather-underground.csv') # SQL query should return one column and one row - a count of the number of days in the dataframe where the rain column is equal to 1 (days it rained) q = """ SELECT COUNT(*) FROM weather_data WHERE rain = 1 """ rainy_days = pandasql.sqldf(q.lower(), locals()) print rainy_days
# Создайте словарь типа "вопрос": "ответ", например: {"Как дела": "Хорошо!", "Что делаешь?": "Программирую"} и так далее. # Напишите функцию ask_user() которая с помощью функции input() просит пользователя ввести вопрос, # а затем, если вопрос есть в словаре, программа давала ему соотвествующий ответ. Например: # Пользователь: Что делаешь? # Программа: Программирую questions_and_answers = { "Как дела": "Хорошо!", "Что делаешь": "Программирую", "Кто ты":"Представитель цифрового мира", "Сколько времени":"Сколько есть, всё ваше" } def ask_user(answers_dict): while True: user_input = input() programm_output = answers_dict.get(user_input.capitalize().replace('?',''), "Даже не знаю что сказать...") print(programm_output) if __name__ == "__main__": print("Какой у вас вопрос?") ask_user(questions_and_answers)
""" Mykola Kryvyi Lab 0.1 Github link: https://github.com/mykolakryvyi/skyscrapers.git """ def read_input(path: str): """ Read game board file from path. Return list of str. """ file = open(path , 'r') contents = file.readlines() contents = list(map(lambda x: x.strip(),contents)) return contents def left_to_right_check(input_line: str, pivot: int): """ Check row-wise visibility from left to right. Return True if number of building from the left-most hint is visible looking to the right, False otherwise. input_line - representing board row. pivot - number on the left-most hint of the input_line. >>> left_to_right_check("412453*", 4) True >>> left_to_right_check("452453*", 5) False """ #my_list = [] right_pivot = int(input_line[0]) if pivot > right_pivot: right_pivot = pivot input_line = list(input_line[1:-1]) array = [int(i) for i in input_line] counter = 1 for index, elem in enumerate(array): check_el = False for i in range(index): if elem > array[i]: check_el = True else: check_el = False break if check_el == True: counter+=1 #my_list.append(elem) if counter == right_pivot: return True return False print(left_to_right_check("132345*", 3)) def check_not_finished_board(board: list): """ Check if skyscraper board is not finished, i.e., '?' present on the game board. Return True if finished, False otherwise. >>> check_not_finished_board(['***21**', '4?????*',\ '4?????*', '*?????5', '*?????*', '*?????*', '*2*1***']) False >>> check_not_finished_board(['***21**', '412453*',\ '423145*', '*543215', '*35214*', '*41532*', '*2*1***']) True >>> check_not_finished_board(['***21**', '412453*',\ '423145*', '*5?3215', '*35214*', '*41532*', '*2*1***']) False """ for i in board: if '?' in i: return False return True def check_uniqueness_in_rows(board: list): """ Check buildings of unique height in each row. Return True if buildings in a row have unique length, False otherwise. >>> check_uniqueness_in_rows(['***21**', '412453*',\ '423145*', '*543215', '*35214*', '*41532*', '*2*1***']) True >>> check_uniqueness_in_rows(['***21**', '452453*',\ '423145*', '*543215', '*35214*', '*41532*', '*2*1***']) False >>> check_uniqueness_in_rows(['***21**', '412453*',\ '423145*', '*553215', '*35214*', '*41532*', '*2*1***']) False """ board = board[1:-1] for row in board: row = list(row[1:-1]) row = [int(x) for x in row if x!='*'] if len(row)!=len(set(row)): return False return True def check_horizontal_visibility(board: list): """ Check row-wise visibility (left-right and vice versa) Return True if all horizontal hints are satisfiable, i.e., for line 412453* , hint is 4, and 1245 are the four buildings that could be observed from the hint looking to the right. >>> check_horizontal_visibility(['***21**', '412453*', '423145*',\ '*543215', '*35214*', '*41532*', '*2*1***']) True >>> check_horizontal_visibility(['***21**', '452453*',\ '423145*', '*543215', '*35214*', '*41532*', '*2*1***']) False >>> check_horizontal_visibility(['***21**', '452413*',\ '423145*', '*543215', '*35214*', '*41532*', '*2*1***']) False """ board = board[1:-1] for i in board: if i[0]!='*': leftright = left_to_right_check(i,0) if leftright == False: return False if i[-1]!='*': rightleft = left_to_right_check(i[::-1],0) if rightleft == False: return False return True def check_columns(board: list): """ Check column-wise compliance of the board for uniqueness (buildings of unique height) and visibility (top-bottom and vice versa). Same as for horizontal cases, but aggregated in one function for vertical case, i.e. columns. >>> check_columns(['***21**', '412453*', '423145*',\ '*543215', '*35214*', '*41532*', '*2*1***']) True >>> check_columns(['***21**', '412453*', '423145*',\ '*543215', '*35214*', '*41232*', '*2*1***']) False >>> check_columns(['***21**', '412553*', '423145*',\ '*543215', '*35214*', '*41532*', '*2*1***']) False """ count = 0 array = [] for _ in board: columnline = '' for _, elem in enumerate(board): columnline = columnline + elem[count] array.append(columnline) count+=1 columnscheck = check_horizontal_visibility(array) uniquecheck = True array_for_check_unique = [i[1:-1] for i in array][1:-1] for i in array_for_check_unique: lst = list(i) lst = [int(i) for i in lst] if len(lst)!=len(set(lst)): uniquecheck = False break return uniquecheck and columnscheck def check_skyscrapers(input_path: str): """ Main function to check the status of skyscraper game board. Return True if the board status is compliant with the rules, False otherwise. """ array = read_input(input_path) final = (check_not_finished_board(array) and check_uniqueness_in_rows(array) and \ check_horizontal_visibility(array) and check_columns(array)) return final
#Tuple Unpacking: assigning of tuples elements to variables. #note: count of variables must to equals to count of element else it will through an error like : "Too many tuples to unpack" # Example days = ("Mon","Tues","Wed") print(days) #now lets unpack it day1,day2,day3 = (days) #here tuples elements are assigned to individual elements print(day1) print(day2) print(day3) #error code : "too many values to unpack (expected 2)" # day1,day2, = (days) #this is error code.. do not try this.. just for undestanding
#Range() Function: to generate a range of list Number_List = list(range(1,11)) print(Number_List)
#Natural Language Processing : is manily used to process free text or content or any kind of document to understand the person's #thoughts and thinking. Basically analysing sentences and words of any person. #before you start , please download nltk entire supporting packages. # install nltk package # > pip install nltk # cmd > nltk.download() # this will pop-up a window with releated packages. Select all packages and click on download. # Buzz words: #1. Tokenize : breaking of sentences into words or breaking of words into character #2. CORPORA : collection of text or documents #3. LEXICON : Its like a dictionary of words with its contextual meanning import nltk #importing tokenize which is of two type : sentence (breaking of sentence into words) and word (breaking of words into characters) from nltk.tokenize import word_tokenize, sent_tokenize #importing stop words using CORPUS module from nltk.corpus import stopwords #Importing stemming : it help to cummiulate words with same meaning into 1 word. like: if there two wrods eat and eating are there in your content #then is model will help us making onw word which is : eat from nltk.stem import PorterStemmer #Part of Speach tagging: its like tagging each and every word from nltk.corpus import state_union from nltk.tokenize import PunktSentenceTokenizer #creating sample content Sample_content = "Hi i am learning NLPL with Mr. Sanjay" #now tokenize word Get_Words = word_tokenize(Sample_content) #print(Get_Words) #Tokenize sentence Get_Sentence = sent_tokenize(Sample_content) #print(Get_Sentence) # STOPWORDS : identifying/removing words which are not required for our analysis #initialize variable with list of stopwords Get_StopWords = set(stopwords.words("english")) #Now, we check if any english stopwords are there in our Get_Words which is already tokenized. #print tokenized words to comparision with stop word. i:e, to check if stopwords are removed are not print(f"Atual Sentence: {Get_Words}") #loop to run words in Get_Santence and print without stopwords for word in Get_Words: if word not in Get_StopWords: print(word) #**********stemming example****************** #sample content2 Sample_content2 = "He eat what he was eating yesterday at the eatery" #Initialize stemming in new varibale Get_PortStemming = PorterStemmer() #Now stemm the words for word in word_tokenize(Sample_content2): print(Get_PortStemming.stem(word)) #*******************Speach Tagging************* # Sample Content3 Train_Sample = state_union.raw("2005-GWBush.txt") Sample_content3 = state_union.raw("2006-GWBush.txt") Custome_Sent_Tokenizer = PunktSentenceTokenizer(Sample_content3) tokenized = Custome_Sent_Tokenizer.tokenize(Sample_content3) def process_Content(): try: for i in tokenized: Words = nltk.word_tokenize(i) tagged = nltk.pos_tag(Words) print(tagged) #Chunking of words chunkGram = r"""Chunk: {<RB.?>*<VB.?>*<NNP>|<NN>?}""" ChunkParser = nltk.RegexpParser(chunkGram) Chunked = ChunkParser.parse(tagged) print(Chunked) except Exception as Err: print(str(Err)) process_Content()
#Index() Function : to find the position of the element. You can define start and end as well to the index position Number = list(range(1,11)) print(Number) print(Number.index(5,1,10))
#**************Center Method************ Name = input("enter your name : ") print(Name.center(len(Name)+8,"*"))
#Sorting List: it sort the list and changes the original list as well. fruits = ["Apple","Orange","Mango","Banana","Apple","Orange","Pineapple"] fruits.sort() print(fruits) Numbers = [3,5,2,4,1,6,8,7,] Numbers.sort() print(Numbers) #sorted() method : it sorts the list but wont change the original list Numbers1 = [3,5,2,4,1,6,8,7,] print(sorted(Numbers1)) print(Numbers1) #Clear methos () : It clears the entire list Numbers1.clear() print(Numbers1) #Copy() method: you can copy any list and create new list Number2 = Numbers.copy() print(Number2)
#Keys in Dictionary #we can check if key is present in dictionary or not #Example: User= { "Name":"Sanju", "Age": 25 } print(User) #IF Condition to check if key is there or not if "Name" in User: print("Key present") else: print("No Key Found") #We can also check if the value is presnet in dictionary or not if "Sanju" in User.values(): print("Value Present") else: print("No value Found")
# String Formating : using place holder {} we can pass the variable value without converting it into str value while printing the output Name = "Sanju" Age = 25 print(f"My name is {Name} and Age is {Age}") # if you want to increase age by 2 so we can do that calculation as well print(f"My name is {Name} and Age is {Age + 2}") # *********************************************Test********************************************************************** # Ask user to input 3 numbers and you have to print average of all three number. Use String Format concept to get average. # Note: input should be separated by coma nu1,num2,num3 = input("Please enter numbers: ").split() print(f"Average is {(int(nu1)+int(num2)+int(num3))/3}")
#Functions: it helps in avoiding writting same taks code again and again by defining function and call it whenever it requires #Example: suppose you have a senario where you always want to sum two numbers def Sum_Number(Num1,Num2): return(Num1+Num2) Get_Total = Sum_Number(2,2) print(Get_Total) #Example2: Function to concatenate 2 string values FirstName="Sanju" LastName = "Singh" def FullName(Name1,Name2): return(Name1+Name2) print(FullName(FirstName,LastName)) #Example3: Function to retuen last character from the return value def Last_Char(Name): return(Name[-1]) print(Last_Char("Sanjay")) #Example4: Odd or even number def Odd_Even(Num): if Num%2==0: return("Even") else: return("Odd") print(Odd_Even(int(input("Enter Any Number : ")))) #Function without passing any argument or Function without parameters def comments(): return ("Log out") print(comments())
""" Code for maximizing a convex function over a polytope, as defined by a set of linear equalities and inequalities. This uses the fact that the maximum of a convex function over a polytope will be achieved at one of the extreme points of the polytope. Thus, the maximization is done by taking a system of linear inequalities, using the pypoman library to create a list of extreme points, and then evaluating the objective function on each point. We use various techniques to first prune away redundant constraints. """ import numpy as np import scipy import pypoman __all__ = ( 'maximize_convex_function', ) import scipy.spatial.distance as sd def remove_duplicates(A,b): # Removes duplicate rows from system (in)equalities given by A and b while True: N = len(A) mx = np.hstack([b[:,None], A]) dists = sd.squareform(sd.pdist(mx)) duplicates_found = False for ndx1 in range(N): A1, b1 = A[ndx1,:], b[ndx1] keep_rows = np.ones(N, bool) keep_rows[ndx1+1:] = dists[ndx1,ndx1+1:]>1e-08 if not np.all(keep_rows): duplicates_found = True A = A[keep_rows,:] b = b[keep_rows] break if not duplicates_found: break return A, b def eliminate_redundant_constraints(A,b): # Eliminate redundant constraints from the inequality system Ax <= b init_num_cons = A.shape[0] # initial number of constraints N = A.shape[1] # number of variables bounds = [(None,None),]*N keep_rows = list(range(A.shape[0])) nonredundant_rows = set([]) while True: eliminated = False for i in keep_rows: # test whether row i is redundant if i in nonredundant_rows: # already tested this row continue # Current row specifies the constraint b >= a^T x # Let A' and b' indicate the constraints in all the other rows # If b >= max_x a^T x such that b' >= A'x, then this constraint is redundant and can be eliminated other_rows = [j for j in keep_rows if j != i] A_other, b_other = A[other_rows], b[other_rows] c = scipy.optimize.linprog(-A[i], A_ub=A_other, b_ub=b_other, bounds=bounds) optval = -c.fun if c.status == 0 and -c.fun <= b[i] + 1e-15: # solver succeeded and this row is redundant keep_rows = other_rows eliminated = True break else: # row is not redundant nonredundant_rows.add(i) if not eliminated: break A, b = A[keep_rows], b[keep_rows] return A, b def maximize_convex_function(f, A_ineq, b_ineq, A_eq=None, b_eq=None): """ Maximize a convex function over a polytope. Parameters ---------- f : function Objective function to maximize A_ineq : matrix Specifies inequalities matrix, should be num_inequalities x num_variables b_ineq : array Specifies inequalities vector, should be num_inequalities long A_eq : matrix Specifies equalities matrix, should be num_equalities x num_variables b_eq : array Specifies equalities vector, should be num_equalities long Returns tuple optimal_extreme_point, maximum_function_value """ best_x, best_val = None, -np.inf A_ineq = A_ineq.astype('float') b_ineq = b_ineq.astype('float') A_ineq, b_ineq = remove_duplicates(A_ineq, b_ineq) if A_eq is not None: # pypoman doesn't support equality constraints. We remove equality # constraints by doing a coordinate transformation. A_eq = A_eq.astype('float') b_eq = b_eq.astype('float') A_eq, b_eq = remove_duplicates(A_eq, b_eq) # Get one solution that satisfies A x0 = b x0 = scipy.linalg.lstsq(A_eq, b_eq)[0] assert(np.abs(A_eq.dot(x0) - b_eq).max() < 1e-5) # Get projector onto null space of A, it satisfies AZ=0 and Z^T Z=I Z = scipy.linalg.null_space(A_eq) # Now every solution can be written as x = x0 + Zq, since A x = A x0 = b # Inequalities get transformed as # A'x <= b' to A'(x0 + Zq) <= b to (A'Z)q <= b - A'x0 b_ineq = b_ineq - A_ineq.dot(x0) A_ineq = A_ineq.dot(Z) A_ineq, b_ineq = remove_duplicates(A_ineq, b_ineq) transform = lambda q: Z.dot(q) + x0 else: transform = lambda x: x A_ineq, b_ineq = eliminate_redundant_constraints(A_ineq, b_ineq) extreme_points = pypoman.compute_polytope_vertices(A_ineq, b_ineq) for v in extreme_points: x = transform(v) val = f(x) if val > best_val: best_x, best_val = x, val if best_x is None: raise Exception('No extreme points found!') return best_x, best_val
# # -*- coding: utf-8 -* try: import tkinter as tkinter # for python 3.x import tkinter.messagebox as mb except: import Tkinter as tkinter # for python 2.x import tkMessageBox as mb import random, time ''' 欢迎关注 微信公众号菜鸟学Python 更多好玩有趣的实战项目 ''' class Ball(): ball_num = 0 gap = 1 ball_hit_bottom_num = 0 ball_speed = 5 def __init__(self, canvas, paddle, score, color, init_x=100, init_y=100): self.canvas = canvas self.paddle = paddle self.score = score self.color = color self.id = canvas.create_oval(10, 10, 30, 30, fill=self.color) self.canvas.move(self.id, init_x, init_y) Ball.ball_num += 1 starts = [-3, -2, -1, 1, 1, 2, 3] random.shuffle(starts) self.x = starts[0] self.y = -3 self.canvas_height = self.canvas.winfo_height() self.canvas_width = self.canvas.winfo_width() self.hit_bottom = False def adjust_paddle(self, paddle_pos): paddle_grow_length = 30 paddle_width = paddle_pos[2] - paddle_pos[0] if self.color == 'red': # shorten the paddle length if paddle_width > 60: if paddle_pos[2] >= self.canvas_width: paddle_pos[2] = paddle_pos[2] - paddle_grow_length else: paddle_pos[0] = paddle_pos[0] + paddle_grow_length elif self.color == 'green': # stretch the paddle length if paddle_width < 300: if paddle_pos[2] >= self.canvas_width: paddle_pos[0] = paddle_pos[0] - paddle_grow_length else: paddle_pos[2] = paddle_pos[2] + paddle_grow_length self.canvas.coords(self.paddle.id, paddle_pos[0], paddle_pos[1], paddle_pos[2], paddle_pos[3]) def hit_paddle(self, pos): paddle_pos = self.canvas.coords(self.paddle.id) print('paddle_pos:', paddle_pos[0], paddle_pos[1], paddle_pos[2], paddle_pos[3]) if pos[2] >= paddle_pos[0] and pos[0] <= paddle_pos[2]: if pos[3] >= paddle_pos[1] and pos[3] <= paddle_pos[3] + Ball.gap: self.x += self.paddle.x colors = ['red', 'green'] random.shuffle(colors) self.color = colors[0] self.canvas.itemconfigure(self.id, fill=colors[0]) self.score.hit(ball_color=self.color) self.canvas.itemconfig(self.paddle.id, fill=self.color) self.adjust_paddle(paddle_pos) return True return False def draw(self): self.canvas.move(self.id, self.x, self.y) pos = self.canvas.coords(self.id) # print pos if pos[1] <= 0: # move down self.y = 3 if pos[3] >= self.canvas_height: # hit the bottom self.hit_bottom = True if self.hit_paddle(pos) == True: self.y = -4 if pos[0] <= 0: # move right self.x = Ball.ball_speed if pos[2] >= self.canvas_width: # move left self.x = -Ball.ball_speed class Paddle: def __init__(self, canvas, color): self.canvas = canvas self.canvas_width = self.canvas.winfo_width() self.canvas_height = self.canvas.winfo_height() self.id = canvas.create_rectangle(0, 0, 180, 15, fill=color) self.canvas.move(self.id, 200, self.canvas_height * 0.75) self.x = 0 self.started = False self.continue_game = False self.canvas.bind_all('<KeyPress-Left>', self.turn_left) self.canvas.bind_all('<KeyPress-Right>', self.turn_right) self.canvas.bind_all('<KeyPress-Up>', self.continue_game) self.canvas.bind_all('<Button-1>', self.start_game) self.canvas.bind_all('<space>', self.pause_game) def draw(self): self.canvas.move(self.id, self.x, 0) pos = self.canvas.coords(self.id) if pos[0] <= 0: # left edge self.x = 0 elif pos[2] >= self.canvas_width: # right edge self.x = 0 def turn_left(self, evt): pos = self.canvas.coords(self.id) if pos[0] <= 0: self.x = 0 else: self.x = -2 def turn_right(self, evt): pos = self.canvas.coords(self.id) if pos[2] >= self.canvas_width: self.x = 0 else: self.x = 2 def start_game(self, evt): self.started = True def pause_game(self, evt): if self.started: self.started = False else: self.started = True class Score(): def __init__(self, canvas, color): self.score = 0 self.canvas = canvas self.canvas_width = self.canvas.winfo_width() self.canvas_height = self.canvas.winfo_height() self.id = canvas.create_text(self.canvas_width - 150, 10, text='score:0', fill=color, font=(None, 18, "bold")) self.note = canvas.create_text(self.canvas_width - 70, 10, text='--', fill='grey', font=(None, 18, "bold")) def hit(self, ball_color='grey'): self.score += 1 self.canvas.itemconfig(self.id, text='score:{}'.format(self.score)) if ball_color == 'red': self.canvas.itemconfig(self.note, text='{}-'.format('W'), fill='red') elif ball_color == 'green': self.canvas.itemconfig(self.note, text='{}+'.format('W'), fill='green') else: self.canvas.itemconfig(self.note, text='--', fill='grey') def main(): tk = tkinter.Tk() # call back for Quit def callback(): if mb.askokcancel("Quit", "Do you really wish to quit?"): Ball.flag = False tk.destroy() tk.protocol("WM_DELETE_WINDOW", callback) # Init parms in Canvas canvas_width = 600 canvas_hight = 500 tk.title("Ball Game V1.2") tk.resizable(0, 0) tk.wm_attributes("-topmost", 1) canvas = tkinter.Canvas(tk, width=canvas_width, height=canvas_hight, bd=0, highlightthickness=0, bg='#00ffff') canvas.pack() tk.update() score = Score(canvas, 'red') paddle = Paddle(canvas, "magenta") ball = Ball(canvas, paddle, score, "grey") game_over_text = canvas.create_text(canvas_width / 2, canvas_hight / 2, text='Game over', state='hidden', fill='red', font=(None, 18, "bold")) introduce = 'Welcome to Ball GameV1.2:\nClick Any Key--Start\nStop--Enter\nContinue-Enter\n' game_start_text = canvas.create_text(canvas_width / 2, canvas_hight / 2, text=introduce, state='normal', fill='magenta', font=(None, 18, "bold")) while True: if (ball.hit_bottom == False) and ball.paddle.started: canvas.itemconfigure(game_start_text, state='hidden') ball.draw() paddle.draw() if ball.hit_bottom == True: time.sleep(0.1) canvas.itemconfigure(game_over_text, state='normal') tk.update_idletasks() tk.update() time.sleep(0.01) if __name__ == '__main__': main()
# A Mad Libs-like program. #!/usr/bin/python print "Welcome to Mad Libs!" main_char = raw_input("Enter a name: ") adj_1 = raw_input("Enter an adjective: ") adj_2 = raw_input("Enter a second adjective: ") adj_3 = raw_input("Enter one more adjective: ") verb_1 = raw_input("Enter a verb: ") verb_2 = raw_input("Enter a second verb: ") verb_3 = raw_input("Enter one more verb: ") print "Now we will need four (4) nouns" noun_1 = raw_input("Enter the first noun: ") noun_2 = raw_input("Enter a second noun: ") noun_3 = raw_input("Enter a third noun: ") noun_4 = raw_input("Enter the last noun: ") animal = raw_input("Enter an animal: ") food = raw_input("Enter a food: ") fruit = raw_input("Enter a fruit: ") number = raw_input("Enter a number: ") superhero = raw_input("Name a superhero: ") country = raw_input("Name a country: ") dessert = raw_input("Name a favorite dessert: ") year = raw_input("Enter a year: ") #The template for the story STORY = "This morning I woke up and felt %s because %s was going to finally %s over the big %s %s.\nOn the other side of the %s were many %ss protesting to keep %s in stores.\nThe crowd began to %s to the rythym of the %s, which made all of the %ss very %s.\n%s tried to %s into the sewers and found %s rats.\nNeeding help, %s quickly called %s.\n%s appeared and saved %s by flying to %s and dropping %s into a puddle of %s.\n%s then fell asleep and woke up in the year %s, in a world where %ss ruled the world.\n" print STORY % (adj_1, main_char, verb_1, adj_2, noun_1, noun_2, animal, food, verb_2, noun_3, fruit, adj_3, main_char, verb_3, number, main_char, superhero, superhero, main_char, country, main_char, dessert, main_char, year, noun_4)
#!/usr/bin/python3 # Script to demonstrate Python comparison and boolean operators. import random # Some relationals. Relationals in Python can be chained, and are # interpreted with an implicit and. c = -2 for a in range(1,4): c = c + 4 for b in range(1,4): print('(' + str(a), '<', str(b) + ') ==', a < b, ' ', '(' + str(a), '>=', b, '>', str(c) + ') ==', a >= b > c, ' ', '(' + str(a), '==', b, '==', str(c) + ') ==', a == b == c, ' ', '(' + str(a), '!=', b, '!=', str(c) + ') ==', a != b != c) c = c - 1 print() # Some boolean operations on comparisons. You have to spell these out # Pascal- or Ada- style. None of this && and || stuff. (Appeals to # shiftless typists.) c = -1 for a in range(0,3): c = c + 5 for b in range(0,3): print('(' + str(a), '==', b, 'or', a, '==', c, 'and', b, '<', str(c) + ') ==', a == b or a == c and b < c, ' ', '(not', a, '<', str(b) + ') ==', not a < b, ' ') c = c - 2 print() # When and or or returns true, it returns the second argument. c = -1 for a in [0, 3, 4]: c = c + 2 for b in [-2, 0, 5]: print('(' + str(a), 'and', b, 'or', str(c) + ') ==', a and b or c, ' ', '(' + str(a), 'or', b, 'and', str(c) + ') ==', a or b and c) c = c - 1 print() # Don't forget the very useful in operator. This works on most (all?) of the # built-in data structures, including strings. some = [2,4,7] for a in range(1,5): if a in some: print(a, 'is', end=' ') else: print(a, 'is not', end=' ') print('in', some)
#!/usr/bin/python3 # Script to copy standard input to standard output, one line at a time, # now using a break. import sys # Loop until terminated by the break statement. while 1: # Get the line, exit if none. line = sys.stdin.readline() if not line: break # Print the line read. print(line[:-1])
''' Script for caching three graphs from one of the examples from the post [1], for use in an interactive post. [1] https://jessicastringham.net/2019/07/01/systems-modeling-from-scratch/ ''' import numpy as np import json from model_simulation import * # In this model, fish regenerate slower if there aren't many other fish, or if there are too many other fish. def regeneration_rate_given_resource(resource): scaled_resource = (resource/1000) if scaled_resource < 0.5: adjusted_resource = scaled_resource else: adjusted_resource = (1 - scaled_resource) rate = np.tanh(12 * adjusted_resource - 3) rate = (rate + 1)/4 return max(0, rate) # People require fish, and are willing to pay more for fish if it is scarce. def price_given_yield_per_unit_capital(yield_per_unit_capital): return 8.8 * np.exp(-yield_per_unit_capital*4) + 1.2 def yield_per_unit_capital_given_resource(resource, some_measure_of_efficiency): return min(1, max(0, (np.tanh(resource/1000*6 - 3 + some_measure_of_efficiency))/1.9 + 0.5)) def renewable_resource(some_measure_of_efficiency): return System([ StockComponent( name='resource', initial_value=1000, inflow='regeneration', outflow='harvest', min_value=0, ), FlowComponent( name='regeneration', initial_value=0, equation=lambda t, resource, regeneration_rate: resource * regeneration_rate, parents=[Parent('resource'), Parent('regeneration_rate')] ), FlowComponent( name='harvest', initial_value=0, equation=lambda t, resource, capital, yield_per_unit_capital: min(resource, capital * yield_per_unit_capital), parents=[Parent('resource'), Parent('capital', prev_timestep=True), Parent('yield_per_unit_capital')] ), StockComponent( name='capital', initial_value=5, inflow='investment', outflow='depreciation', min_value=0, ), FlowComponent( name='investment', equation=lambda t, profit, growth_goal: max(0, min(profit, growth_goal)), initial_value=0, parents=[Parent('profit'), Parent('growth_goal')] ), FlowComponent( name='depreciation', equation=lambda t, capital, capital_lifetime: capital/capital_lifetime, initial_value=0, parents=[Parent('capital', prev_timestep=True), Parent('capital_lifetime')] ), InfoComponent( name='capital_lifetime', equation=lambda _: 20), InfoComponent( name='growth_goal', equation=lambda t, capital: capital * .1, parents=[Parent('capital', prev_timestep=True)]), InfoComponent( name='profit', equation=lambda t, price, harvest, capital: (price * harvest) - capital, parents=[Parent('price'), Parent('harvest'), Parent('capital', prev_timestep=True)] ), InfoComponent( name='price', equation=lambda t, yield_per_unit_capital: price_given_yield_per_unit_capital(yield_per_unit_capital), parents=[Parent('yield_per_unit_capital')] ), InfoComponent( name='regeneration_rate', equation=lambda t, resource: regeneration_rate_given_resource(resource), parents=[Parent('resource')]), InfoComponent( name='yield_per_unit_capital', equation=lambda t, resource: yield_per_unit_capital_given_resource(resource, some_measure_of_efficiency), parents=[Parent('resource')] ) ]) if __name__ == '__main__': years = 200 samples_per_year = 1 t_num = years * samples_per_year dt = 1/samples_per_year # First generate all data. For each some_measure_of_efficiency, # compute the three graphs. xs_yield = np.linspace(0, 1000, 100) xs_simulated_resource = np.linspace(0, years, t_num + 1) xs_simulated_capital = xs_simulated_resource # same as resource graph_data_yield = {} graph_data_simulated_resource = {} graph_data_simulated_capital = {} tap_location_values = np.linspace(-0.5, 1.5, 20) # Cache the function for each tap_locations for yield_parameter in tap_location_values: s = renewable_resource(yield_parameter) simulation = s.simulate(t_num, dt) graph_data_yield[yield_parameter] = [ yield_per_unit_capital_given_resource(x, yield_parameter) for x in xs_yield ] graph_data_simulated_resource[yield_parameter] = simulation['resource'] graph_data_simulated_capital[yield_parameter] = simulation['capital'] database = { 'yield_parameters': list(sorted(graph_data_yield.keys())), 'yield_graph': { 'xs': list(xs_yield), 'ys_by_yield_parameter': graph_data_yield, 'x_domain': [min(xs_yield), max(xs_yield)], 'y_domain': [0, 1], }, 'yield_simulated_resource': { 'xs': list(xs_simulated_resource), 'ys_by_yield_parameter': graph_data_simulated_resource, 'x_domain': [min(xs_simulated_resource), max(xs_simulated_resource)], 'y_domain': [0, 1200], }, 'yield_simulated_capital': { 'xs': list(xs_simulated_capital), 'ys_by_yield_parameter': graph_data_simulated_capital, 'x_domain': [min(xs_simulated_capital), max(xs_simulated_capital)], 'y_domain': [0, 1200], }, } print(json.dumps(database))
from sklearn import linear_model N=input().split() m=int(N[0]) #number of independepent variable n=int(N[1]) # number of dataset X=[] Y=[] for _ in range(n): l=list(map(float,input().strip().split(' '))) X.append(l[0:len(l)-1])#Exluding last number for getting x values Y.append(l[len(l)-1])# Getting y values lm = linear_model.LinearRegression() lm.fit(X, Y) #fitting the function a = lm.intercept_ #Constant value in the equation b = lm.coef_ # Coefficients N1=int(input()) # Test Values for _ in range(N1): # l=list(map(float,input().strip().split(' '))) #Number of lists result=a #Adding constant value to equation for i in range(len(l)): result+=l[i]*b[i] #Adding other terms the result print("%0.2f"%result)
#!/usr/bin/env python # coding: utf-8 # SVM Algorithm: # ->It is a Supervised Macine Learning algorithm # -> SVM offers very high accuracy as compared to other classifiers such as Logistic Regression and Decision trees # # ->It is used in variety of application such as face detection , intrusion detection, classification of emails, news and articles and webpages, classification of genes, and handwritten recognition # # ->SVM is usally considered to be a classification alogo, but it can be employed in both types of classification and regression problems. # How SVM work? # -> The main objective is to segregate the given dataset in the best possible way. # -> The objective is to select a hyperplane with the maximum possible margin between support vectors in the given dataset # Kernel Trick: # -> Linear Kernel: # K(x,xi) = sum(x*xi) # # -> Polynomial kernel: # K(x,xi) = 1+ sum(x*xi)^d # where d is the degree of polynomial # # -> Radial Basis Kernel Function: # k(x,xi) = exp(-gamma * sum((x-xi^2)) # gamma range is 0 to 1 # a higher value of Gamma results in overfitting # # # In[195]: from sklearn import datasets cancer = datasets.load_breast_cancer() # In[205]: cancer.keys() # In[208]: cancer.data[0:1].shape # In[211]: cancer.target[0:5] # In[212]: from sklearn.model_selection import train_test_split # In[213]: X_train, X_test, Y_train, Y_test = train_test_split(cancer.data, cancer.target, test_size=0.3, random_state=109) # Import SVM module and create support vector classifier object by passing argument kernel as the linear kernel in SVC() function. # In[215]: from sklearn import svm clf = svm.SVC(kernel='linear') # In[216]: clf.fit(X_train, Y_train) # In[217]: y_pred=clf.predict(X_test) # In[219]: y_pred # In[221]: from sklearn import metrics print("Accuracy:", metrics.accuracy_score(Y_test, y_pred)) # In[222]: print("Precision:", metrics.precision_score(Y_test, y_pred)) # In[223]: print("Recall:", metrics.recall_score(Y_test, y_pred))
# coding: utf-8 # # simplified Confident Learning Tutorial # *Author: Curtis G. Northcutt, [email protected]* # In this tutorial, we show how to implement confident learning without using cleanlab (for the most part). # This tutorial is to confident learning what this tutorial # https://pytorch.org/tutorials/beginner/examples_tensor/two_layer_net_numpy.html # is to deep learning. # The actual implementations in cleanlab are complex because they support parallel processing, # numerous type and input checks, lots of hyper-parameter settings, # lots of utilities to make things work smoothly for all types of inputs, and ancillary functions. # I ignore all of that here and provide you a bare-bones implementation using mostly for-loops and some numpy. # Here we'll do two simple things: # 1. Compute the confident joint which fully characterizes all label noise. '''上面这句话不理解。什么是 confident joint ? confident joint 是一个变量,通常被写作为 confident_joint Throughout these examples, you’ll see a variable called confident_joint. The confident joint is an m x m matrix (m is the number of classes) that counts, for every observed, noisy class, the number of examples that confidently belong to every latent, hidden class. It counts the number of examples that we are confident are labeled correctly or incorrectly for every pair of obseved and unobserved classes.The confident joint is an unnormalized estimate of the complete-information latent joint distribution, Ps,y. Most of the methods in the cleanlab package start by first estimating the confident_joint. ''' # 2. Find the indices of all label errors, ordered by likelihood of being an error. # ## INPUT (stuff we need beforehand): # 1. s - These are the noisy labels. This is an np.array of noisy labels, shape (n,1) # 2. psx - These are the out-of-sample holdout predicted probabilities for every example in your dataset. # This is an np.array (2d) of probabilities, shape (n, m) # ## OUTPUT (what this returns): # 1. confident_joint - an (m, m) np.array matrix characterizing all the label error counts for every pair of labels. # 一个 numpy 矩阵表征所有的标签错误数针对每对labels。 # 2. label_errors_idx - a numpy array comprised of indices of every label error, # ordered by likelihood of being a label error. # In this tutorial we use the handwritten digits dataset as an example. import cleanlab import numpy as np from sklearn.datasets import load_digits # 使用sklearn 中的数据集 from sklearn.linear_model import LogisticRegression # 导入线性回归模型 # To silence convergence warnings caused by using a weak logistic regression classifier on image data import warnings warnings.simplefilter("ignore") np.random.seed(477) # STEP 0 - Get some real digits data. Add a bunch of label errors. Get probs. # Get handwritten digits data X = load_digits()['data'] # 拿到训练数据。 这个数据的形式是二维的,是个tuple,大小为 (1797,64) # print(digits.data.shape) (1797, 64) y = load_digits()['target'] # 拿到训练数据对应的标签 print('Handwritten digits datasets number of classes:', len(np.unique(y))) print('Handwritten digits datasets number of examples:', len(y)) # Add lots of errors to labels => 这里是添加错误? NUM_ERRORS = 100 # 设置100个错误的标签 s = np.array(y) # 这步操作是干什么用? => 不想修改y,从而搞了一份一模一样的 ndarray 吗? error_indices = np.random.choice(len(s), NUM_ERRORS, replace=False) for i in error_indices: # Switch to some wrong label thats a different class # s[i] 是个标签, np.delete(range(10),s[i]) 是<class 'numpy.ndarray'> # 去掉正确的标签,然后从剩余的标签中,随机选择一个标签作为错误标签。 # np.random.choice() 随机选择一个数 wrong_label = np.random.choice(np.delete(range(10), s[i])) s[i] = wrong_label # 将标签改为错误的标签 # Confirm that we indeed added NUM_ERRORS label errors assert (len(s) - sum(s == y) == NUM_ERRORS) actual_label_errors = np.arange(len(y))[s != y] print('\nIndices of actual label errors:\n', actual_label_errors) # To keep the tutorial short, we use cleanlab to get the # out-of-sample predicted probabilities using cross-validation # with a very simple, non-optimized logistic regression classifier ''' 01.使用 cleanlab 的包 02.使用一个没有优化的逻辑回归分类器 + 交叉验证,从而获得out-of-sample predicted probabilities 03.怎么理解这个 out-of-sample ? 04.latent estimate 是什么意思? 05.最后返回的就是一个概率矩阵 psx ''' psx = cleanlab.latent_estimation.estimate_cv_predicted_probabilities(X, s, clf=LogisticRegression(max_iter=1000, multi_class='auto', solver='lbfgs') ) # Now we have our noisy labels s and predicted probabilities psx. # That's all we need for confident learning. ''' 下面就是关键,用于计算 confident_joint,也就是我不懂的地方 ''' # STEP 1 - Compute confident joint # Verify inputs # asarray() => convert an input to an array s = np.asarray(s) psx = np.asarray(psx) # Find the number of unique classes if K is not given # 很奇怪,为什么这里直接取len()?? 如果说某一类丢失了,怎么办? K = len(np.unique(s)) # Estimate the probability thresholds for confident counting # You can specify these thresholds yourself if you want # as you may want to optimize them using a validation set. # By default (and provably so) they are set to the average class prob. ''' 01.这里用到了列表生成表达式 02. ''' thresholds = [np.mean(psx[:,k][s == k]) for k in range(K)] # P(s^=k|s=k) thresholds = np.asarray(thresholds) ''' 1. 我觉得这个 confident joint 其实就是 计数矩阵 ''' # Compute confident joint confident_joint = np.zeros((K, K), dtype = int) for i, row in enumerate(psx): # 这里的row 是一个item在每个标签下的概率值 s_label = s[i] # 该item 的label # Find out how many classes each example is confidently labeled as # 找出每个example(也就是每个item)会被确切的标记为多少类 # 为什么会叫 confident_bins 这个名字? 为什么会叫confident_joint 这个名字? confident_bins = row >= thresholds - 1e-6 num_confident_bins = sum(confident_bins) # If more than one conf class, inc the count of the max prob class ''' 01.如果该item只属于一个类,则直接+=1;为什么是 np.argmax(confident_bins)??? 否则取其最大的一个+=1,也就是说相信概率大的那一个,这里又是 np.argmax(row)?? 其实不管取哪一个,都是相同的作用,为的就是找出概率最大的那个。 02. np.argmax(confident_bins) 方法的作用,见我git的学习笔记 ''' if num_confident_bins == 1: confident_joint[s_label][np.argmax(confident_bins)] += 1 elif num_confident_bins > 1: confident_joint[s_label][np.argmax(row)] += 1 # 看一下它的size print(confident_joint.size()) ''' 01.可以看到下面这个才是 normalize,也就是做一个归一化操作 ''' # Normalize confident joint (use cleanlab, trust me on this) confident_joint = cleanlab.latent_estimation.calibrate_confident_joint( confident_joint, s) cleanlab.util.print_joint_matrix(confident_joint) # STEP 2 - Find label errors # We arbitrarily choose at least 5 examples left in every class. # Regardless of whether some of them might be label errors. MIN_NUM_PER_CLASS = 5 # Leave at least MIN_NUM_PER_CLASS examples per class. # NOTE prune_count_matrix is transposed (relative to confident_joint) # 可以看到上面for 循环中是先写s[label],这个s[label]是人工标注的标签;而np.argmax(confident_bins)或者 # np.argmax(row) 则是预测标签,所以需要转置 prune_count_matrix = cleanlab.pruning.keep_at_least_n_per_class( prune_count_matrix=confident_joint.T, n=MIN_NUM_PER_CLASS, ) '''下面这部分任务我还不是很清楚 ''' s_counts = np.bincount(s) # 计算s中非负整数的个数 noise_masks_per_class = [] # For each row in the transposed confident joint for k in range(K): noise_mask = np.zeros(len(psx), dtype=bool) # 注意 mask 操作 psx_k = psx[:, k] if s_counts[k] > MIN_NUM_PER_CLASS: # Don't prune if not MIN_NUM_PER_CLASS for j in range(K): # noisy label index (k is the true label index) if k != j: # Only prune for noise rates, not diagonal entries num2prune = prune_count_matrix[k][j] if num2prune > 0: # num2prune'th largest p(classk) - p(class j) # for x with noisy label j margin = psx_k - psx[:, j] s_filter = s == j threshold = -np.partition( -margin[s_filter], num2prune - 1 )[num2prune - 1] noise_mask = noise_mask | (s_filter & (margin >= threshold)) noise_masks_per_class.append(noise_mask) else: noise_masks_per_class.append(np.zeros(len(s), dtype=bool)) # Boolean label error mask label_errors_bool = np.stack(noise_masks_per_class).any(axis=0) # Remove label errors if given label == model prediction for i, pred_label in enumerate(psx.argmax(axis=1)): # np.all let's this work for multi_label and single label if label_errors_bool[i] and np.all(pred_label == s[i]): label_errors_bool[i] = False # Convert boolean mask to an ordered list of indices for label errors label_errors_idx = np.arange(len(s))[label_errors_bool] # self confidence is the holdout probability that an example # belongs to its given class label self_confidence = np.array( [np.mean(psx[i][s[i]]) for i in label_errors_idx] ) margin = self_confidence - psx[label_errors_bool].max(axis=1) label_errors_idx = label_errors_idx[np.argsort(margin)] print('Indices of label errors found by confident learning:') print('Note label errors are sorted by likelihood of being an error') print('but here we just sort them by index for comparison with above.') print(np.array(sorted(label_errors_idx))) # In[5]: score = sum([e in label_errors_idx for e in actual_label_errors]) / NUM_ERRORS print('% actual errors that confident learning found: {:.0%}'.format(score)) score = sum([e in actual_label_errors for e in label_errors_idx]) / len(label_errors_idx) print('% confident learning errors that are actual errors: {:.0%}'.format(score))
# Author: Michael R.Sorell # Fundamentals of Computing: Interactive Programming (Part 1) # 8 November 2018 # template for "Stopwatch: The Game" import simplegui import random # define global variables count_message = "" position = [250,250] width= 500 height= 500 interval = 100 # program 100 counter=0 y=0 x=0 ms = 0 sw_run= True # define helper function format that converts time # in tenths of seconds into formatted string A:BC.D def format(t): global counter, count, count_message,check_minutes, ms count= int(counter) s = (count/10)%60 m= count/600 ms= count - (s*10)-(600*m) minutes=str(m) milliseconds=str(ms) if s < 10: sa= str(s) sb= "0" seconds = sb+sa else: seconds=str(s) count_message = minutes + ':' + seconds + '.' + milliseconds return count_message # define event handlers for buttons; "Start", "Stop", "Reset" def start(): global counter, sw_run timer.start() sw_run= True def stop(): global y, x, counter, sw_run timer.stop() if (sw_run == True): y=y+1 if (counter%10)== 0: x=x+1 sw_run= False def reset(): global counter, y, x timer.stop() counter = 0 y = 0 x = 0 sw_run = True # define event handler for timer with 0.1 sec interval def tick(): global counter,y start() counter +=1 #print counter # define draw handler def draw(canvas): global counter, count_message, y,x t= counter tries=str(y) hits = str(x) history= hits + '/' + tries stopwatch=format(t) canvas.draw_text(stopwatch, position, 48, "white") canvas.draw_text(history, [450,35], 24, "red") # create frame frame = simplegui.create_frame("Home", width, height) # register event handlers timer = simplegui.create_timer(interval, tick) frame.set_draw_handler(draw) frame.add_button("Start", start, 200) frame.add_button("Stop", stop, 200) frame.add_button("Reset", reset, 200) # start frame frame.start() # Please remember to review the grading rubric
from individual import Individual from fitnesscalculator import FitnessCalculator class Population: fit = FitnessCalculator() def __init__(self, populationSize = 30, initialize = True): self.individuals = [] if initialize: for i in xrange(populationSize): self.individuals += [Individual()] def size(self): return len(self.individuals) def addIndividual(self, ind): self.individuals += [ind] def getFittest(self): result = self.individuals[0] maxFit = Population.fit.getFitness(result) for ind in self.individuals: newFit = Population.fit.getFitness(ind) if maxFit > newFit: result = ind maxFit = newFit return result def averageFitness(self): result = 0.0 for ind in self.individuals: result += Population.fit.getFitness(ind) return result / len(self.individuals) def __str__(self): #for ind in self.individuals: # print str(ind) + " " + str(Population.fit.getFitness(ind)) #return "Pop size: " + str(len(self.individuals)) return "" if __name__ == "__main__": pop = Population() print pop
# ---------------------------------------------------------------------------- # # Title: Assignment 07 # Description: This program demonstrates the concepts of error # handling and pickling. The user will be presented # a menu with 3 options: (1) Error Handling Demo; # (2) Pickling Demo; (3) Exit Program. # ChangeLog (Who,When,What): # Chris Messmann,11/29/20,Created started script # Chris Messmann,12/1/20, Finished error handling and pickling demo # ---------------------------------------------------------------------------- # # Data ---------------------------------------------------------------------- # # Declare variables and constants strChoice = "" # Captures the user option selection strerror_handling_selection = "" # Captures the user error_handling_selection data strPriority = "" # Captures the user priority data strStatus = "" # Captures the status of an processing functions Strvalue = "" # Captures users value in error handling demo 1 StrFile = "" # Placeholder for user entered file name in error handling demo 2 Strdata = "" # Placeholder for data sent to pickle processing functions Strnumberdata = "" # Placeholder for the number of items being loaded into pickle dump item = "" # Used in the counter in the pickle dump demo # Processing --------------------------------------------------------------- # class Processor: """ Performs Processing error_handling_selections """ @staticmethod def error_processing_demo1(value): try: quotient = value / 0 print(quotient) except: print("You can't divide by 0") @staticmethod def error_processing_demo2(unavailable_file): try: open(unavailable_file) except IOError as e: print(e, e.__doc__, sep='\n') @staticmethod def pickle_load_processing(): # open a file, where you stored the pickled data file = open('pickle_file', 'rb') # dump information to that file data = pickle.load(file) # close the file file.close() return data # Presentation (Input/Output) -------------------------------------------- # class IO: """ Performs Input and Output error_handling_selections """ @staticmethod def print_menu_error_handling_selections(): """ Display a menu of choices to the user :return: nothing """ print(''' Menu of Options 1) Run Error Handling Demo 2) Run Pickling Demo 3) Exit Program ''') print() # Add an extra line for looks @staticmethod def input_menu_choice(): """ Gets the menu choice from a user :return: string """ try: choice = str(input("Which option would you like to perform? [1 to 3] - ")).strip() print() # Add an extra line for looks except Exception as e: print("That choice is out of range") return choice @staticmethod def input_press_to_continue(optional_message=''): """ Pause program and show a message before continuing :param optional_message: An optional message you want to display :return: nothing """ print(optional_message) input('Press the [Enter] key to continue.') @staticmethod def error_handling_demo1(): print("We're going to demo how structured error handling works.") print("Python has a variety of ways it responds to errors by utilizing 'try-except' blocks.") print("The first example will demo a custom 'user friendly' try-except response. ") value = input("Enter a number and I will try and divide it by 0: ") return value @staticmethod def error_handling_demo2(): print("Python has pre-built in try-except blocks for commonly occurring errors") print("This second example will demo an already built in try-except response to an IO Error.") print() unavailable_file = input("Type in any file name and I will try to open it: ") return unavailable_file @staticmethod def pickle_dump_demo(): print("Data can be saved in binary format instead of just 'plain' text. In Python, this") print("technique is called pickling. Storing data in a binary format can obscure the file's") print("content and may reduce the file's size.") print("This demo will explore how pickling works as an alternative to saving a text doc.") import pickle # take user input to take the amount of data number_data = int(input('Enter the number of data : ')) data = [] #take input of the data for i in range(number_data): raw = input('Enter data ' + str(i) + ' : ') data.append(raw) # open a file and dump the data file = open('pickle_file', 'wb') pickle.dump(data, file) file.close() # open a file, and load the data file = open('pickle_file', 'rb') data = pickle.load(file) file.close() print('Showing the pickled data:') cnt = 0 for item in data: print('The data ', cnt, ' is : ', item) cnt += 1 # Main Body of Script ------------------------------------------------------ # while (True): # Step 1 - Display a menu of choices to the user IO.print_menu_error_handling_selections() # Shows menu strChoice = IO.input_menu_choice() # Get menu option # Step 2 - Process user's menu choice if strChoice.strip() == '1': # Run error handling demo Strvalue = IO.error_handling_demo1() Processor.error_processing_demo1(Strvalue) IO.input_press_to_continue(strStatus) StrFile = IO.error_handling_demo2() Processor.error_processing_demo2(StrFile) IO.input_press_to_continue(strStatus) continue # to show the menu elif strChoice == '2': # Run pickling demo Strdata = IO.pickle_dump_demo() IO.input_press_to_continue(strStatus) continue # to show the menu elif strChoice == '3': # Exit Program print("Goodbye!") input("Enter to Exit", ) break # and Exit
# -------------- # User Instructions # # Write a function, inverse, which takes as input a monotonically # increasing (always increasing) function that is defined on the # non-negative numbers. The runtime of your program should be # proportional to the LOGARITHM of the input. You may want to # do some research into binary search and Newton's method to # help you out. # # This function should return another function which computes the # inverse of the input function. # # Your inverse function should also take an optional parameter, # delta, as input so that the computed value of the inverse will # be within delta of the true value. # ------------- # Grading Notes # # Your function will be called with three test cases. The # input numbers will be large enough that your submission # will only terminate in the allotted time if it is # efficient enough. def slow_inverse(f, delta=1/128.): """Given a function y = f(x) that is a monotonically increasing function on non-negatve numbers, return the function x = f_1(y) that is an approximate inverse, picking the closest value to the inverse, within delta.""" def f_1(y): x = 0 while f(x) < y: x += delta # Now x is too big, x-delta is too small; pick the closest to y return x if (f(x)-y < y-f(x-delta)) else x-delta return f_1 def inverse(f, delta=1/128.): """Given a function y = f(x) that is a monotonically increasing function on non-negatve numbers, return the function x = f_1(y) that is an approximate inverse, picking the closest value to the inverse, within delta.""" def fn(y): lo, hi = find_bound(f, y) return bin_search(f, y, lo, hi, delta) return fn def find_bound(f, y): x = 1. while f(x) < y: x = x*2 lo = 0. if x == 1 else x/2. return lo, x def bin_search(f, y, low, high, delta): while low <= high: x = (low+high)/2. if f(x) < y: low = x + delta elif f(x) > y: high = x - delta else: return x return high if f(high)-y < y-f(low) else low def square(x): return x*x sqrt = slow_inverse(square) print(sqrt(1000000000))