text
stringlengths
37
1.41M
# num=int(input("enter the year")) # if num%4==0: # print("leap year") # else: # print(" It is not leap year")
# # calculator # num1=int(input("enter the num1 ")) # num2=int(input("enter the num2 ")) # operator=input("enter the operator") # if operator == "+": # print(num1+num2) # elif operator == "-": # print(num1-num2) # elif operator == '/': # print(num1/num2) # elif operator == '*': # print(num1*num2) # elif operator == '%': # print(num1%num2) # elif operator == '**': # print(num1**num2) # elif operator == '//': # print(num1//num2) # else: # print("nothing")
# ***isosceles,equirlateral,scalence*** # n=input("enter the degrees ") # a=int(input("a: ")); # b=int(input("b: ")) # c=int(input("c: ")); # if a==b and b==c: # print("is equirlateral triangle") # elif a==b or b==c or c==a: # print("is isosceles triangle") # # elif a!=b or b!=a or b!=c: # else: # print("is scalene triangle") #*** 3 triangle****
# *** creates 9x9 board (valid input for _main_file.solve()) from some of data below (below the getch() method) def create_sudoku(inp): row = 0; col = 0; outp = [[0] * 9 for _ in range(9)] for letter in inp.replace('.', '0'): a = ord(letter) if a >= 48 and a <= 57: # if letter is in between '0' and '9' outp[row][col] = a - 48; col += 1 # save int(letter) here and continue to next field if col == 9: col = 0; row += 1 # next line return outp # *** more optimalised version of previous def get_sudoku(whichgroup, number = 0): # for these simple reduce was enough if whichgroup == 'easy': if number == 0: return create_sudoku(sud_0_a) if number == 1: return create_sudoku(sud_0_b) if number == 2: return create_sudoku(sud_0_c) if number == 3: return create_sudoku(sud_0_d) if number == 4: return create_sudoku(sud_1_a) if number == 5: return create_sudoku(sud_1_b) if number == 6: return create_sudoku(sud_1_c) if number == 7: return create_sudoku(sud_1_d) if number == 8: return create_sudoku(sud_2_c) if number == 9: return create_sudoku(sud_2_d) # naked pairs solved those if whichgroup == 'medium': if number == 0: return create_sudoku(sud_2_a) if number == 1: return create_sudoku(sud_2_b) if number == 2: return create_sudoku(sud_b) if number == 3: return create_sudoku(sud_e) if number == 4: return create_sudoku(sud_h) # stubborn ones if whichgroup == 'hard': if number == 0: return create_sudoku(sud_a) if number == 1: return create_sudoku(sud_c) if number == 2: return create_sudoku(sud_d) if number == 3: return create_sudoku(sud_f) if number == 4: return create_sudoku(sud_g) if number == 5: return create_sudoku(sud_i) if number == 6: return create_sudoku(sud_j) # methods examples - not valid sudoku if whichgroup == 'methods': if number == 0: return create_sudoku(sud_hidden_pairs_a) if number == 1: return create_sudoku(sud_hidden_pairs_b) if number == 2: return create_sudoku(sud_hidden_triples) if number == 3: return create_sudoku(sud_pointing_pair) if number == 4: return create_sudoku(sud_pointing_triple) if number == 5: return create_sudoku(sud_naked_triple) if number == 6: return create_sudoku(sud_naked_triple2) if whichgroup == 'crazy': if number == 0: return create_sudoku(sud_crazy1) if number == 1: return create_sudoku(sud_crazy2) if number == 2: return create_sudoku(sud_crazy3b) if number == 3: return create_sudoku(sud_crazy3) if number == 4: return create_sudoku(sud_crazy4) if number == 5: return create_sudoku(sud_crazy5) if number == 6: return create_sudoku(sud_crazy6) if number == 7: return create_sudoku(sud_crazy0) if whichgroup == 'problem': return problem if whichgroup == 'problem2': return problem2 if whichgroup == 'solution': return solution if whichgroup == 'solution2': return solution2 return True def get_all_valid_sudokus(): out = [] for i in range(10): out += [get_sudoku('easy', i)] for i in range(5): out += [get_sudoku('medium', i)] for i in range(7): out += [get_sudoku('hard', i)] out += [get_sudoku('problem2')] out += [get_sudoku('problem')] return out # ******************* BUNCH OF SUDOKU'S for testing *********************** # *** (official problem from codewars) *** problem = [[9, 0, 0, 0, 8, 0, 0, 0, 1], [0, 0, 0, 4, 0, 6, 0, 0, 0], [0, 0, 5, 0, 7, 0, 3, 0, 0], [0, 6, 0, 0, 0, 0, 0, 4, 0], [4, 0, 1, 0, 6, 0, 5, 0, 8], [0, 9, 0, 0, 0, 0, 0, 2, 0], [0, 0, 7, 0, 3, 0, 2, 0, 0], [0, 0, 0, 7, 0, 5, 0, 0, 0], [1, 0, 0, 0, 4, 0, 0, 0, 7]] solution = [[9, 2, 6, 5, 8, 3, 4, 7, 1], [7, 1, 3, 4, 2, 6, 9, 8, 5], [8, 4, 5, 9, 7, 1, 3, 6, 2], [3, 6, 2, 8, 5, 7, 1, 4, 9], [4, 7, 1, 2, 6, 9, 5, 3, 8], [5, 9, 8, 3, 1, 4, 7, 2, 6], [6, 5, 7, 1, 3, 8, 2, 9, 4], [2, 8, 4, 7, 9, 5, 6, 1, 3], [1, 3, 9, 6, 4, 2, 8, 5, 7]] problem2 = [[7, 0, 5, 6, 2, 0, 8, 0, 0], [0, 2, 0, 8, 0, 9, 0, 7, 5], [3, 0, 8, 7, 4, 5, 0, 2, 1], [5, 3, 0, 2, 0, 6, 0, 1, 0], [0, 0, 2, 0, 0, 0, 5, 0, 0], [0, 7, 0, 5, 0, 4, 0, 6, 2], [2, 5, 0, 0, 6, 7, 0, 8, 4], [0, 8, 0, 4, 5, 2, 0, 9, 0], [0, 0, 7, 0, 0, 0, 2, 5, 0]] solution2 = [[7, 1, 5, 6, 2, 3, 8, 4, 9], [6, 2, 4, 8, 1, 9, 3, 7, 5], [3, 9, 8, 7, 4, 5, 6, 2, 1], [5, 3, 9, 2, 7, 6, 4, 1, 8], [4, 6, 2, 1, 9, 8, 5, 3, 7], [8, 7, 1, 5, 3, 4, 9, 6, 2], [2, 5, 3, 9, 6, 7, 1, 8, 4], [1, 8, 6, 4, 5, 2, 7, 9, 3], [9, 4, 7, 3, 8, 1, 2, 5, 6]] problem_modified = [[0, 0, 0, 0, 8, 0, 0, 0, 1], [0, 0, 0, 4, 0, 6, 0, 0, 0], [0, 0, 5, 0, 7, 0, 3, 0, 0], [0, 6, 0, 0, 0, 0, 0, 4, 0], [4, 0, 1, 0, 6, 0, 5, 0, 8], [0, 9, 0, 0, 0, 0, 0, 2, 0], [0, 0, 7, 0, 3, 0, 2, 0, 0], [0, 0, 0, 7, 0, 5, 0, 0, 0], [1, 0, 0, 0, 4, 0, 0, 0, 7]] # *** (cut'n'paste from sudoku book-to-solve) *** #very easy sud_0_a = ''' ...2.6.3. 73...8... ..5...689 ....8.29. .634.981. .59.1.... 382...1.. ...8...26 .9.5.4...X''' sud_0_b = ''' ..42....5 6.79..4.2 .318.5... .7..5...9 .83...14. 4...6..7. ...5.493. 9.5..72.1 3....27..X''' sud_0_c = ''' 3.85..... .4.....52 52.361... ..3.5.86. .1.627.4. .54.1.7.. ...174.36 76.....8. .....61.5X''' sud_0_d = ''' 26.4..... ....6.8.9 19.8....5 5.1.93.6. .27.1.98. .3.68.5.7 8....5.32 3.4.7.... .....6.58X''' #easy sud_1_a = ''' 4.61..27. ...6.9.4. 7.38..16. ......617 ....9.... 538...... .75..64.2 .8.4.3... .41..73.6X''' sud_1_b = ''' .1.26.... ...9.5.21 ..9...57. 2...71..4 3...8...5 6..52...3 .65...8.. 98.6.2... ....14.5.X''' sud_1_c = ''' 7.2.35.1. ...14..5. 15.....7. 2.59.1... ..6...9.. ...3.47.5 .6.....38 .2..73... .9.62.5.7X''' sud_1_d = ''' 54....... 239..4..5 .....5.23 ..374.8.1 ..2.1.5.. 4.1.862.. 81.6..... 9..8..362 .......58X''' #medium sud_2_a = ''' .7....296 ..16....7 ..9.2.... ...1.3.2. 35..7..81 .8.5.6... ....9.3.. 7....54.. 436....5.X''' sud_2_b = ''' ...13...4 .24...... .7..9..16 ...3.61.2 ..2.7.3.. 4.72.9... 39..8..6. ......89. 2...63...X''' sud_2_c = ''' ..85...94 3.5...... ...81.53. ...3..648 ....7.... 984..2... .93.67... ......1.6 67...59..X''' sud_2_d = ''' ..8...92. ...169.3. .39....1. 5....7..9 ...8.1... 4..3....1 .7....49. .4.925... .13...5..X''' #hard sud_a = ''' .98..2... .....5..4 ..3.7...6 ....3.64. .26...98. .49.2.... 1...6.4.. 5..9..... ...7..23.X''' sud_b = ''' ..1...7.6 9.5..1... ..65.2... 57..9.... 2.......9 ....4..85 ...3.54.. ...8..5.7 1.9...2..X''' sud_c = ''' 5.1....3. ...4.9... ..68...5. 6...3...7 ..9.2.8.. 3...9...6 .3...12.. ...9.7... .1....4.8X''' sud_d = ''' .3.295... 95.7..... ......45. ...4..9.. 6.1...3.2 ..2..1... .28...... .....4.25 ...312.7.X''' sud_e = ''' 1..2..... .2.5.4..8 .8......1 ....4.892 ..2...7.. 843.2.... 7......5. 5..4.9.7. .....5..6X''' sud_f = ''' ...24...7 4.5.....3 ...9..2.4 .7.....2. ...391... .3.....9. 2.7..5... 3.....4.6 9...16...X''' sud_g = ''' ...38.... ..2....6. ..6...874 ..763...8 9.......5 6...912.. 385...7.. .7....4.. ....29...X''' sud_h = ''' .5.....46 6..7...8. .79.1.... ..437.... ..1...4.. ....415.. ....3.69. .3...6..5 74.....3.X''' sud_i = ''' ....19... 9.....28. 37.....4. ..73.1... 5.1...7.9 ...9.21.. .3.....95 .62.....7 ...68....X''' sud_j = ''' .54.3.... .9..46... .......18 ...3.46.. 7.6...1.9 ..89.1... 13....... ...21..7. ....5.26.X''' # *** cut'n'paste from sudokuwiki.org *** # *** they are good for testing (debugging) specific elimination method *** # *** all of (or maybe nearly all of) them are not valid *** sud_hidden_pairs_a = ''' ......... 9.46.7... .768.41.. 3.97.1.8. 7.8...3.1 .513.87.2 ..75.261. ..54.32.8 .........X''' sud_hidden_pairs_b = ''' 72.4.8.3. .8.....47 4.1.768.2 81.739... ...851... ...264.8. 2.968.413 34......8 168943275X''' sud_hidden_triples = ''' .....1.3. 231.9.... .65..31.. 6789243.. 1.3.5...6 ...1367.. ..936.57. ..6.19843 3........X''' sud_pointing_pair = ''' .179.36.. ....8.... 9.....5.7 .72.1.43. ...4.2.7. .6437.25. 7.1....65 ....3.... .56.1.72.X''' sud_pointing_triple = ''' 93..5.... 2..63..95 856..2... ..318.57. ..5.2.98. .8...5... ...8..159 5.821...4 ...56...8X''' sud_naked_triple = ''' .7.4.8.29 ..2.....4 854.2...7 ..83742.. .2....... ..32617.. ....93612 2.....4.3 12.642.7.X''' sud_naked_triple2 = ''' 294513..6 6..842319 3..697254 ....56... .4..8..6. ...47.... 73.164..5 9..735..1 4..928637X''' #possibly wrong sudoku, '2' added at [0][5] for box line test being possible sud_box_line_a = ''' .16..78.3 .9.8..... 87...1.6. .48...3.. 65...9.82 239...65. .6.9...2. .8...2936 9246..51.X''' sud_box_line_b = ''' .2.943715 9.4...6.. 75.....4. 5..48.... 2.....453 4..352... .42....81 ..5..426. .9.2.85.4X''' # almost unfilled sudokus sud_crazy0 = ''' ......... ......... ......... ......... ......... ......... ......... ......... .........X''' sud_crazy1 = ''' 1........ .2....... ..3...... ...4..... ....5.... .....6... ......7.. ......28. ........9X''' sud_crazy2 = ''' 1........ .2....... ..3...... ...4..... ....5.... .....6... ......7.. .......8. ........9X''' sud_crazy3 = ''' 12....... ..34..... ......... ......... ......... ......... ......... ......... .........X''' sud_crazy3b = ''' 12..56... ..34..78. ......... ......... ......... ......... ......... ......... .........X''' sud_crazy4 = ''' ......... ......... .....3... ......... ......... ......... ..5..7... ......... .........X''' sud_crazy5 = ''' ......... .6....... ......... ......... ......... ......... ........9 ......... .........X''' sud_crazy6 = ''' ......... ......... ......... ......... ....5.... ......... ......... ......... .........X'''
from tkinter import * import math from random import randint,choice #Подготовка окна root = Tk() fr = Frame(root) root.title("easySpace") root.geometry("1366x768") canv = Canvas(root, bg='black') canv.pack(fill = BOTH, expand = 1) #Интерфейс пользователя class UI(): def __init__(self): self #""" Здесь описаны методы отрисовки планет """ #Необходимо переделать расположение планет и метод задания координат планет, для их перемещения def SKY():# Генератор звездного неба for i in range(2000) : coord_x = randint(0,1366)# Выборка координаты x coord_y = randint(0,768)# Выборка координаты y r = randint(1,3)# Выборка радиуса звезды color = choice(['white','#AFDAFC','#FB607F']) canv.create_oval(coord_x-r,coord_y-r, coord_x+r, coord_y+r, fill = color ) #Рисует овал, в случайной позиции def Sun():#Солнце canv.create_oval(583,200,783,400, fill = 'orange', outline = 'red' ) def Mercury(event):#Меркурий canv.create_oval(1000,400,1020,420, fill = 'red', outline = 'yellow') def Venera(event):#Венера canv.create_oval(1040,420,1080, 460, fill = 'orange', outline = 'yellow') def Earth(event):#Земля canv.create_oval(1050,430,1090,470, fill = 'blue', outline = 'green') def Mars(event):#Марс canv.create_oval(1050,430,1090,470, fill = 'red', outline = 'red') def Yupiter(event):#Юпитер canv.create_oval(10,100,30,120, fill = 'red', outline = 'white') canv.create_oval(11,101,16,106, fill = 'grey', outline = 'red') def Saturn(event):#Сатурн canv.create_oval(100,100,200,200, fill = '#F0D698', outline = 'grey') def Uran(event):#Уран canv.create_oval(100,100,200,200, fill = '#87CEEB', outline = 'blue') def Neptun(event):#Нептун canv.create_oval(400,100,500,200, fill = '#4169E1', outline = 'grey') #""" Здесь описаны методы отрисовки и логики при нажатии на клавиши """ def Card_Mercury():#Кнопка Меркурия #Рисует карточку-кнопку с инфой по Меркурию button_merc =Button(root, width = 10, height = 2, bg ='grey',text = 'Меркурий') #Нажатие на кнопку ЛКМ button_merc.bind("<Button-1>", UI.Mercury ) button_merc.pack(side = 'left',fill = 'both', expand = True) def Card_Venera():#Кнопка Венеры button_ven = Button(root , width = 10, height = 2, bg ='grey', text = 'Венера') button_ven.bind("<Button-1>", UI.Venera ) button_ven.pack(side = 'left',fill = 'both', expand = True) def Card_Eath():#Кнопка Земли button_earth = Button(root , width = 10, height = 2, bg ='grey', text = 'Земля') button_earth.bind("<Button-1>", UI.Earth ) button_earth.pack(side = 'left',fill = 'both', expand = True) def Card_Mars():#Кнопка Марса button_mars = Button(root , width = 10, height = 2, bg ='grey', text = 'Марс') button_mars.bind("<Button-1>", UI.Mars ) button_mars.pack(side = 'left',fill = 'both', expand = True) def Card_Yupiter():#Кнопка Юпитера button_yup = Button(root , width = 10, height = 2, bg ='grey', text = 'Юпитер') button_yup.bind("<Button-1>", UI.Yupiter ) button_yup.pack(side = 'left',fill = 'both', expand = True) def Card_Saturn():#Кнопка Юпитера button_sat = Button(root , width = 10, height = 2, bg ='grey', text = 'Сатурн') button_sat.bind("<Button-1>", UI.Saturn ) button_sat.pack(side = 'left',fill = 'both', expand = True) def Card_Uran():#Кнопка Урана button_ur = Button(root , width = 10, height = 2, bg ='grey', text = 'Уран') button_ur.bind("<Button-1>", UI.Uran ) button_ur.pack(side = 'left',fill = 'both', expand = True) def Card_Neptun():#Кнопка Нептуна button_nep = Button(root , width = 10, height = 2, bg ='grey', text = 'Нептун') button_nep.bind("<Button-1>", UI.Neptun ) button_nep.pack(side = 'left',fill = 'both', expand = True) # Здесь будет движение планет # Здесь будет вывод текста при нажатии на клавишу (модет и не будет, не решил пока) #Здесь хрень для улучшения графики(может тоже не будет, хз вообще) #Вызов методов UI.SKY() UI.Sun() UI.Card_Mercury() UI.Card_Venera() UI.Card_Eath() UI.Card_Mars() UI.Card_Yupiter() UI.Card_Saturn() UI.Card_Uran() UI.Card_Neptun() root.mainloop()
# Status: Probably works. Demo. # After you put an image with some shapes in image.jpg, it will find # contours and display their outlines and centers. Pretty much just # http://www.pyimagesearch.com/2016/02/01/opencv-center-of-contour/ import imutils import cv2 image = cv2.imread('image.jpg') gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) blurred = cv2.GaussianBlur(gray, (5, 5), 0) thresh = cv2.threshold(blurred, 60, 255, cv2.THRESH_BINARY)[1] # find contours in the thresholded image cnts = cv2.findContours(thresh.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) cnts = cnts[0] if imutils.is_cv2() else cnts[1] # loop over the contours for c in cnts: # compute the center of the contour if cv2.contourArea(c) > 0: M = cv2.moments(c) cX = int(M["m10"] / M["m00"]) cY = int(M["m01"] / M["m00"]) # draw the contour and center of the shape on the image cv2.drawContours(image, [c], -1, (0, 255, 0), 2) cv2.circle(image, (cX, cY), 7, (255, 255, 255), -1) cv2.putText(image, "center", (cX - 20, cY - 20), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 255, 255), 2) # show the image cv2.imshow("Image", image) cv2.waitKey(0) # # cv2.imshow('image',image) # cv2.imshow('blurred',blurred) # cv2.imshow('thresh',thresh) # cv2.waitKey(0) # cv2.destroyAllWindows()
# Unnar Sigurðsson # Movement function def movement(a_str): return a_str # Movement_input function def movement_input(): a_str = str(input("Direction: ")) return a_str # Tiles def tiletraveller(blabla): #Tiles a = "nN" b = "nN" c = "nN" d = "nNsSeE" e = "sSwW" f = "nNsS" g = "sSeE" h = "aAwW" i = "sSwW" if a.count(blabla) >= 1: return blabla else: print("Vitlaust") return 0 # ef a_str er n, þá má fara áfram, en þá þarf ég að halda utan um # Avalible Tiles a_str = "n" a_input = movement_input() print(a_input) print(tiletraveller(a_input)) #print(movement(a_str))
import unittest # 求和 def add(x, y): return x + y class TestAdd(unittest.TestCase): def test_add_01(self): result = add(1, 1) self.assertEqual(result, 2) def test_add_02(self): result = add(1, 0) self.assertEqual(result, 1) def test_add_03(self): result = add(0, 0) self.assertEqual(result, 0) def test_add(self): test_data = [(1, 1, 2), (1, 0, 1), (0, 0, 0)] for x, y, expect in test_data: print("x={} y={} expect={}".format(x, y, expect)) result = add(x, y) self.assertEqual(result, expect)
def multiply(x, y): result = x * y return result answer = multiply(10.5, 4) print(answer) forty_two = multiply(6, 7) print(forty_two) print('-' * 80) for val in range(1, 5): two_times = multiply(2, val) print(two_times) print('-' * 80)
import time # Interview question at Radband October 2018 # Problem description (aproximately): design a scheduler that receive at init time several event and their frequencies. # When started, the scheduler begin triggering the events respecting their frequencies class Node: def __init__(self, val, freq): self.val = val self.freq = freq self.delta = freq class Scheduler: def __init__(self): self.l = [] def put(self, val, freq): n = Node(val, freq) pre = 0 i = 0 after = False for i in range(len(self.l)): tmp = pre + self.l[i].delta if tmp < freq: pre = tmp after = True elif tmp == freq: after = True break else: after = False break if pre != 0: n.delta = n.freq - pre k = i + 1 if after == True else i self.l.insert(k, n) for j in range(k + 1, len(self.l)): self.l[j].delta -= n.delta def run(self): now = 0 while True: tm = self.l[0].delta time.sleep(tm) now += tm bucket = [] while len(self.l) > 0 and tm == self.l[0].delta \ and (now % self.l[0].freq) == 0: n = self.l.pop(0) bucket.append(n) while len(bucket) > 0: n = bucket.pop(0) print('%d: %s' % (now, str(n.val))) self.put(n.val, n.freq) print('------------------------------') s = Scheduler() s.put('a', 2) s.put('b', 3) s.run()
# input: 13 -> 1101 -> {11}{01} -> 1110 -> output: 14 # input: 74 -> 01001010 -> {01}{00}{10}{10} -> 10000101 -> output: 133 def swapAdjacentBits(n): return int("".join(["".join(i) for i in zip("{0:032b}".format(n)[1::2], "{0:032b}".format(n)[::2])]), 2) def swapAdjacentBits2(n): return ((n & 0xaaaaaaaa) >> 1) | ((n & 0x55555555) << 1) # ===>>> # arr = zip(arr[::2], arr[1::2]) # arr_sole_reverse = zip(arr[1::2], arr[::2]) # `"{0:032b}".format(n)` || bin(50)[2:] :convert number to binary 32 bit. # `int("00000000000000000000000000001110", 2)` convert binary to number # Đếm bit len của một số: n.bit_length()
from collections import deque """ de = collections.deque([1,2,3]) de.append(4) de.appendleft(6) de.pop() de.popleft() de.index(4,2,5) # The number 4 first occurs at a position ? from 2 to 5 de.insert(4,3) # insert the value 3 at 5th position de.count(3) # The count of 3 in deque is ... de.remove(3) # remove the first occurrence of 3 de.extend([4,5,6]) de.extendleft([7,8,9]) de.reverse() de.rotate(-3) # xoay theo số truyền vào, nếu số là âm thì xoay 3 phần tử đầu tiên, số dương thì xoay 3 phần tử cuối cùng """ def doodled_password(digits): n = len(digits) res = [deque(digits) for _ in range(n)] deque(map(lambda i: res[i].rotate(n-i), range(n)), 0) return [list(d) for d in res] print(doodled_password([1, 2, 3, 4, 5]))
class Item: """ This is a class to represent an online sold item. Attributes ---------- category: str Item's category. name: str Item's name. code: str Item's unique code. price: str Item's price in brazilian currency (BRL). details: str Item's long description. """ def __init__(self, category, name, code, price, details): self.category = category self.name = name self.code = code self.price = price self.details = details def __str__(self): return self.category + ";" + self.name + ";" + self.code + ";" + \ self.price + ";" + self.details def __eq__(self, other): if type(other) is type(self): return self.code == other.code else: return False def __hash__(self): return self.code
import random #import the random function in order to randomly select a number, which is used later on in the function import pygame #This game sets the size of the pygame display, and titles the name of the pygame window as Magnet Monopoly pygame.init() display_width= 880 display_height= 600 gameDisplay = pygame.display.set_mode((display_width,display_height)) pygame.display.set_caption('Magnet Monopoly') #Sets our created monopoly board as the background image and displays it BackgroundIMG = pygame.image.load("monopolyboard.png") gameDisplay.blit(BackgroundIMG, (0,0)) #Downloads the image of our board pieces, a hat and car, and puts them into the file hatIMG = pygame.image.load("hat.png") carIMG = pygame.image.load("car.png") #this function gives the instructions on how to play Monopoly def instructions(): """This function gives the user instructions on how to play Magnet Monopoly""" print("Welcome to Magnet Monopoly! This is a 2 person game of monopoly, where the board is all Magnet themed! Like regular monopoly, you land on different properties, buy them or pay rent if they are already owned, and build houses and hotels on them if you all the properties of a given color set. There is no trading, and the moment one of you has no money, the game ends. You each start with 1500 dollars, so spend your money wisely, and good luck!") print("") return instructions() #this calls on the instructions function #this is a class that has defines all of the spaces on the board, including how much they cost, how much each house costs, how much to pay for a given number of houses if someone lands on the space, determining who is the owner of that space, and figuring out their coordinates in the pygame window. class board_pieces: def __init__(self, name, owner, color, purchase_price, house_price, rent_price, house_1price, house_2price, house3_price, house4_price, hotel_price, location, house_owner, house_2count, house_count, hotel_owner,stationcount1, stationcount2, car_coodinates, hat_coordinates): self.name = name self.owner= owner self.color = color self.purchase_price = purchase_price self.house_price = house_price self.rent_price = rent_price self.house_1price = house_1price self.house_2price = house_2price self.house3_price = house3_price self.house4_price = house4_price self.hotel_price= hotel_price self.location = location self.house_owner = house_owner self.house_2count = house_2count self.house_count = house_count self.hotel_owner = hotel_owner self.stationcount1 = stationcount1 self.stationcount2 = stationcount2 self.car_coordinates = car_coodinates self.hat_coordinates = hat_coordinates Go= board_pieces('Go', 'N/A', 'N/A', 'N/A', 'N/A', 'N/A', 'N/A', 'N/A', 'N/A', 'N/A', 'N/A',0, 0 , 0, 0 , 'none',0,0,(750,520), (750,520)) Pinto= board_pieces('Pinto', 'none', 'purple', 60,50, 2, 10,30,90,160,250,1, 'none', 0 , 0, 'none',0,0,(650, 520), (670, 520)) Chance1= board_pieces('Chance', 'Chance', 'N/A', 'N/A', 'N/A', 'N/A', 'N/A', 'N/A', 'N/A', 'N/A', 'N/A', 2, 0 , 0 ,0, 'none',0 ,0, (580, 520), (600, 520)) Arnold= board_pieces('Arnold', 'none', 'purple',60,50,4,20,60,180,320,450, 3, 'none', 0 , 0, 'none',0,0, (510, 520), (530, 520)) Tax1= board_pieces('Tax', 'Tax', 'N/A', 'N/A', 'N/A', 'N/A', 'N/A', 'N/A', 'N/A', 'N/A', 'N/A', 4, 'none',0 ,0 , 'none',0,0, (440, 520), (460, 520)) MakerSpaceStation= board_pieces('MakerSpace Station', "station", 'black', 200, 25 , 25, 'N/A', 'N/A', 'N/A', 'N/A', 'N/A', 5, 'none', 0 , 0, 'none',0,0, (370, 520), (390, 520)) Raite= board_pieces('Raite', 'none', 'light blue', 100,50,6,30,90,270,400,550,6, 'none', 0 , 0, 'none',0,0, (300, 520), (320, 520)) Chance2= board_pieces('Chance', 'Chance', 'N/A', 'N/A', 'N/A', 'N/A', 'N/A', 'N/A', 'N/A', 'N/A', 'N/A', 7, 'none', 0 ,0 , 'none',0,0, (230, 520), (250, 520)) Gupta= board_pieces('Gupta', 'none', 'light blue',100,50,6,30,90,270,400,550,8, 'none',0 , 0, 'none',0,0, (160, 520), (180, 520)) Wickerhauser= board_pieces('Wickerhauser', 'none', 'light blue',120,50,8,40,100,300,450,600,9, 'none',0 , 0, 'none',0,0, (90, 520),(110, 520)) LOP= board_pieces('LOP', 'N/A', 'N/A', 'N/A', 'N/A', 'N/A', 'N/A', 'N/A', 'N/A', 'N/A', 'N/A', 10, 'none', 0 ,0 , 'none',0,0, (0, 520),(0, 520)) Tenanbaum= board_pieces("Tenanbaum", 'none', 'pink',140, 100, 10,50, 150, 450, 25, 750, 11, 'none',0 , 0, 'none',0,0, (0, 440), (0, 455)) Chance3= board_pieces('Chance', 'Chance', 'N/A', 'N/A', 'N/A', 'N/A', 'N/A', 'N/A', 'N/A', 'N/A', 'N/A', 12, 'none',0 , 0 , 'none',0,0, (0, 390), (0,410)) Nowakowski= board_pieces("Nowakowski", 'none', 'pink',140, 100, 10,50, 150, 450, 25, 750, 13, 'none',0 , 0, 'none',0,0, (0, 340), (0, 365)) Mcmenamin= board_pieces('Mcmenamin', 'none', 'pink',160, 100, 12,60, 180, 500, 700, 900, 15, 'none',0 , 0, 'none',0,0, (0, 290), (0,320)) GymStation= board_pieces("Gym Station", "station", 'N/A', 200, 25, 25, 'N/A', 'N/A', 'N/A', 'N/A', 'N/A', 16, 'none', 0 , 0, 'none',0,0, (0, 240), (0,275)) M_O= board_pieces('Mansfield Office' , 'none', 'orange',180, 100, 14, 70, 200, 550, 750, 950, 17, 'none',0 , 0, 'none',0,0, (0,190), (0, 225)) Chance4= board_pieces('Chance', 'Chance', 'N/A', 'N/A', 'N/A', 'N/A', 'N/A', 'N/A', 'N/A', 'N/A', 'N/A', 18, 'none',0 , 0 , 'none', 0,0, (0,140), (0, 180)) Valverde= board_pieces("Valverde", 'none', 'orange',180,100, 14, 70, 200, 550, 750, 950, 19, 'none', 0 , 0, 'none',0,0, (0,90), (0,135)) Mejia= board_pieces("Mejia", 'none', 'orange',200, 100, 16, 80,220, 600, 800, 1000, 20, 'none', 0 ,0, 'none',0,0, (0,40), (0, 90)) Free_Parking= board_pieces('Free_Parking', 'N/A', 'N/A', 'N/A', 'N/A', 'N/A', 'N/A', 'N/A', 'N/A', 'N/A', 'N/A', 21, 'none', 0 ,0 , 'none',0,0, (0,0), (0, 0)) Sanservino= board_pieces("Sanservino", 'none', "red", 260, 150, 22, 110, 330, 800, 975, 1150, 22, 'none',0 , 0, 'none',0,0, (90,0), (110, 0)) Valley= board_pieces("Valley", 'none', 'red', 260, 150, 22, 110, 330, 800, 975, 1150, 23, 'none',0 , 0, 'none',0,0, (160,0), (180, 0)) Chance5= board_pieces('Chance', 'Chance', 'N/A', 'N/A', 'N/A', 'N/A', 'N/A', 'N/A', 'N/A', 'N/A', 'N/A', 24, 'none',0 , 0 , 'none',0,0, (230, 0), (250, 0)) Draesel= board_pieces("Draesel", 'none', "red", 280, 150, 24, 120, 360, 850, 1025, 1200, 25, 'none', 0 ,0, 'none',0,0, (300,0), (320, 0)) LabStation= board_pieces('Lab Station', 'station', 'N/A', 200, 25 , 25, 'N/A', 'N/A', 'N/A', 'N/A', 'N/A', 26, 'none', 0 ,0, 'none',0,0, (370,0), (390, 0)) Weisser= board_pieces("Weisser", 'none', "yellow",300, 200, 26, 130, 390, 900, 1100, 1275, 27, 'none', 0 ,0, 'none',0,0, (440,0), (460,0)) Fang= board_pieces("Fang", 'none', "yellow",300, 200, 26, 130, 390, 900, 1100, 1275, 28, 'none', 0 , 0, 'none',0,0, (510,0), (530,0)) Chance6= board_pieces('Chance', 'Chance', 'N/A', 'N/A', 'N/A', 'N/A', 'N/A', 'N/A', 'N/A', 'N/A', 'N/A', 29, 'none', 0 , 0, 'none',0,0, (580, 0), (600,0)) Gerstein= board_pieces("Gerstein", 'none', "yellow",320, 200, 28, 150, 450, 1000, 1200, 1400, 30, 'none', 0 , 0, 'none',0,0, (650,0), (670,0)) GoToLOP= board_pieces("GoToLOP", 'GoToLOP', 'N/A', 'N/A', 'N/A', 'N/A', 'N/A', 'N/A', 'N/A', 'N/A', 'N/A', 31, 'none', 0 ,0 , 'none',0,0,(750, 0), (750, 0)) OConnor= board_pieces('OConnor', 'none', "green", 220, 150, 18, 90, 250, 700, 875, 1050, 32, 'none',0 , 0, 'none',0,0, (750, 40), (750, 90)) Liu= board_pieces("Liu", 'none', "green",220, 150, 18, 90, 250, 700, 875, 1050, 33, 'none',0 , 0, 'none',0,0, (750, 90), (750, 135)) Chance7= board_pieces('Chance', 'Chance', 'N/A', 'N/A', 'N/A', 'N/A', 'N/A', 'N/A', 'N/A', 'N/A', 'N/A', 34, 'none', 0 ,0 , 'none',0,0, (750, 140), (750, 180)) Moskowitz= board_pieces("Moskowitz", 'none', "green",240, 150, 20,100,300,750,925, 1100, 35, 'none',0 , 0, 'none',0,0, (750, 190), (750, 225)) AuditoriumStation= board_pieces('Auditorium Station', "station", 'N/A', 200, 25 , 25, 'N/A', 'N/A', 'N/A', 'N/A', 'N/A', 36, 'none', 0 ,0, 'none',0,0, (750, 240), (750, 275)) Chance8= board_pieces('Chance', 'Chance', 'N/A', 'N/A', 'N/A', 'N/A', 'N/A', 'N/A', 'N/A', 'N/A', 'N/A', 37, 'none', 0 ,0 , 'none',0,0, (750, 290), (750, 320)) Guidance= board_pieces("guidance", 'none', "dark blue",400,200, 50, 200, 600, 1400, 1700, 2000, 38, 'none', 0 , 0, 'none',0,0, (750, 340), (750, 365)) Tax2= board_pieces('Tax', 'Tax', 'N/A', 'N/A', 'N/A', 'N/A', 'N/A', 'N/A', 'N/A', 'N/A', 'N/A', 39, 'none', 0 ,0 , 'none',0,0,(750, 390), (750, 410)) RafOffice= board_pieces("Rafolowski's Office", 'none', "dark blue",350, 200, 35, 175, 500, 1100, 1300, 1500, 40, 'none',0 , 0, 'none',0,0, (750, 440), (750, 455)) #This class defines the 2 players in the game, including their name, where they are on the board, how much money they have, and how many stations they own class Player: def __init__(self, name, location, money, station): self.name = name self.location = location self.money = money self.station = station #This list defines all the spacces on the board in order. That way, this list can be used as a way to determine where the player is on the board, and set their location to that space. board= [Go, Pinto, Chance1, Arnold, Tax1, MakerSpaceStation, Raite, Chance2, Gupta, Wickerhauser, LOP, Tenanbaum, Chance3, Nowakowski, Mcmenamin, GymStation, M_O, Chance4, Valverde, Mejia, Free_Parking, Sanservino, Chance5, Valley, Draesel, LabStation, Weisser, Fang, Chance6, Gerstein, GoToLOP, OConnor, Liu, Chance7, Moskowitz, AuditoriumStation, Chance8, RafOffice, Tax2, Guidance] #Initializing player 1, who starts at location 0 which is Go, has 1500 dollars, and doesn't own any stations player1name = input("Player one, input your name. You will go first. ") player1= Player(player1name, 0, 1500, 0) #Tells the player he starts at Go print(f"You are starting at {board[player1.location].name}") #Initializing player 2 player2name = input("Player two, input your name. ") player2= Player(player2name, 0, 1500, 0 ) #Tells the player he starts at Go print(f"You are starting at {board[player2.location].name}") #Sets the minimum places the person can move at 2, and the maximum places the person can move at 12, just like rolling 2 dice min = 2 max = 12 #Lists to see if the player owns all the spaces of a certain color, so they can start building houses and hotels on those spaces color1=[] color2=[] #This loop escapes the game if you close the pygame window for e in pygame.event.get(): if e.type == pygame.QUIT: quit() #Sets a list of where the coordinates of the car and hat are. That way, when it's time to change the location of the car or hat, the previous image of the car/hat can be removed and replaced with the coordinates of the new image player1character = [] player2character = [] #Game only occurs when the players have money while player1.money > 0 and player2.money > 0: dice_answer1= input(f"{player1.name}, are you ready to roll the dice? Click enter to roll.") #Pick a random integer between 2 and 12 for the player to move move = int(random.randint(min,max)) print(f"{player1.name} rolled a {move}") #Move the player to that location player1.location = player1.location + move if player1.location < 40: #Set the image of the car to the coordinates of the location where the player is currently at gameDisplay.blit(carIMG, (board[player1.location].car_coordinates)) #Display the image and the current location of the image to the list that tracks where the car was previously. That way, when it goes through the loop again, this previous image of the car can be replaced in the list by the image of the car at the new location. pygame.display.update() player1character.append(carIMG) #if the number is greater than 40, take the mod of that number to find the location of where the player is on the board if player1.location >= 40: player1.location = player1.location % 40 player1.money= player1.money + 200 #Set the image, display the image, and add it to the list that tracks the car's location gameDisplay.blit(carIMG, (board[player1.location].car_coordinates)) pygame.display.update() player1character.append(carIMG) #Since the player passes go when it goes through all 40 spaces, they get 200 dollars print(f"{player1.name} now has {player1.money} because they got 200 dollars for passing Go.") #When the list that tracks the car's location is greater than 1, you keep the image of the car that was just added to the list, and get rid of the old image of it's location if len(player1character) > 1: player1character.pop(0) print(f"{player1.name} is at {board[player1.location].name}") #When the player lands on chance, randomly pick between them getting or losing 50 dollars, and change their money total as a result. if board[player1.location].owner == 'Chance': chance1= [player1.money - 50] chance3= [player1.money + 50] chances= [chance1, chance3] randomchance = random.choice(chances) result = int(randomchance[0]) player1.money = result print(f"{player1.name} now has {player1.money} dollars because they landed on a chance spot. ") #If the player lands on Go To LOP, they go to LOP elif board[player1.location].name == 'GoToLOP': player1.location = board.index(LOP) print(f"Oh no, you are at LOP because you landed on Go To LOP!") #If the player lands on a station and it's owner is still no one, they can buy the station at a certain price. If they do buy it, you change their money total based on how much it cost, and make them the owner elif board[player1.location].owner == 'station': answerS= input(f"Would you like to buy this property for {board[player1.location].purchase_price}? ").lower() if answerS == 'yes': player1.money= player1.money - board[player1.location].purchase_price print(f"{player1.name} now has {player1.money} dollars. ") board[player1.location].owner = player1.name print(f"The owner of {board[player1.location].name} is {board[player1.location].owner}") #You add 1 to the player's station count, because if they get more stations, the other player has to pay more when they land on one of their stations, so we need to keep track of how many stations each player owns player1.station= player1.station + 1 board[player1.location].stationcount1= board[player1.location].stationcount1 +1 #If the player lands on a station the other player owns and they own 1 station, you pay them the rent price for owning 1 station ($25), and they get $25 elif board[player1.location].owner == player2.name and player2.station == 1 and board[player1.location].stationcount2 == 1: player1.money= player1.money - 25 player2.money= player2.money + 25 print(f"{player1.name} has to pay 25 dollars and now has {player1.money} dollars because they landed on a station owned by player 2.") print(f"{player2.name} now has {player2.money} dollars after collecting it from Player 1.") #if the player lands on a station the other player owns and they own 2 stations, you pay them the rent price for owning 2 stations ($50), and they get $50 elif board[player1.location].owner == player2.name and player2.station == 2 and board[player1.location].stationcount2 == 1: player1.money= player1.money - 50 player2.money= player2.money + 50 print(f"{player1.name} has to pay 50 dollars and now has {player1.money} dollars because they landed on a station owned by player 2 (who owns two stations).") print(f"{player2.name} now has {player2.money} dollars after collecting it from Player 1.") #if the player lands on a station the other player owns and they own 3 stations, you pay them the rent price for owning 3 stations ($75), and they get $75 elif board[player1.location].owner == player2.name and player2.station == 3 and board[player1.location].stationcount2 == 1: player1.money= player1.money - 75 player2.money= player2.money + 75 print(f"{player1.name} has to pay 75 dollars and now has {player1.money} dollars because they landed on a station owned by player 2 (who owns three stations).") print(f"{player2.name} now has {player2.money} dollars after collecting it from Player 1.") #if the player lands on a station the other player owns and they own 4 stations, you pay them the rent price for owning 4 stations ($100), and they get $100 elif board[player1.location].owner == player2.name and player2.station == 4 and board[player1.location].stationcount2 == 1: player1.money= player1.money - 100 player2.money= player2.money + 100 print(f"{player1.name} has to pay 100 dollars and now has {player1.money} dollars because they landed on a station owned by player 2 (who owns four stations).") print(f"{player2.name} now has {player2.money} dollars after collecting it from Player 1.") #If the player lands on tax, subtract 50 dollars from their total elif board[player1.location].owner == 'Tax': player1.money= player1.money - 50 print(f"{player1.name} has to pay 50 dollars and now has {player1.money} dollars.") #If the player lands on an unowned property, ask them if they want to buy it. If they say yes, you subtract the price to buy it from them, and make them the owner of the property elif board[player1.location].owner == 'none': answer1= input(f"Would you like to buy this property for {board[player1.location].purchase_price}? ") if answer1 == 'yes': player1.money= player1.money - board[player1.location].purchase_price print(f"{player1.name} now has {player1.money} dollars. ") board[player1.location].owner = player1.name print(f"The owner of {board[player1.location].name} is {board[player1.location].owner}") #Add the location of the space the player owns to the list that tracks if they own all the spaces of a certain color, to see if they can buy houses or hotels later color1.append(board[player1.location].color) #If the player lands on a the other player's space and they have a hotel there, the player pays the hotel price to the other player elif board[player1.location].hotel_owner == player2.name: player1.money= player1.money - board[player1.location].hotel_price player2.money = player2.money + board[player1.location].hotel_price print(f"{player1.name} now has {player1.money} dollars because they landed on Player Two's Property that has a hotel on it. ") print(f"{player2.name} now has {player2.money} dollars after collecting it from Player 1.") #If the player lands on a the other player's space and they have 1 house there, the player pays the price of that space when it has 1 house to the other player elif board[player1.location].house_owner == player2.name and board[player1.location].house_2count == 1: player1.money= player1.money - board[player1.location].house_1price player2.money = player2.money + board[player1.location].house1_price print(f"{player1.name} now has {player1.money} dollars because they landed on Player Two's Property that has a house on it. ") print(f"{player2.name} now has {player2.money} dollars after collecting it from Player 1.") #If the player lands on a the other player's space and they have 2 houses there, the player pays the price of that space when it has 2 houses to the other player elif board[player1.location].house_owner == player2.name and board[player1.location].house_2count == 2: player1.money= player1.money - board[player1.location].house_2price player2.money = player2.money + board[player1.location].house2_price print(f"{player1.name} now has {player1.money} dollars because they landed on Player Two's Property that has two houses on it. ") print(f"{player2.name} now has {player2.money} dollars after collecting it from Player 1.") #If the player lands on a the other player's space and they have 3 houses there, the player pays the price of that space when it has 3 houses to the other player elif board[player1.location].house_owner == player2.name and board[player1.location].house_2count == 3: player1.money= player1.money - board[player1.location].house3_price player2.money = player2.money + board[player1.location].house3_price print(f"{player1.name} now has {player1.money} dollars because they landed on Player Two's Property that has three houses on it. ") print(f"{player2.name} now has {player2.money} dollars after collecting it from Player 1.") #If the player lands on a the other player's space and they have 4 houses there, the player pays the price of that space when it has 4 houses to the other player elif board[player1.location].house_owner == player2.name and board[player1.location].house_2count == 4: player1.money= player1.money - board[player1.location].house4_price player2.money = player2.money + board[player1.location].house4_price print(f"{player1.name} now has {player1.money} dollars because they landed on Player Two's Property that has four houses on it. ") print(f"{player2.name} now has {player2.money} dollars after collecting it from Player 1.") #If the player lands on a the other player's space and they have 0 houses there, the player pays the rent price of that space to the other player elif board[player1.location].owner == player2.name: player1.money= player1.money - board[player1.location].rent_price player2.money = player2.money + board[player1.location].rent_price print(f"{player1.name} now has {player1.money} dollars because they landed on Player Two's Property at {board[player1.location].name}. ") print(f"{player2.name} now has {player2.money} dollars after collecting it from Player 1.") #If the player lands on their property, nothing happens elif board[player1.location].owner == player1.name: print("This location is your property, so you don't have to pay money!") #If the player has all the purple spaces and they are on one of those spaces, they can buy a house for that space. If they say yes, you subtract the price to buy a house, and add a house to that location if color1.count('purple')== 2 and board[player1.location].color=='purple': P_house_answer= input(f'Congrats, you have all of the purple properties, would you like to buy a house for {board[player1.location].house_price}? Type yes if you want to!').lower() if P_house_answer == 'yes': player1.money= player1.money- board[player1.location].house_price print(f'You now have {player1.money} dollars and a house at {board[player1.location].name}.') board[player1.location].house_owner = player1.name board[player1.location].house_count +=1 #If the player has all the light blue spaces and they are on one of those spaces, they can buy a house for that space. If they say yes, you subtract the price to buy a house, and add a house to that location elif color1.count('light blue') == 3 and board[player1.location].color == 'light blue': LB_house_answer= input(f'Congrats, you have all of the light blue properties, would you like to buy a house for {board[player1.location].house_price}? Type yes if you want to!').lower() if LB_house_answer == 'yes' and board[player1.location].color == 'light blue': player1.money= player1.money- board[player1.location].house_price print(f'You now have {player1.money} dollars and a house at {board[player1.location].name}.') board[player1.location].house_owner = player1.name board[player1.location].house_count +=1 #If the player has all the pink spaces and they are on one of those spaces, they can buy a house for that space. If they say yes, you subtract the price to buy a house, and add a house to that location elif color1.count('pink') == 3 and board[player1.location].color == 'pink': P_house_answer= input(f'Congrats, you have all of the pink properties, would you like to buy a house for {board[player1.location].house_price}? Type yes if you want to!').lower() if P_house_answer == 'yes': player1.money= player1.money- board[player1.location].house_price print(f'You now have {player1.money} dollars and a house at {board[player1.location].name}.') board[player1.location].house_owner = player1.name board[player1.location].house_count +=1 #If the player has all the orange spaces and they are on one of those spaces, they can buy a house for that space. If they say yes, you subtract the price to buy a house, and add a house to that location elif color1.count('orange') == 3 and board[player1.location].color == 'orange': O_house_answer= input(f'Congrats, you have all of the pink properties, would you like to buy a house for {board[player1.location].house_price}? Type yes if you want to!').lower() if O_house_answer == 'yes': player1.money= player1.money- board[player1.location].house_price print(f'You now have {player1.money} dollars and a house at {board[player1.location].name}.') board[player1.location].house_owner = player1.name board[player1.location].house_count +=1 #If the player has all the red spaces and they are on one of those spaces, they can buy a house for that space. If they say yes, you subtract the price to buy a house, and add a house to that location elif color1.count('red') == 3 and board[player1.location].color == 'red': R_house_answer= input(f'Congrats, you have all of the pink properties, would you like to buy a house for {board[player1.location].house_price}? Type yes if you want to!').lower() if R_house_answer == 'yes': player1.money= player1.money- board[player1.location].house_price print(f'You now have {player1.money} dollars and a house at {board[player1.location].name}.') board[player1.location].house_owner = player1.name board[player1.location].house_count +=1 #If the player has all the yellow spaces and they are on one of those spaces, they can buy a house for that space. If they say yes, you subtract the price to buy a house, and add a house to that location elif color1.count('yellow') == 3 and board[player1.location].color == 'yellow': Y_house_answer= input(f'Congrats, you have all of the pink properties, would you like to buy a house for {board[player1.location].house_price}? Type yes if you want to!').lower() if Y_house_answer == 'yes': player1.money= player1.money- board[player1.location].house_price print(f'You now have {player1.money} dollars and a house at {board[player1.location].name}.') board[player1.location].house_owner = player1.name board[player1.location].house_count +=1 #If the player has all the green spaces and they are on one of those spaces, they can buy a house for that space. If they say yes, you subtract the price to buy a house, and add a house to that location elif color1.count('green') == 3 and board[player1.location].color == 'green': G_house_answer= input(f'Congrats, you have all of the pink properties, would you like to buy a house for {board[player1.location].house_price}? Type yes if you want to!').lower() if G_house_answer == 'yes': player1.money= player1.money- board[player1.location].house_price print(f'You now have {player1.money} dollars and a house at {board[player1.location].name}.') board[player1.location].house_owner = player1.name board[player1.location].house_count +=1 #If the player has all the dark blue spaces and they are on one of those spaces, they can buy a house for that space. If they say yes, you subtract the price to buy a house, and add a house to that location elif color1.count('dark blue') == 2 and board[player1.location].color == 'dark blue': DB_house_answer= input(f'Congrats, you have all of the dark blue properties, would you like to buy a house for {board[player1.location].house_price}? Type yes if you want to!').lower() if DB_house_answer == 'yes': player1.money= player1.money- board[player1.location].house_price print(f'You now have {player1.money} dollars and a house at {board[player1.location].name}.') board[player1.location].house_owner = player1.name board[player1.location].house_count +=1 #If the player lands on a space of a place they already have 4 houses on, they can buy a hotel. If they say yes, subtract the hotel price and add a hotel to their location elif board[player1.location].house_count == 4: hotel_answer= input("You have four houses at this location, would you like to buy a hotel here?").lower() if hotel_answer == 'yes': board[player1.location].house_count +=1 player1.money= player1.money- board[player1.location].house_price board[player1.location].hotel_owner == player1.name print(f"Congrats, you now own a hotel at {board[player1.location]} and you have {player1.money} dollars.") #Pick a random integer between 2 and 12 for the player to move dice_answer2= input(f"{player2.name}, are you ready to roll the dice? Click enter to roll.") #Move the player to that location move2 = int(random.randint(min,max)) print(f"{player2.name} rolled a {move2}") player2.location = player2.location + move2 if player2.location < 40: #Set the image of the hat to the coordinates of the location where the player is currently at gameDisplay.blit(hatIMG, (board[player2.location].hat_coordinates)) #Display the image and the current location of the image to the list that tracks where the car was previously. That way, when it goes through the loop again, this previous image of the car can be replaced in the list by the image of the car at the new location. pygame.display.update() player2character.append(hatIMG) #If the number is greater than 40, take the mod of that number to find the location of where the player is on the board if player2.location >= 40: player2.location = player2.location % 40 player2.money = player2.money + 200 #Set the image, display the image, and add it to the list that tracks the car's location gameDisplay.blit(hatIMG, (board[player2.location].hat_coordinates)) pygame.display.update() player2character.append(hatIMG) #Since the player passes go when it goes through all 40 spaces, they get 200 dollars print(f"{player2.name} now has {player2.money} because they got 200 dollars for passing Go.") #When the list that tracks the car's location is greater than 1, you keep the image of the car that was just added to the list, and get rid of the old image of it's location if len(player2character) > 1: player2character.pop(0) print(f"{player2.name} is at {board[player2.location].name}") #When the player lands on chance, randomly pick between them getting or losing 50 dollars, and change their money total as a result. if board[player2.location].owner == 'Chance': chance1= [player1.money - 50] chance2= [player2.money - 50] chance3= [player1.money + 50] chance4= [player2.money + 50] chances2= [chance2, chance4] randomchance2 = random.choice(chances2) result2 = int(randomchance2[0]) player2.money = result2 print(f"{player2.name} now has {player2.money} dollars because they landed on a chance spot. ") #If the player lands on Go To LOP, they go to LOP elif board[player2.location].owner == 'GoToLOP': player2.location = board.index(LOP) print(f"Oh no, you are at {board[player2.location].name} because you landed on Go To LOP!") #If the player lands on a station and it's owner is still no one, they can buy the station at a certain price. If they do buy it, you change their money total based on how much it cost, and make them the owner elif board[player2.location].owner == 'station': answerS2= input(f"Would you like to buy this property for {board[player2.location].purchase_price}? ").lower() if answerS2 == 'yes': player2.money= player2.money - board[player2.location].purchase_price print(f"{player2.name} now has {player2.money} dollars. ") board[player2.location].owner = player2.name print(f"The owner of {board[player2.location].name} is {board[player2.location].owner}") #You add 1 to the player's station count, because if they get more stations, the other player has to pay more when they land on one of their stations, so we need to keep track of how many stations each player owns player2.station= player2.station + 1 board[player2.location].stationcount2= board[player2.location].stationcount2 +1 #If the player lands on a station the other player owns and they own 1 station, you pay them the rent price for owning 1 station ($25), and they get $25 elif board[player2.location].owner == player1.name and player1.station == 1 and board[player2.location].stationcount1 == 1: player2.money= player2.money - 25 player1.money= player1.money + 25 print(f"{player2.name} has to pay 25 dollars and now has {player2.money} dollars because they landed on a station owned by player 1.") print(f"{player1.name} now has {player1.money} dollars after collecting it from Player 2.") #if the player lands on a station the other player owns and they own 2 stations, you pay them the rent price for owning 2 stations ($50), and they get $50 elif board[player2.location].owner == player1.name and player1.station == 2 and board[player2.location].stationcount1 == 1: player2.money= player2.money - 50 player1.money= player1.money + 50 print(f"{player2.name} has to pay 50 dollars and now has {player2.money} dollars because they landed on a station owned by player 1 (who owns two stations).") print(f"{player1.name} now has {player1.money} dollars after collecting it from Player 2.") #if the player lands on a station the other player owns and they own 3 stations, you pay them the rent price for owning 3 stations ($75), and they get $75 elif board[player2.location].owner == player1.name and player1.station == 3 and board[player2.location].stationcount1 == 1: player2.money= player2.money - 75 player1.money= player1.money + 75 print(f"{player2.name} has to pay 75 dollars and now has {player2.money} dollars because they landed on a station owned by player 1 (who owns three stations).") print(f"{player1.name} now has {player1.money} dollars after collecting it from Player 2.") #if the player lands on a station the other player owns and they own 4 stations, you pay them the rent price for owning 4 stations ($100), and they get $100 elif board[player2.location].owner == player1.name and player1.station == 4 and board[player1.location].stationcount1 == 1: player2.money= player2.money - 100 player1.money= player1.money + 100 print(f"{player2.name} has to pay 100 dollars and now has {player2.money} dollars because they landed on a station owned by player 2 (who owns four stations).") print(f"{player1.name} now has {player1.money} dollars after collecting it from Player 2.") #If the player lands on tax, subtract 50 dollars from their total elif board[player2.location].owner == 'Tax': player2.money= player2.money - 50 print(f"{player2.name} has to pay 50 dollars and now has {player2.money} dollars.") #If the player lands on an unowned property, ask them if they want to buy it. If they say yes, you subtract the price to buy it from them, and make them the owner of the property elif board[player2.location].owner == 'none': answer2= input(f"Would {player2.name} like to buy this property for {board[player2.location].purchase_price}? ") if answer2 == 'yes': player2.money= player2.money - board[player2.location].purchase_price print(f"{player2.name} now has {player2.money} dollars. ") board[player2.location].owner = player2.name print(f"The owner of {board[player2.location].name} is {board[player2.location].owner}") #Add the location of the space the player owns to the list that tracks if they own all the spaces of a certain color, to see if they can buy houses or hotels later color2.append(board[player2.location].color) #If the player lands on a the other player's space and they have a hotel there, the player pays the hotel price to the other player elif board[player2.location].hotel_owner == player1.name: player2.money= player2.money - board[player2.location].hotel_price player1.money= player1.money + board[player2.location].hotel_price print(f"{player2.name} now has {player2.money} dollars because they landed on Player One's Property that has a hotel on it. ") print(f"{player1.name} now has {player1.money} dollars after collecting it from Player 2.") #If the player lands on a the other player's space and they have 1 house there, the player pays the price of that space when it has 1 house to the other player elif board[player2.location].house_owner == player1.name and board[player2.location].house_count == 1: player2.money= player2.money- board[player2.location].house_1price player1.money= player1.money + board[player2.location].house_1price print(f"You landed on {player1.name}'s propery with one house, so {player2.name} now has {player2.money} dollars. ") print(f"{player1.name} now has {player1.money} dollars after collecting it from Player 2.") #If the player lands on a the other player's space and they have 2 houses there, the player pays the price of that space when it has 2 houses to the other player elif board[player2.location].house_owner == player1.name and board[player2.location].house_count == 2: player2.money= player2.money- board[player2.location].house_2price player1.money= player1.money + board[player2.location].house_2price print(f"You landed on {player1.name}'s propery with two houses, so {player2.name} now has {player2.money} dollars. ") print(f"{player1.name} now has {player1.money} dollars after collecting it from Player 2.") #If the player lands on a the other player's space and they have 3 houses there, the player pays the price of that space when it has 3 houses to the other player elif board[player2.location].house_owner == player1.name and board[player2.location].house_count == 3: player2.money= player2.money- board[player2.location].house3_price player1.money= player1.money + board[player2.location].house_3price print(f"You landed on {player1.name}'s propery with three houses, so {player2.name} now has {player2.money} dollars. ") print(f"{player1.name} now has {player1.money} dollars after collecting it from Player 2.") #If the player lands on a the other player's space and they have 4 houses there, the player pays the price of that space when it has 4 houses to the other player elif board[player2.location].house_owner == player1.name and board[player2.location].house_count == 4: player2.money= player2.money- board[player2.location].house4_price player1.money= player1.money + board[player2.location].house_4price print(f"You landed on {player1.name}'s propery with four houses, so {player2.name} now has {player2.money} dollars. ") print(f"{player1.name} now has {player1.money} dollars after collecting it from Player 2.") #If the player lands on a the other player's space and they have 0 houses there, the player pays the rent price of that space to the other player elif board[player2.location].owner == player1.name: player2.money= player2.money - board[player2.location].rent_price player1.money= player1.money + board[player2.location].rent_price print(f"You landed on {player1.name}'s propery at {board[player2.location].name}, so {player2.name} now has {player2.money} dollars. ") print(f"{player1.name} now has {player1.money} dollars after collecting it from Player 2.") #If the player lands on their property, nothing happens elif board[player2.location].owner == player2.name: print("This location is your property, so you don't have to pay money!") #If the player has all the purple spaces and they are on one of those spaces, they can buy a house for that space. If they say yes, you subtract the price to buy a house, and add a house to that location elif color2.count('purple')== 2 and board[player2.location].color=='purple': P2_house_answer= input(f'Congrats, you have all of the purple properties, would you like to buy a house for {board[player2.location].house_price}? Type yes if you want to!').lower() if P2_house_answer == 'yes': player2.money= player2.money- board[player2.location].house_price print(f'You now have {player2.money} dollars and a house at {board[player2.location].name}.') board[player2.location].house_owner = player2.name board[player2.location].house_2count +=1 #If the player has all the light blue spaces and they are on one of those spaces, they can buy a house for that space. If they say yes, you subtract the price to buy a house, and add a house to that location elif color2.count('light blue') == 3 and board[player2.location].color == 'light blue': LB2_house_answer= input(f'Congrats, you have all of the light blue properties, would you like to buy a house for {board[player2.location].house_price}? Type yes if you want to!').lower() if LB2_house_answer == 'yes' and board[player2.location].color == 'light blue': player2.money= player2.money- board[player2.location].house_price print(f'You now have {player2.money} dollars and a house at {board[player2.location].name}.') board[player2.location].house_owner = player2.name board[player2.location].house_2count +=1 #If the player has all the pink spaces and they are on one of those spaces, they can buy a house for that space. If they say yes, you subtract the price to buy a house, and add a house to that location elif color2.count('pink') == 3 and board[player2.location].color == 'pink': P2_house_answer= input(f'Congrats, you have all of the pink properties, would you like to buy a house for {board[player2.location].house_price}? Type yes if you want to!').lower() if P2_house_answer == 'yes' : player2.money= player2.money- board[player2.location].house_price print(f'You now have {player2.money} dollars and a house at {board[player2.location].name}.') board[player2.location].house_owner = player2.name board[player2.location].house_2count +=1 #If the player has all the orange spaces and they are on one of those spaces, they can buy a house for that space. If they say yes, you subtract the price to buy a house, and add a house to that location elif color2.count('orange') == 3 and board[player2.location].color == 'orange': O2_house_answer= input(f'Congrats, you have all of the pink properties, would you like to buy a house for {board[player2.location].house_price}? Type yes if you want to!').lower() if O2_house_answer == 'yes': player2.money= player2.money- board[player2.location].house_price print(f'You now have {player2.money} dollars and a house at {board[player2.location].name}.') board[player2.location].house_owner = player2.name board[player2.location].house_2count +=1 #If the player has all the red spaces and they are on one of those spaces, they can buy a house for that space. If they say yes, you subtract the price to buy a house, and add a house to that location elif color2.count('red') == 3 and board[player2.location].color == 'red': R2_house_answer= input(f'Congrats, you have all of the pink properties, would you like to buy a house for {board[player2.location].house_price}? Type yes if you want to!').lower() if R2_house_answer == 'yes': player2.money= player2.money- board[player2.location].house_price print(f'You now have {player2.money} dollars and a house at {board[player2.location].name}.') board[player2.location].house_owner = player2.name board[player2.location].house_2count +=1 #If the player has all the yellow spaces and they are on one of those spaces, they can buy a house for that space. If they say yes, you subtract the price to buy a house, and add a house to that location elif color2.count('yellow') == 3 and board[player2.location].color == 'yellow': Y2_house_answer= input(f'Congrats, you have all of the pink properties, would you like to buy a house for {board[player2.location].house_price}? Type yes if you want to!').lower() if Y2_house_answer == 'yes': player2.money= player2.money- board[player2.location].house_price print(f'You now have {player2.money} dollars and a house at {board[player2.location].name}.') board[player2.location].house_owner = player2.name board[player2.location].house_2count +=1 #If the player has all the green spaces and they are on one of those spaces, they can buy a house for that space. If they say yes, you subtract the price to buy a house, and add a house to that location elif color2.count('green') == 3 and board[player2.location].color == 'green': G2_house_answer= input(f'Congrats, you have all of the pink properties, would you like to buy a house for {board[player2.location].house_price}? Type yes if you want to!').lower() if G2_house_answer == 'yes': player2.money= player2.money- board[player2.location].house_price print(f'You now have {player2.money} dollars and a house at {board[player2.location].name}.') board[player2.location].house_owner = player2.name board[player2.location].house_2count +=1 #If the player has all the dark blue spaces and they are on one of those spaces, they can buy a house for that space. If they say yes, you subtract the price to buy a house, and add a house to that location elif color2.count('dark blue') == 2 and board[player2.location].color == 'dark blue': DB2_house_answer= input(f'Congrats, you have all of the pink properties, would you like to buy a house for {board[player2.location].house_price}? Type yes if you want to!').lower() if DB2_house_answer == 'yes': player2.money= player2.money- board[player2.location].house_price print(f'You now have {player2.money} dollars and a house at {board[player2.location].name}.') board[player2.location].house_owner = player2.name board[player2.location].house_2count +=1 #If the player lands on a space of a place they already have 4 houses on, they can buy a hotel. If they say yes, subtract the hotel price and add a hotel to their location elif board[player2.location].house_2count == 4: hotel2_answer= input("You have four houses at this location, would you like to buy a hotel here?").lower() if hotel2_answer == 'yes': board[player2.location].house_count +=1 player2.money= player2.money- board[player2.location].house_price board[player2.location].hotel_owner == player2.name print(f"Congrats, you now own a hotel at {board[player2.location].name} and you have {player2.money} dollars.") #Make all the images actually appear pygame.display.flip() #If Player 1 still has money, they win if player1.money > 0: print(f"{player2name} ran out of money, so {player1name} won! Congratulations on winning MAGNET MONOPOLY! ") #If Player 2 still has money, they win elif player2.money > 0 : print(f"{player1name} ran out of money, so {player2name} won! Congratulations on winning MAGNET MONOPOLY! ")
#########################Done######################### #First Aproach def IsSame(s1,s2): l1=len(s1) l2 = len(s2) if l1!=l2: return False if l1<1 and l2<1: return True if l1<1 or l2<1: return False #We can sort then and compare character by character #Second Approach def IsSame2(s1,s2): #I will do it using an array where we will store the count of #of characters using ascii value of the character pass # Third Approach def IsSame3(s1, s2): # I will do it using dictionary for strong count for first string #Will check second string char and decrease the count : if we will get any charcter not existing in dict keys then return false #At the end of our operation if any count is greater than zero then retun false pass if __name__=='__main__': s1 = input() s2 = input() print IsSame(s1,s2)
# def convertIntoBinary(num,b): # res=0 # i=0 # while num>0 and i<=b: # res=res+(num%10)*(2**i) # num=num/10 # i=i+1 # return res # def binaryToDecimal(binary): # binary1 = binary # decimal, i, n = 0, 0, 0 # while (binary != 0): # dec = binary % 10 # decimal = decimal + dec * pow(2, i) # binary = binary // 10 # i += 1 # return decimal def binaryToDecimal(stri): return int(stri, 2) if __name__=='__main__': # print convertIntoBinary(1010,4) # print convertIntoBinary(0100, 4) # print convertIntoBinary(0010, 4) # print convertIntoBinary(0011, 4) print binaryToDecimal('1010') print binaryToDecimal('0100') print binaryToDecimal('0010') print binaryToDecimal('0011') # arr=raw_input().split() # a=int(arr[0]) # b=int(arr[0]) # print a,'--',b # max=0 # for i in range(a): # num=input() # t=convertIntoBinary(num,b-1) # if t>max: # max=t # print max
import math def checkPrime(n): if n<2: return False if n==2: return False if n%2==0: return False for i in range(3,int(math.sqrt(n))): if n%i==0: return False return True n=input("Enter the number:") for i in range(1,n+1): if n%i==0: if checkPrime(i) : print i,"It's Prime number" else: print i,"It's not Prime number"
n=input("Enter the number") li=[x for x in range(1,n+1)] print sum(li)
class Node: def __init__(self,data): self.data=data self.next=None class LinkedList: def __init__(self): self.head=None if __name__=='__main__': llist=LinkedList() llist.head=Node(10) second=Node(20) third=Node(30) second.next=third llist.head.next=second
n=int(raw_input("Enter the number:")) rev=0 while n>0: rev=rev*10+n%10 n=n/10 print rev
''' n=input("Enter the number: ") dict={} dict2={} for i in range(1,n+1): dict[i]=i*i dict2.update({i:i*i}) print dict print dict2 ''' print "-----------------Staring completely new session-----------------" #Creating a empty dictionary data1={} data2={} data3={} data4={} data5={} #Creating a dictionary with initial values data1={'a':1,'b':2,'c':3} print "Printing data 1========================",data1 data2=dict(a=1,b=2,c=3) print "Printing data 1========================",data2 data3={k:v for k,v in (('a',1),('b',2),('c',3))} print "Printing data 1========================",data3 #Inserting/Updating a single value data1['a']=1 data1.update({'a':1}) data1.update(dict(a=1)) data1.update(a=1) #Inserting/Updating multiple values data1.update
count=0 high=100 low=0 print("Please think of a number between 0 and 100!") while input != 'c': newnum=int((high+low)/2) print("Is your secret number "+str( newnum)+"?") x = input("Enter 'h' to indicate the guess is too high. Enter 'l' to indicate the guess is too low. Enter 'c' to indicate I guessed correctly.") if x == 'h': high = newnum count+=1 elif x == 'l': low = newnum count+=1 elif x == 'c': print("Game over. Your secret number was: " + str( newnum)) break else: print("try again")
print ('Merhaba, Django Girls!') if 3>2: print('calisiyor') if 5>2 : print("5 gercekten de 2'den buyuktur") else: print("5 2'den buyuk degildir") name = "Zeynep" if name == "Ayse": print("Selam Ayse!") elif name == "Zeynep": print("Selam Zeynep!") else: print("Selam yabanci") volume = 57 if volume <20: print("cok sessiz.") elif 20 <= volume < 40: print ("guzel bir fon muzigi") elif 40 <= volume < 60: print("Harika her notayi duyabiliyorum") elif 60 <= volume < 80 : print ("Parti baslasin") elif 80 <= volume <100 : print ("Biraz gurultulu") else: print("kulaklarim agriyor! :(") if volume < 20 or volume > 80: volume = 50 print("That's better!") def hi(): print('Merhaba!') print('Nasilsin?') hi() def hi(name): if name=="Ayse": print ("Merhaba Ayse!") elif name == "Zeynep": print ("Merhaba Zeynep!") else: print ("Merhaba Yabanci!") hi(name) hi("Ayse") hi("Zeynep") def hi(name): print ("Merhaba " + name + "!") hi ("Seda") kizlar= ["Seda", "Gul", "Pinar", "Ayse", "Esra"] for name in kizlar: def hi(name): print("Merhaba" + name + "!") kizlar= ["Seda", "Gul", "Pinar", "Ayse", "Esra"] for name in kizlar: hi(name) print ('Siradaki kiz') for i in range (1,6): print(i)
n = int(input("Ingrese numero de filas: ")) for i in range(1, n+1): print((str(i)+ " ")*i)
# ex15 reading files # import argv module from sys import argv # unpack the argv script, filename = argv # open the file txt = open(filename) # print the file name print "Here's your file %s:" % filename # print the file content print txt.read() # reread the file print "Type the filename again:" file_again = raw_input("> ") # reopen the file txt_again = open(file_again) # print the file again print txt_again.read()
# Definition for a undirected graph node # class UndirectedGraphNode: # def __init__(self, x): # self.label = x # self.neighbors = [] class Solution: # @param node, a undirected graph node # @return a undirected graph node def __init__(self): self.Map = {} #store nodes in copied graph def cloneGraph(self, node): if node is None: return head = UndirectedGraphNode(node.label) self.Map[node.label] = head for neighbor in node.neighbors: if neighbor == node: head.neighbors.append(head) continue if not self.Map.has_key(neighbor.label): new_neighbor = self.cloneGraph(neighbor) else: new_neighbor = self.Map[neighbor.label] head.neighbors.append(new_neighbor) return head
# Definition for an interval. # class Interval: # def __init__(self, s=0, e=0): # self.start = s # self.end = e class Solution: # @param intervals, a list of Interval # @return a list of Interval def merge(self, intervals): if not intervals: return [] intervals.sort(key = lambda x:x.start) #sort intervals by their start point i = 0 while i<len(intervals)-1: if intervals[i+1].start <= intervals[i].end: intervals[i].end = max(intervals[i+1].end,intervals[i].end) intervals.pop(i+1) else: i+= 1 return intervals
class Solution: # @return a list of integers def getRow(self, rowIndex): values = [1 for i in range(0, rowIndex+1)] #we only need the bottom row for row in range(1, rowIndex+1): values[row] = 1 for col in range(row-1, 0, -1): values[col] = values[col-1] + values[col] return values
# Definition for a binary tree node # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None # self.next = None class Solution: # @param root, a tree node # @return nothing def connect(self, root): if root is None: return queue = [root] while queue: node = queue.pop(0) if node.left and node.right: node.left.next = node.right next = self.search(node) if next: if next.left: node.right.next = next.left elif next.right: node.right.next = next.right queue.append(node.left) queue.append(node.right) elif node.left and not node.right: next = self.search(node) if next: if next.left: node.left.next = next.left elif next.right: node.left.next = next.right queue.append(node.left) elif node.right and not node.left: next = self.search(node) if next: if next.left: node.right.next = next.left elif next.right: node.right.next = next.right queue.append(node.right) def search(self, node): #search for the next node that has child node in the same level next = node.next while next: if next.left or next.right: return next else: next = next.next return None
# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: # @param a list of ListNode # @return a ListNode def mergeKLists(self, lists): if not lists: return None if len(lists) == 1: return lists[0] #divide and conquer l = len(lists) l1 = self.mergeKLists(lists[:l/2]) l2 = self.mergeKLists(lists[l/2:]) return self.mergeTwo(l1,l2) def mergeTwo(self, a, b): if a == None or b == None: return a if b==None else b elif a == None and b == None: return None start = a if a.val<b.val: a = a.next else: start = b b = b.next head = start while a and b: if a.val < b.val: head.next = a head = a a = a.next else: head.next = b head = b b = b.next while a: head.next = a head = a a = a.next while b: head.next = b head = b b = b.next return start
__author__ = 'Justin' """ Question: Write a program which can compute the factorial of a given numbers. The results should be printed in a comma-separated sequence on a single line. Suppose the following input is supplied to the program: 8 Then, the output should be: 40320 """ num = int(input("Enter number: ")) factorial = 1 for i in range(1, num + 1): factorial *= i print(factorial) """ def fact(x): if x == 0: return 1 return x * fact(x - 1) x=int(raw_input()) print fact(x) """
from tkinter import * root = Tk() root.geometry('400x400') root.config(bg = 'magenta') root.resizable(0,0) root.title('PhoneBook App') contactlist = [ ['Jane Doe', '123456'], ['John Doe', '78910'], ] Name = StringVar() Number = StringVar() frame = Frame(root) frame.pack(side = RIGHT) #scroll = Scrollbar(frame, orient=VERTICAL) select = Listbox(frame, height=12) #scroll.config (command=select.yview) #scroll.pack(side=RIGHT, fill=Y) select.pack(side=LEFT, fill=BOTH, expand=1) def Selected(): return int(select.curselection()[0]) def AddContact(): contactlist.append([Name.get(), Number.get()]) Select_set() def Select_set() : contactlist.sort() select.delete(0,END) for name, phone in contactlist: select.insert(END, name) Select_set() Label(root, text = 'NAME', font='arial 12 bold', bg='white', fg='#ebb434').place(x= 30, y=20) Entry(root, textvariable = Name).place(x= 100, y=20) Label(root, text = 'PHONE NO.', font='arial 12 bold',bg='white', fg='#ebb434').place(x= 30, y=70) Entry(root, textvariable = Number).place(x= 130, y=70) Button(root,text=" ADD", font='arial 12 bold',bg='white', fg='#ebb434', command = AddContact).place(x= 50, y=110) root.mainloop()
def create_multiplication_table(width, height): output = "" num_chars = len(str(width*height)) + 1 for a in range(1, height+1): for b in range(1, width+1): product = a * b product_str = str(product) product_str = product_str.rjust(num_chars, ' ') output += product_str output += "\n\n" return output def process_input(raw_input): if int(raw_input) > 0: value = int(raw_input) return value def get_user_input(): values = [] for prompt in ('Width', 'Height'): raw_input = input(prompt + ": ") processed_input = process_input(raw_input) values.append(processed_input) return values def main(): success = False try: width, height = get_user_input() success = True except: print("\nUser input must be a positive integer.") if success: output = create_multiplication_table(width, height) print("\n\n" + output) if __name__ == "__main__": main()
#--- ALUNO - WALSAN JADSON --- #------- IMPORTANDO BIBLIOTECAS ------- import sys import timeit #------- DEFININDO FUNCOES ------- #-- 1 def countingSort(lista): a = lista print(a) b = [0] for i in range(0, len(a)): b.append(a[i]) k = buscaMaior(a) print "maior numero da lista: "+str(k) #cria o vetor auxiliar e zera os elementos c = [] for i in range(0, k+1): c.append(0) #incrementa for j in range(0, len(a)): c[a[j]] = c[a[j]] + 1 #acumula for i in range(1, k+1): c[i] = c[i] + c[i - 1] #ordena for j in range(len(a)-1, -1, -1): b[c[a[j]]] = a[j] c[a[j]] = c[a[j]] - 1 #retorno for i in range (0, len(lista)): lista[i] = b[i+1] def countingSort2(lista, chave): a = lista print(a) b = [0] for i in range(0, len(a)): b.append(a[i]) #cria o vetor auxiliar e zera os elementos c = [0] * 10 #incrementa for j in range(0, len(a)): indice = (a[j]/chave) c[ indice%10 ] += 1 #acumula for i in range(1, 10): c[i] += c[i-1] #ordena for j in range(len(a)-1, -1, -1): indice = a[j]/chave #b[c[a[j]]] = a[j] b[c[ indice%10 ]] = a[j] #c[a[j]] = c[a[j]] - 1 c[ indice%10 ] -= 1 #retorno for i in range (0, len(lista)): lista[i] = b[i+1] #-- 2 def radixSort(lista): maiorNumero = buscaMaior(lista) chave = 1 while maiorNumero/chave > 0: countingSort2(lista,chave) chave *= 10 def buscaMaior(lista): maiorNumero = 0 for i in range(0, len(lista)): if(lista[i] > maiorNumero): maiorNumero = lista[i] return maiorNumero #------- ENTRADA ------- ''' Exemplo de chamada a ser executada pelo terminal pra ser proccessada com o metodo 1 (countingSort) : >python Ordenacao03.py 1 entrada.txt ''' opcaoOrdenacao = int(sys.argv[1]) arquivoDeEntrada = sys.argv[2] arquivo = open(arquivoDeEntrada, 'r') #tamanho = int(raw_input()) tamanho = int(arquivo.readline()) lista = range(0,tamanho) for i in range(0,tamanho): #lista[i] = int(raw_input()) #conversao feita na leitura lista[i] = int(arquivo.readline()) #conversao feita na leitura tempo = [] #------- PROCESSAMENTO ------- # 1 - counting sort if opcaoOrdenacao == 1: t = timeit.Timer("countingSort(lista)","from __main__ import lista, countingSort") tempo = t.repeat(1,1) # 2 - radix sort if opcaoOrdenacao == 2: t = timeit.Timer("radixSort(lista)","from __main__ import lista, radixSort") tempo = t.repeat(1,1) #------- SAIDA ------- arquivoDeSaida = open("saida.txt", 'a') arquivoDeSaida.write("Entrada: "+str(arquivoDeEntrada)+"\n") if(opcaoOrdenacao == 1): arquivoDeSaida.write("Algoritmo: Counting Sort\n") if(opcaoOrdenacao == 2): arquivoDeSaida.write("Algoritmo: Radix Sort\n") print ("saida:") for i in lista: print (i) arquivoDeSaida.write(""+str(i)+"\n") print (tempo)
def get_length(dna): ''' (str) -> int Return the length of the DNA sequence dna. >>> get_length('ATCGAT') 6 >>> get_length('ATCG') 4 ''' return (len (dna)) def is_longer(dna1, dna2): ''' (str, str) -> bool Return True if and only if DNA sequence dna1 is longer than DNA sequence dna2. >>> is_longer('ATCG', 'AT') True >>> is_longer('ATCG', 'ATCGGA') False ''' if get_length(dna1) > get_length(dna2): return True else: return False def count_nucleotides(dna, nucleotide): ''' (str, str) -> int Return the number of occurrences of nucleotide in the DNA sequence dna. >>> count_nucleotides('ATCGGC', 'G') 2 >>> count_nucleotides('ATCTA', 'G') 0 ''' num_nucleotide = 0 for char in dna: if char in nucleotide: num_nucleotide = num_nucleotide + 1 return num_nucleotide def contains_sequence(dna1, dna2): ''' (str, str) -> bool Return True if and only if DNA sequence dna2 occurs in the DNA sequence dna1. >>> contains_sequence('ATCGGC', 'GG') True >>> contains_sequence('ATCGGC', 'GT') False ''' if dna2 in dna1: return True else: return False def is_valid_sequence(dna): ''' (str) -> bool Return True if and only if the nucleotides in the sequence are valid. >>> is_valid_sequence('ATCGTCA') True >>> is_valid_sequence('ATCGRNA') False ''' dna == 'ATCG'
import string import itertools import math class MyCrossword: __doc__ = "helper to solve crossword puzzles" def __init__(self): return def GeneratePermutation(self,A=None,B=None,C=None,D=None,E=None,F=None,G=None,H=None,I=None,J=None,K=None): if K is not None: for perm in self.GeneratePermutation(B,C,D,E,F,G,H,I,J,K): yield A + perm for perm in self.GeneratePermutation(A,C,D,E,F,G,H,I,J,K): yield B + perm for perm in self.GeneratePermutation(A,B,D,E,F,G,H,I,J,K): yield C + perm for perm in self.GeneratePermutation(A,B,C,E,F,G,H,I,J,K): yield D + perm for perm in self.GeneratePermutation(A,B,C,D,F,G,H,I,J,K): yield E + perm for perm in self.GeneratePermutation(A,B,C,D,E,G,H,I,J,K): yield F + perm for perm in self.GeneratePermutation(A,B,C,D,E,F,H,I,J,K): yield G + perm for perm in self.GeneratePermutation(A,B,C,D,E,F,G,I,J,K): yield H + perm for perm in self.GeneratePermutation(A,B,C,D,E,F,G,H,J,K): yield I + perm for perm in self.GeneratePermutation(A,B,C,D,E,F,G,H,I,K): yield J + perm for perm in self.GeneratePermutation(A,B,C,D,E,F,G,H,I,J): yield K + perm elif J is not None: for perm in self.GeneratePermutation(B,C,D,E,F,G,H,I,J): yield A + perm for perm in self.GeneratePermutation(A,C,D,E,F,G,H,I,J): yield B + perm for perm in self.GeneratePermutation(A,B,D,E,F,G,H,I,J): yield C + perm for perm in self.GeneratePermutation(A,B,C,E,F,G,H,I,J): yield D + perm for perm in self.GeneratePermutation(A,B,C,D,F,G,H,I,J): yield E + perm for perm in self.GeneratePermutation(A,B,C,D,E,G,H,I,J): yield F + perm for perm in self.GeneratePermutation(A,B,C,D,E,F,H,I,J): yield G + perm for perm in self.GeneratePermutation(A,B,C,D,E,F,G,I,J): yield H + perm for perm in self.GeneratePermutation(A,B,C,D,E,F,G,H,J): yield I + perm for perm in self.GeneratePermutation(A,B,C,D,E,F,G,H,I): yield J + perm elif I is not None: for perm in self.GeneratePermutation(B,C,D,E,F,G,H,I): yield A + perm for perm in self.GeneratePermutation(A,C,D,E,F,G,H,I): yield B + perm for perm in self.GeneratePermutation(A,B,D,E,F,G,H,I): yield C + perm for perm in self.GeneratePermutation(A,B,C,E,F,G,H,I): yield D + perm for perm in self.GeneratePermutation(A,B,C,D,F,G,H,I): yield E + perm for perm in self.GeneratePermutation(A,B,C,D,E,G,H,I): yield F + perm for perm in self.GeneratePermutation(A,B,C,D,E,F,H,I): yield G + perm for perm in self.GeneratePermutation(A,B,C,D,E,F,G,I): yield H + perm for perm in self.GeneratePermutation(A,B,C,D,E,F,G,H): yield I + perm elif H is not None: for perm in self.GeneratePermutation(B,C,D,E,F,G,H): yield A + perm for perm in self.GeneratePermutation(A,C,D,E,F,G,H): yield B + perm for perm in self.GeneratePermutation(A,B,D,E,F,G,H): yield C + perm for perm in self.GeneratePermutation(A,B,C,E,F,G,H): yield D + perm for perm in self.GeneratePermutation(A,B,C,D,F,G,H): yield E + perm for perm in self.GeneratePermutation(A,B,C,D,E,G,H): yield F + perm for perm in self.GeneratePermutation(A,B,C,D,E,F,H): yield G + perm for perm in self.GeneratePermutation(A,B,C,D,E,F,G): yield H + perm elif G is not None: for perm in self.GeneratePermutation(B,C,D,E,F,G): yield A + perm for perm in self.GeneratePermutation(A,C,D,E,F,G): yield B + perm for perm in self.GeneratePermutation(A,B,D,E,F,G): yield C + perm for perm in self.GeneratePermutation(A,B,C,E,F,G): yield D + perm for perm in self.GeneratePermutation(A,B,C,D,F,G): yield E + perm for perm in self.GeneratePermutation(A,B,C,D,E,G): yield F + perm for perm in self.GeneratePermutation(A,B,C,D,E,F): yield G + perm elif F is not None: for perm in self.GeneratePermutation(B,C,D,E,F): yield A + perm for perm in self.GeneratePermutation(A,C,D,E,F): yield B + perm for perm in self.GeneratePermutation(A,B,D,E,F): yield C + perm for perm in self.GeneratePermutation(A,B,C,E,F): yield D + perm for perm in self.GeneratePermutation(A,B,C,D,F): yield E + perm for perm in self.GeneratePermutation(A,B,C,D,E): yield F + perm elif E is not None: for perm in self.GeneratePermutation(B,C,D,E): yield A + perm for perm in self.GeneratePermutation(A,C,D,E): yield B + perm for perm in self.GeneratePermutation(A,B,D,E): yield C + perm for perm in self.GeneratePermutation(A,B,C,E): yield D + perm for perm in self.GeneratePermutation(A,B,C,D): yield E + perm elif D is not None: for perm in self.GeneratePermutation(B,C,D): yield A + perm for perm in self.GeneratePermutation(A,C,D): yield B + perm for perm in self.GeneratePermutation(A,B,D): yield C + perm for perm in self.GeneratePermutation(A,B,C): yield D + perm elif C is not None: for perm in self.GeneratePermutation(B,C): yield A + perm for perm in self.GeneratePermutation(A,C): yield B + perm for perm in self.GeneratePermutation(A,B): yield C + perm elif B is not None: for perm in self.GeneratePermutation(B): yield A + perm for perm in self.GeneratePermutation(A): yield B + perm elif A is not None: yield A else: #self.permutations.append(Baked) print("error") def PermutationGenerator(self,input): for char in input: yield char.upper() def GeneratePermutation_Test(self): chars =["a","b","c","d","e","f","g","h","i"] baked = "" self.GeneratePermutation(baked,chars[0],chars[1],chars[2],chars[3],chars[4],chars[5],chars[6],chars[7],chars[8]) return def GeneratePermutation_Jun28_1(self): #chars =["c","a","r","t","o","o","t","e","d"] #baked = "" #self.GeneratePermutation(baked,chars[0],chars[1],chars[2],chars[3],chars[4],chars[5],chars[6],chars[7],chars[8]) return def GeneratePermutation_Jun28_2(self): chars =["c","e","p","s","p","r","o","u","t","s"] baked = "" self.GeneratePermutation(baked,chars[0],chars[1],chars[2],chars[3],chars[4],chars[5],chars[6],chars[7],chars[8],chars[9]) return def GeneratePermutation_Jun28_3(self): chars =["b","r","u","i","s","e","d","l","o","f","t"] baked = "" self.GeneratePermutation(baked,chars[0],chars[1],chars[2],chars[3],chars[4],chars[5],chars[6],chars[7],chars[8],chars[9],chars[10]) return def CrossReference_Jun28_1(self): words = self.LoadWords() self.GeneratePermutation_Jun28_1() #indexs = self.IndexPermutation() chars =["c","a","r","t","o","o","t","e","d"] wordsDictionary = self.DictionaryOfWords() for perm in self.GeneratePermutation(chars[0],chars[1],chars[2],chars[3],chars[4],chars[5],chars[6],chars[7],chars[8]): if perm.lower() in wordsDictionary: print(perm + " in Dictionary " + "And permutation " + perm) ##for perm in self.permutations: ## startat = indexs[perm[0].lower()] ## for word in itertools.islice(words,startat,len(words)-1): ## if word[:7].lower() == perm[:7].lower(): ## print("Dictionary word is: " + word + " Permutation is: " + perm) ## if word[0] > perm[0]: ## break; return def CrossReference_Jun28_2(self): words = self.LoadWords() self.GeneratePermutation_Jun28_2() #indexs = self.IndexPermutation() wordsDictionary = self.DictionaryOfWords() for perm in self.permutations: if perm.lower() in wordsDictionary: print(perm + " in Dictionary " + "And permutation " + perm) return def CrossReference_Jun28_3(self): words = self.LoadWords() #self.GeneratePermutation_Jun28_3() indexs = self.IndexPermutation() print("indexed dictionary") chars =["b","r","u","i","s","e","d","l","o","f","t"] count = 0 for perm in self.GeneratePermutation(chars[0],chars[1],chars[2],chars[3],chars[4],chars[5],chars[6],chars[7],chars[8],chars[9],chars[10]): if perm[:3] not in indexs: continue startat = indexs[perm[:3]] count+=1 if count % 1000 == 0: print(count) #for word in itertools.islice(words,startat,None): # if perm[:8] == word[:8].lower(): # print("dictionary word " + word + " perumutatin is " + perm) # elif word[:3].lower() > perm[:3]: # break #chars =["b","r","u","i","s","e","d","l","o","f","t"] #for perm in self.GeneratePermutation(chars[0],chars[1],chars[2],chars[3],chars[4],chars[5],chars[6],chars[7],chars[8],chars[9],chars[10]): # startat = indexs[perm[0].lower()] # for word in itertools.islice(words,startat,len(words)-1) : # if perm[:7] == word[:7].lower(): # print("dictionary word " + word + " perumutatin is " + perm) # if word[0] > perm[0]: # break #chars =["b","r","u","i","s","e","d","l","o","f","t"] #wordsDictionary = self.DictionaryOfWords() #for perm in self.GeneratePermutation(chars[0],chars[1],chars[2],chars[3],chars[4],chars[5],chars[6],chars[7],chars[8],chars[9],chars[10]): # if perm.lower() in wordsDictionary: # print(perm + " in Dictionary " + "And permutation " + perm) return def CrossReference_Jun29_1(self): words = self.LoadWords() #indexs = self.IndexPermutation() chars =["g","l","e","n","p","l","a","i","n"] wordsDictionary = self.DictionaryOfWords() for perm in self.GeneratePermutation(chars[0],chars[1],chars[2],chars[3],chars[4],chars[5],chars[6],chars[7],chars[8]): if perm.lower() in wordsDictionary: print(perm + " in Dictionary " + "And permutation " + perm) ##for perm in self.permutations: ## startat = indexs[perm[0].lower()] ## for word in itertools.islice(words,startat,len(words)-1): ## if word[:7].lower() == perm[:7].lower(): ## print("Dictionary word is: " + word + " Permutation is: " + perm) ## if word[0] > perm[0]: ## break; return def CrossReference_Jun29_2(self): words = self.LoadWords() chars =["h","o","u","r","l","y","p","e","s","t"] wordsDictionary = self.DictionaryOfWords() for perm in self.GeneratePermutation(chars[0],chars[1],chars[2],chars[3],chars[4],chars[5],chars[6],chars[7],chars[8],chars[9]): if perm.lower() in wordsDictionary: print(perm + " in Dictionary " + "And permutation " + perm) return def CrossReference_Jun29_3(self): words = self.LoadWords() chars =["p","a","n","i","c","h","e","l","p","e","d"] wordsDictionary = self.DictionaryOfWords() for perm in self.GeneratePermutation(chars[0],chars[1],chars[2],chars[3],chars[4],chars[5],chars[6],chars[7],chars[8],chars[9],chars[10]): if perm.lower() in wordsDictionary: print(perm + " in Dictionary " + "And permutation " + perm) return def CrossReference_Jun30_1(self): words = self.LoadWords() #chars =["c","o","r","n","m","e","a","l","s] chars =["c","o","r","m","a"] wordsDictionary = self.DictionaryOfWords() for perm in self.GeneratePermutation(chars[0],chars[1],chars[2],chars[3],chars[4]): if perm.lower() in wordsDictionary: print(perm + " in Dictionary " + "And permutation " + perm) return def CrossReference_Jun30_2(self): words = self.LoadWords() chars =["d","r","i","v","e","n","w","i","f","e"] wordsDictionary = self.DictionaryOfWords() for perm in self.GeneratePermutation(chars[0],chars[1],chars[2],chars[3],chars[4],chars[5],chars[6],chars[7],chars[8],chars[9]): if perm.lower() in wordsDictionary: print(perm + " in Dictionary " + "And permutation " + perm) return def CrossReference_Jun30_3(self): words = self.LoadWords() chars =["t","r","i","m","t","h","e","l","e","g"] wordsDictionary = self.DictionaryOfWords() self.CrossReference_Jun30_3_Rec(wordsDictionary,chars,5,list()) #for i in range(9): # taken = [] # newchars = chars[:] # taken.append(newchars[i]) # del newchars[i] # for j in range(8): # taken2 = taken[:] # newchars2 = newchars[:] # taken2.append(newchars2[j]) # del newchars2[j] # for k in range(7): # taken3 = taken2[:] # newchars3 = newchars2[:] # taken3.append(newchars3[k]) # del newchars3[k] # for perm in self.GeneratePermutation(newchars3[0],newchars3[1],newchars3[2],newchars3[3],newchars3[4],newchars3[5]): # if perm.lower() in wordsDictionary: # print(perm + " in Dictionary " + "And permutation " + perm) # #and print ident word for 3 chars # for perm2 in self.GeneratePermutation(taken3[0],taken3[1],taken3[2]): # if perm2.lower() in wordsDictionary: # print("\t" + perm2) #for i in range(9): # for j in range(9): # if j==i: # break # newchars = chars[:] # del newchars[i] # del newchars[j] # for perm in self.GeneratePermutation(newchars[0],newchars[1],newchars[2],newchars[3],newchars[4],newchars[5],newchars[6]): # if perm.lower() in wordsDictionary: # print(perm + " in Dictionary " + "And permutation " + perm) #for perm in self.GeneratePermutation(chars[0],chars[1],chars[2],chars[3],chars[4]): # if perm.lower() in wordsDictionary: # print(perm + " in Dictionary " + "And permutation " + perm) return def CrossReference_Jun30_3_Rec(self,recWordsDictionary,recChars,recSplitNum, recSplitVals): wordsDictionary = recWordsDictionary chars = recChars splitNum = recSplitNum splitVals = recSplitVals if splitNum == 0: for perm in self.GeneratePermutation(chars[0],chars[1],chars[2],chars[3],chars[4]): if perm.lower() in wordsDictionary: #print(perm + " in Dictionary " + "And permutation " + perm) t = [] #and print ident word for 3 chars for perm2 in self.GeneratePermutation(splitVals[0],splitVals[1],splitVals[2],splitVals[3],splitVals[4]): if perm2.lower() in wordsDictionary: #print("\t" + perm2) t.append(perm2) if len(t) > 0: print(perm + " in Dictionary " + "And permutation " + perm) print("\t",end="") for str in t: print(str+",",end="") print("") return for i in range(len(chars)): newSplitVals = splitVals[:] newChars = chars[:] newSplitVals.append(newChars[i]) del newChars[i] self.CrossReference_Jun30_3_Rec(wordsDictionary,newChars,splitNum-1, newSplitVals) def CrossReference_Jun30_3_Rec_2(self,recWordsDictionary,recChars,recSplitNum, recSplitVals): wordsDictionary = recWordsDictionary chars = recChars splitNum = recSplitNum splitVals = recSplitVals for i in range(len(chars)): newchars = chars[:] newchars.remove(newchars[i]) #newchars. #CrossReference_Jun30_3_Rec_2 def CrossReference_July04_1(self): words = self.LoadWords() chars =["m","i","n","i","c","o","s","m","o","s"] wordsDictionary = self.DictionaryOfWords() for perm in self.GeneratePermutation(chars[0],chars[1],chars[2],chars[3],chars[4],chars[5],chars[6],chars[7],chars[8],chars[9]): if perm.lower() in wordsDictionary: print(perm + " in Dictionary " + "And permutation " + perm) return def CrossReference_July04_2(self): words = self.LoadWords() chars =["b","a","l","t","i","c","c","u","p"] wordsDictionary = self.DictionaryOfWords() self.CrossReference_July04_2_Rec(wordsDictionary,chars,6) return def CrossReference_July04_2_Rec(self,recWordsDictionary,recChars,recSplit): wordsDictionary = recWordsDictionary chars = recChars Split = recSplit count = 0 for perm in self.GeneratePermutation(chars[0],chars[1],chars[2],chars[3],chars[4],chars[5],chars[6],chars[7],chars[8]): count += 1 if count == math.factorial(len(chars)-Split): count = 0 if perm[:Split] in wordsDictionary: out = [] chars2 = perm[Split:] for perm2 in self.GeneratePermutation(chars2[0],chars2[1],chars2[2]): if perm2 in wordsDictionary: out.append(perm2) if len(out) > 0: print(perm[:Split] + " dictionary permuation " + perm[:Split]) print("\t", end="") for item in out: if out.index(item) == (len(out)-1): print(item,end="") else: print(item + ", ",end="") print("") def CrossReference_July04_3(self): words = self.LoadWords() chars =["r","i","p","w","e","t","h","e","a","p"] wordsDictionary = self.DictionaryOfWords() self.CrossReference_July04_3_Rec(wordsDictionary,chars,5) return def CrossReference_July04_3_Rec(self,recWordsDictionary,recChars,recSplit): wordsDictionary = recWordsDictionary chars = recChars Split = recSplit count = 0 for perm in self.GeneratePermutation(chars[0],chars[1],chars[2],chars[3],chars[4],chars[5],chars[6],chars[7],chars[8],chars[9]): count += 1 if count == math.factorial(len(chars)-Split): count = 0 if perm[:Split] in wordsDictionary: out = [] chars2 = perm[Split:] for perm2 in self.GeneratePermutation(chars2[0],chars2[1],chars2[2],chars2[3],chars2[4]): if perm2 in wordsDictionary: out.append(perm2) if len(out) > 0: print(perm[:Split] + " dictionary permuation " + perm[:Split]) #print(out) print("\t", end="") for item in out: print("(" +str(out.index(item))+")"+item + ", ",end="") print("") def CrossReference_July05_1(self): words = self.LoadWords() chars =["n","a","t","a","l","m","a","i","d"] wordsDictionary = self.DictionaryOfWords() for perm in self.GeneratePermutation(chars[0],chars[1],chars[2],chars[3],chars[4],chars[5],chars[6],chars[7],chars[8]): if perm.lower() in wordsDictionary: print(perm + " in Dictionary " + "And permutation " + perm) return def CrossReference_July05_2(self): words = self.LoadWords() chars =["o","p","e","n","a","i","r","m","a","n"] wordsDictionary = self.DictionaryOfWords() for perm in self.GeneratePermutation(chars[0],chars[1],chars[2],chars[3],chars[4],chars[5],chars[6],chars[7],chars[8],chars[9]): if perm.lower() in wordsDictionary: print(perm + " in Dictionary " + "And permutation " + perm) return def CrossReference_July05_3(self): words = self.LoadWords() chars =["t","i","t","h","e","r","i","s","e","r","s"] wordsDictionary = self.DictionaryOfWords() self.CrossReference_July05_3_Rec(wordsDictionary,chars,6) return def CrossReference_July05_3_Rec(self,recWordsDictionary,recChars,recSplit): wordsDictionary = recWordsDictionary chars = recChars Split = recSplit count = 0 for perm in self.GeneratePermutation(chars[0],chars[1],chars[2],chars[3],chars[4],chars[5],chars[6],chars[7],chars[8],chars[9],chars[10]): count += 1 if count == math.factorial(len(chars)-Split): count = 0 if perm[:Split] in wordsDictionary: print(perm[:Split] + " dictionary permuation " + perm[:Split]) def IndexPermutation_OLD(self): indexs = {} words = self.LoadWords() lowercases = list(string.ascii_lowercase) for letter in lowercases: for word in words: if letter == word[0].lower(): indexs[letter] = words.index(word) break return indexs def IndexPermutation(self): indexs = {} words = self.LoadWords() print("words length"+str(len(words))) lowercases = list(string.ascii_lowercase) alphabetIndexes = [] for char in lowercases: for char2 in lowercases: for char3 in lowercases: alphabetIndexes.append(char+char2+char3) print("ok") quickIndex = 0 for perm in alphabetIndexes: if alphabetIndexes.index(perm) % 100 == 0: print(alphabetIndexes.index(perm)) for word in itertools.islice(words, quickIndex, None): if len(word) < 3: continue elif perm < word[:3].lower(): break elif perm == word[:3].lower(): indexs[perm] = words.index(word) quickIndex = words.index(word) break return indexs def AlphabetIndexs(self): return def IndexWords(self): words = self.LoadWords() WordsIndex = {} lowercases = list(string.ascii_lowecase) return def DictionaryOfWords(self): words = self.LoadWords() wordsDictionary = {} for word in words: wordsDictionary[word.lower()] = 1 return wordsDictionary def LoadWords(self): with open('words.txt') as f: content = f.readlines() # you may also want to remove whitespace characters like `\n` at the end of each line content = [x.strip() for x in content] #make lowercase content = [x.lower() for x in content] content.sort(key = str.lower) return content mycrossword = MyCrossword() mycrossword.CrossReference_July04_3()
#Find wearther string is having Uniq Charectors are not from collections import Counter def isHavingUniq(s): C = Counter(s) for key in C: if C[key] != 1: return False return True s= 'abcde' print(isHavingUniq(s)) def uni_Char2(s): return len(set(s)) == len(s) s= 'abcdaf' print(uni_Char2(s)) def uniq_char3(s): char = set() for c in s: if c in char: return False else: char.add(c) return True s= 'abcdf' print(uniq_char3(s))
# Reverce the words in the sentence def revSentence(s): s1 = s.strip() print(s1) rString = '' sWords = s.split(' ') for word in reversed(sWords): rString = rString + " " + word.strip() return rString s = " This is the Best " def revSentence1(s): i = 0 lenght = len(s) space = [' '] words = [] while i < lenght: if s[i] not in space: wordstart = i while i < lenght and s[i] not in space: i += 1 words.append(s[wordstart:i]) i += 1 return " ".join(reversed(words)) rs = revSentence1(s) print(rs) rs = revSentence(s)
s = 'azcbobobegghakl' b = 0 if 'bob' in s: print('\'bob\' in string \'s\'') i = 0 for char in s: print('char ' + str(i) + ' in string \'s\': ' + char) if char == 'b': i += 1 for char in s[i]: print('Found letter \'b\', checking for \'o\'') if char == 'o': i += 1 for char in s[i]: print('Found letter \'o\', checking for last \'b\'') if char == 'b': b += 1 i += 1 for char in s[i]: print('Found last \'b\', added one to the bob tally, checking if followed by another \'o\'') if char == 'o': i += 1 for char in s[i]: print('Found another \'o\', checking for \'b\'') if char == 'b': b += 1 i += 1 print('Found \'b\', added one to the bob tally, that makes two, checking if followed by another \'o\'') else: i += 1 else: i += 1 else: i += 1 else: i += 1 print('Number of times bob occurs is: ' + str(b))
#-*-encoding=utf-8-*- class Kiyafetler(): def __init__(self): self.adi="Mızrak" self.ozellik="+8 Atak Gücü" def ozellikGoster(self): print("{} adlı eşyanın özelliği {}".format(self.adi,self.ozellik)) def kiyafetGiy(self,oyuncu): oyuncu.saldırıGucu += 8 oyuncu.ustundekiler.append(self.adi) def kiyafetCikar(self,oyuncu): oyuncu.saldırıGucu -= 8 oyuncu.ustundekiler.remove(self.adi) def mesaj(self): print("Tebrikler {} kıyafetini kazandınız.".format(self.adi)) class Hancer(Kiyafetler): def __init__(self): self.adi="Hançer" self.ozellik="+3 Atak Gücü" def kiyafetGiy(self,oyuncu): oyuncu.saldırıGucu += 3 oyuncu.ustundekiler.append(self.adi) def kiyafetCikar(self,oyuncu): oyuncu.saldırıGucu -=3 oyuncu.ustundekiler.remove(self.adi) class Kilic(Kiyafetler): def __init__(self): self.adi="Kılıç" self.ozellik="+5 Atak Gücü" def kiyafetGiy(self,oyuncu): oyuncu.saldırıGucu +=5 oyuncu.ustundekiler.append(self.adi) def kiyafetCikar(self,oyuncu): oyuncu.saldırıGucu -=5 oyuncu.ustundekiler.remove(self.adi) class Mizrak(Kiyafetler): def __init__(self): super().__init__() class KumasElbise(Kiyafetler): def __init__(self): self.adi="Kumaş Elbise" self.ozellik="+20 Can" def kiyafetGiy(self,oyuncu): oyuncu.can += 20 oyuncu.ustundekiler.append(self.adi) def kiyafetCikar(self,oyuncu): oyuncu.cn -= 20 oyuncu.ustundekiler.remove(self.adi) class TahtaKalkan(Kiyafetler): def __init__(self): self.adi="Tahta Kalkan" self.ozellik="+5 Defans Gücü" def kiyafetGiy(self,oyuncu): oyuncu.savunmaGucu += 5 oyuncu.ustundekiler.append(self.adi) def kiyafetCikar(self,oyuncu): oyuncu.savunmaGucu -= 5 oyuncu.ustundekiler.remove(self.adi) class Migfer(Kiyafetler): def __init__(self): self.adi="Miğfer" self.ozellik="+5 Savunma Gücü" def kiyafetGiy(self,oyuncu): oyuncu.savunmaGucu += 5 oyuncu.ustundekiler.append(self.adi) def kiyafetCikar(self,oyuncu): oyuncu.savunmaGucu -= 5 oyuncu.ustundekiler.remove(self.adi) class Bileklik(Kiyafetler): def __init__(self): self.adi="Bileklik" self.ozellik="+5 Can" def kiyafetGiy(self,oyuncu): oyuncu.can += 5 oyuncu.ustundekiler.append(self.adi) def kiyafetCikar(self,oyuncu): oyuncu.can -= 5 oyuncu.ustundekiler.remove(self.adi) class Ayakkabi(Kiyafetler): def __init__(self): self.adi="Ayakkabı" self.ozellik="+15 Can" def kiyafetGiy(self,oyuncu): oyuncu.can += 15 oyuncu.ustundekiler.append(self.adi) def kiyafetCikar(self,oyuncu): oyuncu.can -= 15 oyuncu.ustundekiler.remove(self.adi) class Kalkan(Kiyafetler): def __init__(self): self.adi="Kalkan" self.ozellik="+10 Savunma Gücü" def kiyafetGiy(self,oyuncu): oyuncu.savunmaGucu += 10 oyuncu.ustundekiler.append(self.adi) def kiyafetCikar(self,oyuncu): oyuncu.savunmaGucu -= 10 oyuncu.ustundekiler.remove(self.adi) class Bonus(Kiyafetler): def __init__(self): self.adi="At" self.ozellik="+20 Savunma Gucu" def kiyafetGiy(self,oyuncu): oyuncu.savunmaGucu += 20 def kiyafetCikar(self,oyuncu): oyuncu.savunmaGucu -=20 def mesaj(self): print("Tebrikler Bonus Ödülü Kazandınız") super().mesaj()
#-*-encoding=utf-8-*- import random class Karakterler(): def __init__(self): self.kasa=[] self.saldırıGucu=12 self.savunmaGucu=15 self.can=150 self.adi="Ana Karakter" self.ustundekiler=[] def saldir(self,rakip): self.savasSimilasyonu(rakip) def savasSimilasyonu(self,rakip): print("Saldıran Adı={}\nSaldırılan Adı={}".format(self.adi,rakip.adi)) print("Saldırı Gücü = {}\nSavunma Gücü = {}\nCan = {}".format(rakip.saldırıGucu,rakip.savunmaGucu,rakip.can)) sayac=0 while self.can>0 and rakip.can>0: if sayac % 2 == 0: saldiran_saldiri_puani = (int)((self.saldırıGucu/random.randint(1,6))-(rakip.savunmaGucu/random.randint(5,11))) if saldiran_saldiri_puani < 0: pass else: rakip.can -= saldiran_saldiri_puani sayac+=1 else : saldiri_puani= (int)((rakip.saldırıGucu/random.randint(3,7))-(self.savunmaGucu/random.randint(5,9))) #print("saldırı puanı = {} kalan can = {}".format(saldiri_puani,self.can)) if saldiri_puani < 0: pass else: self.can -= saldiri_puani sayac+=1 class AnaKarakter(Karakterler): def __init__(self): super().__init__() def kıyafetGiy(self,kiyafet,oyuncu): if len(self.kasa) == 0: print("Kasanız boş kıyafet giyemezsiniz.") else : kiyafet.kiyafetGiy(oyuncu) def kiyafetListele(self): if len(self.ustundekiler) == 0: print("Üstünüzde kıyafet yok") else: for i in self.ustundekiler: print("{:>20}".format(i)) def kasaListele(self): if len(self.kasa) == 0: print("Kasanızda kıyafet yok.") else: for i in self.kasa: print("{:>20}".format(i)) def ozellikGoster(self): print("Saldırı Gücü = {}\nSavunma Gücü = {}\nCan = {}".format(self.saldırıGucu,self.savunmaGucu,self.can)) class Yeniceri(Karakterler): def __init__(self): self.saldırıGucu=10 self.can=20 self.savunmaGucu=10 self.adi="Yeniçeri" class Baltali(Karakterler): def __init__(self): self.can=35 self.saldırıGucu=5 self.savunmaGucu=10 self.adi="Baltalı" class Atli(Karakterler): def __init__(self): self.can=25 self.saldırıGucu=13 self.savunmaGucu=15 self.adi="Atlı" class Mızraklı(Karakterler): def __init__(self): self.can=30 self.savunmaGucu=15 self.saldırıGucu=7 self.adi="Mızraklı"
In a town, there are N people labelled from 1 to N. There is a rumor that one of these people is secretly the town judge. If the town judge exists, then: The town judge trusts nobody. Everybody (except for the town judge) trusts the town judge. There is exactly one person that satisfies properties 1 and 2. You are given trust, an array of pairs trust[i] = [a, b] representing that the person labelled a trusts the person labelled b. If the town judge exists and can be identified, return the label of the town judge. Otherwise, return -1 class Solution: def findJudge(self, N: int, trust: List[List[int]]) -> int: n=1 count=0 a=[0]*N for i in range (0,N): a[i]=n n=n+1 for i in range (0,len(trust)): t=trust[i][0] a[t-1]=-1 for i in range (0,len(a)): if(a[i]!=-1): val=a[i] count=count+1 if(count!=1): return -1 else: count=0 for i in range (0,len(trust)): if(trust[i][1]==val): count=count+1 if(count==N-1): return val else: return -1
import random from menu import * from time import sleep from typing import * # passphrase generator randomly generates passphrase # from words found in textfile paramater # until min char count acheived # returns passphrase and wordcount of passphrase def Passphrase_Generator(): text_files = Menu() text_files.set_text_files() text_files.set_title('choose story from which a passphrase will be generated') text_files.display() index = int(input('$: ')) min_char = int(input('Enter minimum character length for passphrase $: ')) with open(text_files.selection[index], 'r') as f: # imports story string from textfile as story story = f.read() story_punctuated = story.split() # splits story's words into list story = list() # story is now empty so we can store words without punctuation punc = '.!?\"\',;:()-_[]{}1234567890' # punctuation and numbers defined in string for word in story_punctuated: # removes punctuation from words and appends to story newword = '' for letter in word: if letter not in punc: newword += letter story.append(newword.lower()) p_phrase = '' # empty string to store passphrase pass_list = [] while len(p_phrase) < min_char: # will continue to add random word to p_phrase until p_phrase is long enough choice = random.choice(story) p_phrase += choice pass_list.append(choice) print('') print('Passphrase generated:') print(p_phrase) print('') print(f'from the words:') print(pass_list) print('') print(f'Length: {len(p_phrase)}') print('') typing('Continue to main menu') print('') x = input('$: ')
# IoT program by MicroPython # https://github.com/rnsk/micropython-iot # # MIT License # Copyright (c) 2021 Yoshika Takada (@rnsk) """CdS library""" from machine import Pin, ADC class CdS: def __init__(self, pin_id): """Initialize Args: pin_id (int): センサーのPIN番号 """ self.adc = ADC(Pin(pin_id)) def read(self): """センサーの値を取得する Returns: integer: The return value. """ return self.adc.read() def is_greater_than(self, expected): """センサーの値を比較する expected < value が成立するかどうか Args: expected (int): 比較対象の数値 Returns: bool: The return Result of comparison. """ return expected < self.read() def is_greater_than_or_equal(self, expected): """センサーの値を比較する expected <= value が成立するかどうか Args: expected (int): 比較対象の数値 Returns: bool: The return Result of comparison. """ return expected <= self.read() def is_less_than(self, expected): """センサーの値を比較する expected > value が成立するかどうか Args: expected (int): 比較対象の数値 Returns: bool: The return Result of comparison. """ return expected > self.read() def is_less_than_or_equal(self, expected): """センサーの値を比較する expected >= value が成立するかどうか Args: expected (int): 比較対象の数値 Returns: bool: The return Result of comparison. """ return expected >= self.read()
# -*- coding: utf-8 -*- """ Created on Sun Apr 5 16:46:21 2020 @author: Shivam Sekra """ import numpy as np import cv2 # We point OpenCV's CascadeClassifier function to where our # classifier (XML file format) is stored face_classifier = cv2.CascadeClassifier('haarcascade_frontalface_default.xml') # Load our image then convert it to grayscale image = cv2.imread('face.png') gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) # Our classifier returns the ROI of the detected face as a tuple # It stores the top left coordinate and the bottom right coordiantes faces = face_classifier.detectMultiScale(gray, 1.3, 5) # When no faces detected, face_classifier returns and empty tuple if faces is (): print("No faces found") # We iterate through our faces array and draw a rectangle # over each face in faces for (x,y,w,h) in faces: cv2.rectangle(image, (x,y), (x+w,y+h), (127,0,255), 2) cv2.imshow('Face Detection', image) cv2.waitKey(0) cv2.destroyAllWindows()
dict1 = {0: "Zero", 1: "One", 2: "Two", 3: "Three", 4: "Four", 5: "Five"} ans = "y" while ans == "y" or ans == "Y" : val = input("Enter value: ") print("Value", val, end = " ") for k in dict1: if dict1[k] == val: print("Exists at", k) break else: print("Not found") ans = input("Want to check more values? (y/n): ")
#!/usr/bin/python ''' There are two sorted arrays nums1 and nums2 of size m and n respectively. Find the median of the two sorted arrays. The overall run time complexity should be O(log (m+n)). nums1 = [1, 3] nums2 = [2] The median is 2.0 nums1 = [1, 2] nums2 = [3, 4] The median is (2 + 3)/2 = 2.5 ''' class Solution(object): def findMedianSortedArrays(self, nums1, nums2): """ :type nums1: List[int] :type nums2: List[int] :rtype: float """ ans = nums1+nums2 ans.sort() if len(ans)%2 == 0: return (float(ans[len(ans)/2-1])+float(ans[len(ans)/2]))/2 else: return float(ans[len(ans)/2]) def findMedianSortedArrays2(self, nums1, nums2): """ O(log(m+n)) alogrithm divided into two part, [0,m] for nums1, and [0,n] for nums2 if want to divide into two equal part and max(left_part) <= min(right_part) there will be i for m and j will be i+j=(m+n)/2 - 1 """ m = len(nums1) n = len(nums2) A = nums1 B = nums2 if m>n: m,n,A,B=n,m,nums2,nums1 if n == 0: raise ValueError imin, imax, half_len = 0, m, (m+n+1)/2 while imin<=imax: i = (imin+imax)/2 j = half_len - i if i < m and B[j-1] > A[i]: imin = i+1 elif i > 0 and A[i-1] > B[j]: imax = i-1 else: if i == 0: max_of_left = B[j-1] elif j == 0: max_of_left = A[i-1] else: max_of_left = max(A[i-1],B[j-1]) if (m+n)%2 == 1: return max_of_left if i == m: min_of_right = B[j] elif j == n: min_of_right = A[i] else: min_of_right = min(A[i],B[j]) return (max_of_left+min_of_right)/2.0 if __name__ == "__main__": nums1 = [1,2] nums2 = [3,4] a = Solution() print a.findMedianSortedArrays(nums1,nums2)
import numpy as np class Collection: def __init__(self, values): self.values = values def get(self): if len(self.values) == 0: return None return np.random.choice(self.values) def all(self): return set(self.values) def c(values=list()): """ Creates a collection of values. :param values: list of values :return: a collection """ if isinstance(values, Collection): return values elif isinstance(values, list): return Collection(values) else: return Collection([values])
import numpy as np import string from .collection import c, Collection from typing import List ''' Generators should be classes that have at least two public methods with the following signatures generate_formula([String]) vocabulary(config) The first one should generate a random and valid mathematical expression in latex broken down into the smallest tokens possible (e.g. sin should be 's', 'i', 'n', instead of 'sin'). The second method should return all tokens that the generator can generate in a set. ''' class Config: """ Configs are used to modify the behaviour of generators.""" def __init__(self, separator='.', variables=c(['x', 'y']), multiplier=c()): self.separator = separator self.variables = variables self.multiplier = multiplier def vocabulary(self): return self.variables.all() | self.multiplier.all() | {self.separator} class FormulaGenerator(object): """ FormulaGenerators are objects that can generate formulas.""" def generate(self, tokens: List[str], config=Config()): """ Generates a formula. :param tokens: a list that contains tokens :param config: optional config object """ raise NotImplementedError("Class %s doesn't implement generate()" % self.__class__.__name__) def vocabulary(self, config=Config()): """ Creates a vocabulary that contains all tokens that this generator can create. :param config: optional config :return: set of tokens """ raise NotImplementedError("Class %s doesn't implement vocabulary()" % self.__class__.__name__) class WrappingFormulaGenerator(FormulaGenerator): """ Formula generators that wrap other generators. It can accept arbitrary generators in a list of generators. """ def __init__(self, generators: List[FormulaGenerator]): super().__init__() self.generators = generators def generate(self, tokens, config=Config()): super().generate(tokens, config) def vocabulary(self, config=Config()): vocab = set() for generator in self.generators: vocab = vocab | generator.vocabulary(config) return vocab class RandomTokenGenerator(FormulaGenerator): """ Generates a random token """ def __init__(self, token_collection: Collection): super().__init__() self.token_collection = token_collection def generate(self, tokens: List[str], config=Config()): tokens += [self.token_collection.get()] def vocabulary(self, config=Config()): return self.token_collection.all() class TokenGenerator(RandomTokenGenerator): """ Generates a single token. """ def __init__(self, token="x"): super().__init__(c(token)) @property def token(self): return self.token_collection.get() @token.setter def token(self, value): self.token_collection = c(value) class NumberGenerator(FormulaGenerator): """ Generates numbers. """ def __init__(self, n=5, p=0.05, p_real=0.1, p_neg=0.0): """ Create a NumberGenerator. The length of the number (number of decimals) is defined by a binomial distribution with parameters n and p. With probability p_real, it generates a real number. With probability p_neg it generates a negative number. :param n: binomial probability distribution parameter n :param p: binomial probability distribution parameter p :param p_real: probability of real number :param p_neg: probability of negative number """ self.n = n self.p = p self.p_real = p_real self.p_neg = p_neg def generate(self, tokens, config=Config()): if np.random.random() < self.p_neg: tokens += "-" self._generate_number(tokens) if np.random.random() < self.p_real: tokens += config.separator self._generate_number(tokens) def _generate_number(self, tokens): length = np.random.binomial(self.n, self.p) + 1 if length > 0: tokens += [str(np.random.random_integers(1, 9))] tokens += [str(np.random.random_integers(0, 9)) for _ in range(length - 1)] def vocabulary(self, config=Config()): vocab = {str(num) for num in range(0, 10)} if self.p_neg > 0: vocab = vocab | {'-'} if self.p_real > 0: vocab = vocab | {config.separator} return vocab class ExpressionGenerator(WrappingFormulaGenerator): """ Generates expressions. """ def __init__(self, generators: List[FormulaGenerator], operators: List[Collection] = list()): """ Creates an expression generator. It is defined by a list of generators, which are separated by the operators. :param generators: the list of generators :param operators: operators that separate the expression. Each operator is a collection of operators. """ super().__init__(generators) self.operators = operators self.randomize_order = False def generate(self, tokens, config=Config()): if self.randomize_order: np.random.shuffle(self.generators) for index in range(len(self.generators)): if index < len(self.operators) and self.operators[index] is not None: operator = self.operators[index].get() if operator is not None: tokens += [operator] self.generators[index].generate(tokens, config) def vocabulary(self, config=Config()): vocab = set() for generator in self.generators: vocab = vocab | generator.vocabulary(config) for operator in self.operators: if operator is not None: vocab = vocab | operator.all() if None in vocab: vocab.remove(None) return vocab class CommandGenerator(WrappingFormulaGenerator): """ Generates formulas with commands and parameters. """ def __init__(self, name, generators=list()): """ Create a CommandGenerator. :param name: name of the command :param generators: parameter generators, separated by curly braces {} """ super().__init__(generators) self.name = name def generate(self, tokens, config=Config()): tokens += [self.name] for generator in self.generators: tokens += "{" generator.generate(tokens, config) tokens += "}" def vocabulary(self, config=Config()): vocab = {self.name} for generator in self.generators: vocab = vocab | generator.vocabulary(config) return vocab class CallableGenerator(WrappingFormulaGenerator): """ Callable generator e.g. sin(x) or f(a,b). """ def __init__(self, name, generators, brackets): """ Creates a CallableGenerator. :param name: name of the generator :param generators: parameters :param brackets: brackets to use """ super().__init__(generators) self._name = c(name) self.brackets = brackets @property def name(self): """ Get the name of the callable e.g. sin """ return self._name @name.setter def name(self, value): """ Set the name of the callable e.g. cos """ self._name = c(value) def generate(self, tokens, config=Config()): if self.name is not None: name = self.name.get() if name is not None: tokens.append(name) tokens += [self.brackets[0]] for index in range(len(self.generators)): self.generators[index].generate(tokens, config) if index < len(self.generators) - 1: tokens += [","] tokens += [self.brackets[1]] def vocabulary(self, config=Config()): vocab = {self.brackets[0], self.brackets[1]} if self.name is not None: for name in self.name.all(): if name is not None: vocab.add(name) for generator in self.generators: vocab = vocab | generator.vocabulary(config) if len(self.generators) > 1: vocab = vocab | {","} if None in vocab: vocab.remove(None) return vocab class RelationGenerator(ExpressionGenerator): """ Relation generator with two left and right sides. """ def __init__(self, operator=c("="), left_side: FormulaGenerator = TokenGenerator(), right_side: FormulaGenerator = TokenGenerator()): super().__init__([left_side, right_side], [operator]) class VariableGenerator(FormulaGenerator): """ Generates variables. """ def __init__(self, variable_wrapper: WrappingFormulaGenerator = None, scale_generator: FormulaGenerator = None): """ Create a VariableGenerator. :param variable_wrapper: :param scale_generator: token generator that is appended before the variable """ self.variable_wrapper = variable_wrapper self.scale_generator = scale_generator def generate(self, tokens, config=Config()): if self.scale_generator is not None: self.scale_generator.generate(tokens, config) if config.multiplier is not None: multiplier = config.multiplier.get() if multiplier is not None: tokens += [multiplier] if self.variable_wrapper is not None: self.variable_wrapper.generators = [TokenGenerator(config.variables.get())] self.variable_wrapper.generate(tokens, config) else: tokens += [config.variables.get()] def vocabulary(self, config=Config()): vocab = set() if self.scale_generator is not None: vocab = vocab | self.scale_generator.vocabulary(config) if config.multiplier is not None: vocab = vocab | config.multiplier.all() if self.variable_wrapper is not None: vocab = vocab | self.variable_wrapper.vocabulary(config) vocab = vocab | config.variables.all() return vocab class PowerGenerator(WrappingFormulaGenerator): """ Generates power expressions. """ def __init__(self, generator: FormulaGenerator = NumberGenerator(), power_generator: FormulaGenerator = TokenGenerator("2")): """ Create a PowerGenerator object. :param generator: object to wrap with power :param power_generator: the expression in the power term """ super().__init__([generator]) self.power_generator = power_generator def generate_formula(self, tokens, config): new_tokens = [] self.generators[0].generate(new_tokens, config) if len(new_tokens) > 1: tokens += "(" tokens += new_tokens if len(new_tokens) > 1: tokens += ")" tokens += ["^", "{"] self.power_generator.generate(tokens, config) tokens += ["}"] def vocabulary(self, config=Config()): vocab = {"(", ")", "^", "{", "}"} vocab = vocab | self.generators[0].vocabulary(config) vocab = vocab | self.power_generator.vocabulary(config) return vocab # These build on the ones before class PolynomialGenerator(FormulaGenerator): """ Generates polynomial expressions. """ def __init__(self, length=c([2, 3, 4]), p_miss=0.1, p_minus=0.3): """ Creates a Polynomial Generator object. :param length: collection of lengths :param p_miss: probability of missing a term :param p_minus: probability of having a negative term """ self.length = length self.p_miss = p_miss self.p_minus = p_minus self.power = TokenGenerator("1") self.power_gen = PowerGenerator(TokenGenerator(), power_generator=self.power) self.number_gen = NumberGenerator() self.var_gen = VariableGenerator(self.power_gen, self.number_gen) def generate(self, tokens: List[str], config=Config()): new_tokens = [] length = self.length.get() for ind in range(length, 0, -1): if not (ind == 2 and length == 2) and np.random.random() < self.p_miss: continue if np.random.random() < self.p_minus: new_tokens += ["-"] elif len(new_tokens) > 0: new_tokens += ["+"] if ind > 2: self.power.token = str(ind - 1) self.var_gen.variable_wrapper = self.power_gen self.var_gen.generate(new_tokens, config) elif ind == 2: self.var_gen.variable_wrapper = None self.var_gen.generate(new_tokens, config) else: self.number_gen.generate(new_tokens, config) tokens += new_tokens def vocabulary(self, config=Config()): vocab = {"+"} | self.var_gen.vocabulary(config) if self.p_minus > 0: vocab = vocab | {"-"} return vocab class RandomGenerator(FormulaGenerator): """ A collection of generators. """ def __init__(self, generators: List[FormulaGenerator]): """ Create a RandomGenerator. :param generators: a list of generators """ self.generators = generators def generate(self, tokens: List[str], config=Config()): generator = np.random.choice(self.generators) generator.generate(tokens, config) def vocabulary(self, config=Config()): vocab = set() for generator in self.generators: vocab = vocab | generator.vocabulary(config) return vocab class GibberishGenerator(WrappingFormulaGenerator): """ Generates just unintelligible gibberish. """ def __init__(self, generators, min_length=4, max_length=20, brckt_p=0.2): super().__init__(generators) self.min_length = min_length self.max_length = max_length self.brckt_p = brckt_p self.brackets = [('(', ')'), ('[', ']'), ('{', '}')] def generate(self, tokens: List[str], config=Config()): length = np.random.randint(self.min_length, self.max_length) if length > 3 and np.random.uniform() < self.brckt_p: opening_bracket = np.random.randint(0, length - 2) closing_bracket = np.random.randint(opening_bracket, length - 1) else: opening_bracket = -2 closing_bracket = -2 bracket_idx = np.random.choice(len(self.brackets)) bracket = self.brackets[bracket_idx] for i in range(0, length): if i == opening_bracket: tokens += bracket[0] elif i == closing_bracket: tokens += bracket[1] else: idx = np.random.choice(len(self.generators)) generator = self.generators[idx] generator.generate(tokens, config) def vocabulary(self, config=Config()): tokens = super().vocabulary(config) for bracket in self.brackets: tokens |= {bracket[0], bracket[1]} return tokens def gibberish_generator(min_length=4, max_length=20, brckt_p=0.2): random_tokens = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '\\Delta', '\\alpha', '\\beta', '\\cos', '\\div', '\\exists', '\\forall', '\\gamma', '\\geq', '\\gt', '\\in', '\\infty', '\\int', '\\lambda', '\\ldots', '\\leq', '\\lim', '\\log', '\\lt', '\\mu', '\\neq', '\\phi', '\\pi', '\\pm', '\\prime', '\\rightarrow', '\\sigma', '\\sin', '\\sqrt', '\\sum', '\\tan', '\\theta', '\\times', '!', '+', ',', '-', '.', '/', '='] generator = RandomTokenGenerator(c(random_tokens)) single_token_gen = RandomGenerator([uppercase_character(), lowercase_character(), generator]) return GibberishGenerator([single_token_gen], min_length, max_length, brckt_p) square_brackets = ("[", "]") round_brackets = ("(", ")") curly_brackets = ("{", "}") def numbers(): numbers = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'] return RandomTokenGenerator(c(numbers)) def uppercase_character(): characters = ['A', 'B', 'C', 'E', 'F', 'G', 'H', 'I', 'L', 'M', 'N', 'P', 'R', 'S', 'T', 'V', 'X', 'Y'] return RandomTokenGenerator(c(characters)) def lowercase_character(): characters = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'] return RandomTokenGenerator(c(characters)) def function_generator(name, generators): return CallableGenerator(name, generators, round_brackets) def fraction_generator(numerator, denominator): return CommandGenerator("\\frac", [numerator, denominator]) def random_simple_expression(): num = NumberGenerator() var1 = VariableGenerator(scale_generator=num) var2 = VariableGenerator() rand = RandomGenerator([var1, var2]) expr = ExpressionGenerator([rand, num], operators=[c(None), c(["+", "-"])]) expr.randomize_order = True return expr def random_simple_equation(): num = NumberGenerator() var = VariableGenerator(scale_generator=num) expr = ExpressionGenerator([var, num], [c([None, "+", "-"]), c(["+", "-"])]) expr.randomize_order = True rel = ExpressionGenerator([expr, num], [c(None), c(["=", "\\leq", "\\geq"])]) return rel def random_coord(): num = NumberGenerator(p_neg=0.5) co = function_generator(None, [num, num]) generators = [] for character in string.ascii_uppercase: generators.append(TokenGenerator(character)) rand = RandomGenerator(generators) return RelationGenerator(operator=c("="), left_side=rand, right_side=co) def random_fraction(): num = NumberGenerator(p_neg=0.5) pow_num = NumberGenerator(0, p_real=0, p_neg=0.4) power_generator = PowerGenerator(power_generator=pow_num) var = VariableGenerator(scale_generator=num, variable_wrapper=power_generator) fraction = fraction_generator(var, pow_num) tok = TokenGenerator("y") rel = ExpressionGenerator(generators=[tok, RandomGenerator([fraction])], operators=[c(None), c("=")]) return rel def random_long_expression_no_frac(): commands = ["sin", "cos", "tan"] simple = random_simple_expression() command_gen = function_generator(c(commands), [simple]) random = RandomGenerator([command_gen, simple]) return random def _random_long_expr_item(): expression = random_long_expression_no_frac() frac = fraction_generator(expression, expression) return RandomGenerator([expression, frac]) def random_long_expression(): generators = [] for i in range(4, 8): expr = ExpressionGenerator(generators=[_random_long_expr_item() for _ in range(i)], operators=[c(None)] + [c(["+", "-"]) for _ in range(i - 1)]) generators.append(expr) return RandomGenerator(generators) def random_square_root(): simple = random_simple_expression() return CommandGenerator("\\sqrt", [simple]) def random_generator(): generators = [random_simple_expression()] # generators = [random_simple_expression(), random_polynomial(), random_coord(), # random_fraction(), random_long_expression_no_frac()]\ # , almost_absolutely_random_generator(), # almost_absolutely_random_generator(), almost_absolutely_random_generator()] return RandomGenerator(generators) def almost_absolutely_random_generator(): long_random_generator = gibberish_generator() short_random_generator = gibberish_generator(2, 5) very_short_generator = gibberish_generator(1, 2) bs_frac_generator = fraction_generator(short_random_generator, short_random_generator) random_frac_or_nofrac = RandomGenerator([short_random_generator, bs_frac_generator]) relation_generator = RelationGenerator(left_side=random_frac_or_nofrac, right_side=random_frac_or_nofrac) power_generator = PowerGenerator(short_random_generator, very_short_generator) longer_power = ExpressionGenerator(generators=[power_generator, very_short_generator]) power_relation = RelationGenerator(left_side=random_frac_or_nofrac, right_side=longer_power) generators = [long_random_generator, bs_frac_generator, short_random_generator, bs_frac_generator, relation_generator, power_generator, longer_power, power_relation] return RandomGenerator(generators) def single_token_generator(): generators = [] for char in range(0, 9): generators.append(TokenGenerator(str(char))) for operators in ['=', '+', '-', '.', '\\times', '(', ')', ',']: generators.append(TokenGenerator(operators)) for char in range(ord('a'), ord('z') + 1): generators.append(TokenGenerator(chr(char))) return RandomGenerator(generators) def simple_number_operation_generator() -> GibberishGenerator: numbers = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '-', '+'] token = RandomTokenGenerator(c(numbers)) return GibberishGenerator([token], 1, 6, 0)
from PIL import Image from k_means import k_means if __name__ == '__main__': print("Coloque el nombre de la imagen a comprimir:") imageName = input() #imageName = "stardewValley.png" # Se carga la imagen y se obtienen los valores de sus pixeles # (requiere pillow en python3, PIL en python2) image = Image.open(imageName) pixels = image.load() # Se obtiene el tamaño de la imagen width,height = image.size # Se obtiene el nombre y la extension de la imagen name,extension = imageName.split(".") # Se inicializa una lista de pixeles pixelList = [[(0,0,0) for i in range(height)] for j in range(width)] # Se aplana la matriz de pixeles en la lista for i in range(width): for j in range(height): pixelList[i][j] = pixels[i,j] flattenedPixels = [i for sublist in pixelList for i in sublist] # Se corre k_means para cada K y se cambian los pixeles # luego se guarda la imagen. # (No se cambia la lista aplanada de pixeles). for i in [2, 4, 8, 16, 32, 64, 128]: clusters,mapping = k_means(i,flattenedPixels,compression=True) for w in range(width): for h in range(height): pixels[w,h] = clusters[mapping[w*height+h]] image.save("ImagenesComprimidas/"+name + "K" + str(i) + "." + extension)
#!/usr/bin/env python2 # -*- coding: utf-8 -*- """ Created on Fri Apr 17 11:16:22 2020 @author: ivan """ #bilo je python3 #PART 1 - BUILDING A CNN from keras.models import Sequential from keras.layers import Conv2D from keras.layers import MaxPooling2D from keras.layers import Flatten from keras.layers import Dense #Initializing the CNN classifier = Sequential() #kreiramo objekt klase Sequential #1 sloj. konvolucija classifier.add(Conv2D(32,(3,3),input_shape = (64,64,3), activation ='relu')) #32 - broj filtera, 3x3 dimanzije filtera #kolko ima feature detectora, tolko ima i feature mapa # input shape - expected format input image, kasnije cemo ih skalirati na tu veličinu #2. sloj - pooling classifier.add(MaxPooling2D(pool_size = (2,2))) #uglavnom je 2*2 #jos jedan sloj da dobimo vecu acc #sve isto samo nema vise input shape classifier.add(Conv2D(32,(3,3), activation ='relu')) #sve isto samo nema vise input shape, mogla bi staviti 64 classifier.add(MaxPooling2D(pool_size = (2,2))) #3.sloj - flatten classifier.add(Flatten()) #4. korak fully connected layer , samo cemo hidden i output classifier.add(Dense(units = 128, kernel_initializer = 'uniform', activation = 'relu')) #128 - kolko ih ima u skrivenom, eksperimantalno, ni premalo ni previse, oko 100 je oke, uzimamo potenciju 2 classifier.add(Dense(units = 5, kernel_initializer = 'uniform', activation = 'softmax')) #da je binarno- sigmoid #pazi, promijeni ovjde unit s obzirom na to kolko imas klasa #compile classifier.compile(optimizer = 'adam', loss = 'categorical_crossentropy', metrics = ['accuracy']) #da je binary outcome bila bi binary_crossentropy ## kopirano sa https://keras.io/preprocessing/image/ #image augumenttaion, ujedno i fitting i testing from keras.preprocessing.image import ImageDataGenerator #image augumentation part train_datagen = ImageDataGenerator(rescale=1./255, #tu je ovaj rescale, slicno ko feature scaling prije, sve vrijdnosti pixea ce biti [0,1] shear_range=0.2, #shearing - smicanje, transvection zoom_range=0.2, #random zoom na sliku horizontal_flip=True) #postoji jos svasta, i vertical flip, pogledaj dokumntaciju test_datagen = ImageDataGenerator(rescale=1./255) #ovo ce samo napraviti za test training_set = train_datagen.flow_from_directory( #napraviti ce cijeli train_Set 'marsela_dataset/1026_1/1026/dataset2/training_set', #ovo tu treba promijeniti, odkud cemo uzet slike, ne treb cijeli path jer je dataset u working direcotry target_size=(64, 64), #i ovo, bilo je 150, velicina slike koju ocekujes u cnn modelu , a gore smo napisali da zelimo 64x64 batch_size=32, #broj slika nakon kojih ce tezine biti updatane, a sadrze te izoblicene slike class_mode='categorical') #dvije klase binary test_set = test_datagen.flow_from_directory('marsela_dataset/1026_1/1026/dataset2/test_set', target_size=(64, 64), batch_size=32, class_mode='categorical') #treniranje i testiranje classifier.fit_generator(training_set, steps_per_epoch=1235, #broj slika koje imamo u training setu epochs=25, validation_data=test_set, validation_steps=140) #broj slika u test setu classifier.save("model2_1026.h5") #### prediction from keras.models import load_model from keras.preprocessing import image import numpy as np #classifier = load_model('model_1026.h5') test_image = image.load_img("predict/-0.002/-0.002_frame_828.jpg", target_size = (64,64)) #mora biti iste velicine ko train. uzela iz 0.002 #sad je size (64,64), 2D , treba bi 64x64x3 test_image = image.img_to_array(test_image) #sad je 3D #classifier.predict(test_image) #ovo ne bude proslo, trazi 4tu dimenziju, tj batch. #predict prima inpute samo u batchu. ovo bude batch koji ima jednu sliku test_image = np.expand_dims(test_image, axis = 0) #axis je pozicija indexa u dimanziji, axis = 0 znaci da dodajemo prvi index, a ic ce na prvo mjesto jer tako trazi predict #sad je (1,64,64,3) result =classifier.predict(test_image) #dobim array [0,0,0,0,1] #korisiti atribut class_indicies da vidis kak je to mapirano indexi_klasa = training_set.class_indices # dobim disctionary {'-0.0005': 1, '-0.0015': 3, '-0.0': 0, '-0.001': 2, '-0.002': 4} result_list = result.tolist() result_list = result_list[0] prediction_index = result_list.index(1.0) if prediction_index == 0: prediction = 0.0 elif prediction_index == 1: prediction = 0.0005 elif prediction_index == 2: prediction = 0.001 elif prediction_index == 3: prediction = 0.0015 elif prediction_index ==4: prediction = 0.002 else: prediction = 'error' print (prediction)
s = int(input("อัตราเร็วของการเคลื่อนที่ :")) t = int(input("เวลาที่วัตถุใช้เคลื่อนที่จริง :")) v = int(s/t) print (v, "km/h")
from math import sqrt, pow def length(a, b): return sqrt(pow(b.x - a.x, 2) + pow(b.y - a.y, 2)) def triangle_area(t): a, b, c = (length(t.a, t.b), length(t.b, t.c), length(t.c, t.a)) s = (a + b + c) / 2 return sqrt(s * (s - a) * (s - b) * (s - c))
class Patient(object): def __init__(self, id_number, name, allergies=[], bed_number='none'): self.id_number = id_number self.name = name self.allergies = allergies self.bed_number = bed_number class Hospital(object): def __init__(self, name, capacity, patients=[]): self.name = name self.capacity = capacity self.patients = patients self.open_bed_numbers = range(self.capacity) for i in range(len(self.patients)): self.patients[i].bed_number = i self.open_bed_numbers.pop(0) def admit(self, patient): if len(self.patients) >= self.capacity: print 'Sorry, the hospital is full! :(' else: patient.bed_number = self.open_bed_numbers.pop(0) self.patients.append(patient) print 'Patient ID #{} was successfully admitted'.format(patient.id_number) return self def discharge(self, patient_id_number): for i, patient in enumerate(self.patients): if patient.id_number == patient_id_number: self.open_bed_numbers.append(patient.bed_number) patient.bed_number = 'none' self.patients.pop(i) print 'Patient ID #{} was discharged'.format(patient.id_number) break return self p0 = Patient(0, 'charlie') p1 = Patient(1, 'emily') p2 = Patient(2, 'bobby') p3 = Patient(3, 'anna') patients = [p0, p1, p2] hospital = Hospital('Awesome Hospital', 6, patients) print hospital.patients[0].name print hospital.patients[0].bed_number print 'open hospital beds:', hospital.open_bed_numbers print '\n' hospital.admit(p3) print 'open hospital beds:', hospital.open_bed_numbers print 'admitted patient name: ', hospital.patients[3].name print 'admitted patient bed number: ', hospital.patients[3].bed_number print '\n' hospital.discharge(2) print '# of patients:', len(hospital.patients) print 'open hospital beds:', hospital.open_bed_numbers
## TODO: define the convolutional neural network architecture import torch import torch.nn as nn import torch.nn.functional as F # can use the below import should you choose to initialize the weights of your Net import torch.nn.init as I class Net(nn.Module): def __init__(self): """ Neural network defined based on NaimeshNet Network takes in square (same width/height), grayscale image Network ends with a linear layer representing the keypoints with 136, (2 for each 68 (x, y) pairs) """ # Inherit attributes, methods from nn.Module class super(Net, self).__init__() # Convolutional layers # 1 input image channel (grayscale), 32 output channels # 4x4 square convolutional kernel # output size = (W-F)/S + 1 = (224-4)/1 + 1 = 221 # output Tensor for one image will have dimensions (32, 221, 221) # after one pool layer, (32, 110, 110), rounded down self.conv1 = nn.Conv2d(1, 32, 4) # second conv layer: 32 inputs, 64 outputs # 3x3 square convolutional kernel # output size: (W-F)/S + 1 = (110-3)/1 + 1 = 108 # output Tensor: (64, 108, 108) # output Tensor after maxpooling: (64, 54, 54) self.conv2 = nn.Conv2d(32, 64, 3) # third conv layer: 64 inputs, 128 outputs # 2x2 square convolutional kernel # output size: (W-F)/S + 1 = (54-2)/1 + 1 = 53 # output Tensor: (128, 53, 53) # output Tensor after maxpooling: (128, 26, 26), rounded down self.conv3 = nn.Conv2d(64, 128, 2) # fourth conv layer: 128 inputs, 256 outputs # 1x1 square convolution kernel # output size: (W-F)/S + 1 = (26-1)/1 + 1 = 26 # output tensor: (256, 26, 26) # output Tensor after maxpooling: (256, 13, 13) self.conv4 = nn.Conv2d(128, 256, 1) # Fully-connected (dense) linear layers # 256 outputs * 13x13 filtered/pooled map size self.fc1 = nn.Linear(256*13*13, 1000) self.fc2 = nn.Linear(1000, 1000) self.fc3 = nn.Linear(1000, 136) # Maxpooling layer with shape(2,2) self.pool = nn.MaxPool2d(2,2) # Dropout layers # Note that dropout layers could be nn.Dropout2d (for convolutional # part of network) nn.Dropout (for linear parts of the network) self.dropout1 = nn.Dropout2d(p=0.1) self.dropout2 = nn.Dropout2d(p=0.2) self.dropout3 = nn.Dropout2d(p=0.3) self.dropout4 = nn.Dropout2d(p=0.4) self.dropout5 = nn.Dropout(p=0.5) self.dropout6 = nn.Dropout(p=0.6) def forward(self, x): """Defining feedforward behavior inspired by NaimeshNet""" # Convolutional/pooling layer 1 x = self.pool(F.relu(self.conv1(x))) x = self.dropout1(x) # Convolutional/pooling layer 2 x = self.pool(F.relu(self.conv2(x))) x = self.dropout2(x) # Convolutional/pooling layer 3 x = self.pool(F.relu(self.conv3(x))) x = self.dropout3(x) # Convolutional/pooling layer 4 x = self.pool(F.relu(self.conv4(x))) x = self.dropout4(x) # Flatten x for linear, dense layers x = x.view(x.size(0), -1) # Fully-connected (dense) layer 1 x = F.relu(self.fc1(x)) x = self.dropout5(x) # Fully-connected (dense) layer 2 x = F.relu(self.fc2(x)) x = self.dropout6(x) # Final fully-connected layer to output x = self.fc3(x) # a modified x, having gone through all the layers of your model, should be returned return x
for _ in range(int(input())): N=int(input()) while N!=1: print(int(N),end=' ') if N%2==0: N=N/2 else: N=(N*3)+1 print(int(N))
import math print("ievadi garumu centimetros") g = int(input()) print("ievadi svaru kilogramos") s = int(input()) print(s / g**2 * 100)
# Python program to display all the prime numbers within an interval lower = 900 #lower limit upper = 950 # upper limit print("Prime numbers between", lower, "and", upper, "are:") for num in range(lower, upper + 1): # all prime numbers are greater than 1 if num > 1: for i in range(2, num): if (num % i) == 0: break else: print(num)
#Escribe un programa que permita leer un arreglo de n datos enteros, luego imprime de manera invertida. Guarde el archivo como Arreglo.py import random import numpy as np # a = np.array([ # [1, 2, 3], # [4, 5, 6] # ]) # b = np.array([ # [0, 0, 0], # [0, 0, 0] # ]) # # Recorrer filas # for i in range(len(a)): # # Recorrer columnas # for j in range(len(a[0])): # b[i][j] = a[i][j] # for z in b: # print(z) matriz=[] def iniciar_matriz(a, b): for fila in range(a): matriz.append([0]*b) for i in range(a): for j in range(b): matriz[i][j]=random.randint(1,20) def mostrar_matriz(): print("La matriz resultantes es: ") for i in matriz: print(i) #region Main filas = int(input("Escriba el numero de filas: ")) columnas = int(input("Escriba el numero de columnas: ")) iniciar_matriz(filas, columnas) mostrar_matriz() #endregion Main # a = np.array([ # [4, 5, 6] # ]) # print(a[:, :]) # print(a[0, ::-1]) # Escribe un programa que lea una matriz de longitud n x m, # luego imprime la matriz en consola similar al referente de la imagen. Guarda el archivo como LecturaMatriz.py # while counter < 10: # numero = input("Escriba el numero para agregar a la lista: ") # listaenteros.append(numero) # counter += 1
import time # Funcion menu def menu(): print("================================= Menu de Opciones =================================") print("0. Salir") print("1. Saludar") print("2. Calcular si un número es par") print("3. Calcular el promedio de 5 notas") print("4. Calcular el porcentaje") print("5. Elevar a una potencia") print("6. Calcular el módulo") print("====================================================================================") # Función Saludar def saludar(): saludo = 'Saludos desde Python' print (saludo) #region Main opcion = None while opcion != 0: menu() opcion = int(input("Seleccione una opción: ")) if opcion >= 0 and opcion <= 6: if opcion == 1: saludar() # Llamo a la fución saludar() time.sleep(2) elif opcion == 2: print("Calcular número par") # Llamo a la función calcularpar() time.sleep(2) elif opcion == 3: print("Calcular promedio de 5 notas") # Llamo a la función calcularpromedio() time.sleep(2) elif opcion == 4: print("Calcular porcentaje") # Llamo a la función calcularporcentaje() time.sleep(2) elif opcion == 5: print("Elevar a una potencia") # Llamo a la función calcularpotencia() time.sleep(2) elif opcion == 6: print("Calcular el módulo") # Llamo a la función calcularmodulo() time.sleep(2) else: print("Opción no válida") time.sleep(2) print("Saliendo del programa") time.sleep(2) exit() #endregion Main
# Crear una lista y almacenar 10 enteros pedidos por teclado. Eliminar todos los elementos que sean iguales al número entero 5. # listaenteros = list() # counter = 0 # while counter < 10: # numero = input("Escriba el numero para agregar a la lista: ") # listaenteros.append(numero) # counter += 1 # print(listaenteros) # Crear una lista de 5 enteros y cargarlos por teclado. # Borrar los elementos mayores o iguales a 10 # y generar una nueva lista con dichos valores listaenteros = list() counter = 1 while counter <= 5: numero = int(input(f"Escriba el numero {counter} para agregar a la lista: ")) listaenteros.append(numero) # Agregando elementos a la lista counter += 1 print(f"Imprimiendo lista creada: {listaenteros}") # Imprimir lista creada for i in range(len(listaenteros)-1, -1, -1): if listaenteros[i] >= 10: # Instrucción para comparar elemento de la lista listaenteros.pop(i) # Remover elemento #print("Removiendo...", listaenteros[i]) print(listaenteros) else: print("No hubo coincidencia con el número") print(f"Imprimiendo lista modificada: {listaenteros}") # Impriir lista modificada
# -*- coding: utf-8 -*- """ Created on Fri Mar 19 13:45:23 2021 @author: epits """ from ps6.py import Message import string class CiphertextMessage(Message): def __init__(self, text): ''' Initializes a CiphertextMessage object text (string): the message's text a CiphertextMessage object has two attributes: self.message_text (string, determined by input text) self.valid_words (list, determined using helper function load_words) ''' Message.__init__(self,text) def build_decrypter(self,shift): d = dict.fromkeys(string.ascii_letters, 0) for ch in d: if not ch.isupper(): if ord(ch)-shift<97: left=shift-(ord(ch)-97) new=122-left d[ch]=chr(new) else: d[ch]=chr(ord(ch)-shift) else: if ord(ch)-shift<65: left= shift-(ord(ch)-65) new=90-left d[ch]=chr(new) else: d[ch]=chr(ord(ch)-shift) return d def apply_decrypter(self,shift): d=self.build_decrypter(shift) newWord='' for i in self.message_text: try: new_ch=d[i] newWord=newWord+new_ch except: newWord=newWord+i return newWord def decrypt_message(self): ''' Decrypt self.message_text by trying every possible shift value and find the "best" one. We will define "best" as the shift that creates the maximum number of real words when we use apply_shift(shift) on the message text. If s is the original shift value used to encrypt the message, then we would expect 26 - s to be the best shift value for decrypting it. Note: if multiple shifts are equally good such that they all create the maximum number of you may choose any of those shifts (and their corresponding decrypted messages) to return Returns: a tuple of the best shift value used to decrypt the message and the decrypted message text using that shift value ''' max_counter=0 best_suggestion=0 for i in range(26): counter=0 ecryption=self.apply_decrypter(i) for w in ecryption: if w in self.valid_words: counter=counter+1 if counter>max_counter: best_suggestion=i final=ecryption.split(' ') return final
""" Implement the function unique_in_order which takes as argument a sequence and returns a list of items without any elements with the same value next to each other and preserving the original order of elements. For example: unique_in_order('AAAABBBCCDAABBB') == ['A', 'B', 'C', 'D', 'A', 'B'] unique_in_order('ABBCcAD') == ['A', 'B', 'C', 'c', 'A', 'D'] unique_in_order([1,2,2,3,3]) == [1,2,3] test.assert_equals(unique_in_order('AAAABBBCCDAABBB'), ['A','B','C','D','A','B']) best solution : def unique_in_order(iterable): result = [] prev = None for char in iterable[0:]: if char != prev: result.append(char) prev = char return result """ def unique_in_order(string_test): string_aray = list(string_test) array_uni = [] i = 0 while i < len(string_aray): if i == 0: array_uni.append(string_aray[0]) else: if string_aray[i] != array_uni[-1]: array_uni.append(string_aray[i]) i += 1 return array_uni string_test = 'ABBCcAD' result = unique_in_order(string_test) print(result)
from node import Node # inserir na fila # remover na fila # observar o topo da fila class Fila: def __init__(self): self._size = 0 self.first = None self.last = None def __len__(self): return self._size def push(self, elemento): node = Node(elemento) if self.last is None: self.last = node else: self.last.next = node self.last = node if self.first is None: self.first = node self._size = self._size + 1 def pop(self): if self.first is not None: elemento = self.first.data self.first - self.first.next self._size = self._size - 1 return elemento def peek(self):
def approach1(): global a, b a = [1, 2, 3, 4, 5] b = [5, 6, 7, 8, 9] for vala in a: for valb in b: if vala == valb: print("common values present") def approach2(): [print("common values present") for vala in a if vala in b] def approach3(): c = set(a) d = set(b) if not c.isdisjoint(d): print("common values present") approach1() approach2() approach3()
# myDict = { # 1: "mani", # 2: "suresh" # } #print(myDict) import random import string random_invalid_alnums = lambda s="rand12", exclude=[]: [ str(s) + c for c in string.punctuation if c not in exclude ] random_invalid_alphas = lambda s="rand", exclude=[]: [ str(s) + c for c in string.punctuation + string.digits[:2] if c not in exclude ] random_invalid_numbers = lambda s=12, exclude=[]: [ str(s) + c for c in string.punctuation + string.ascii_letters[:2] if c not in exclude ] print(random_invalid_alnums()) invalid_values_for_fields = { "client": ["AA" * 6] + ["RPOSs", "Personify"], "communicationType": random_invalid_alphas() + ["AA" * 16], "contactId": random_invalid_alnums(exclude="'-") + ["AA" * 16], "templateId": random_invalid_alnums() + ["AA" * 51], "sourceAddress": random_invalid_numbers() + ["9" * 9, "9" * 21], "recipientAddress": random_invalid_numbers() + ["9" * 9, "9" * 21], "transactionType": random_invalid_alphas(exclude="'-") + ["AA" * 26], "contactPhonenumber": random_invalid_numbers() + ["9" * 9, "9" * 21], } print(invalid_values_for_fields)
class parent: def __init__(self, fname, lname): self.fname = fname self.lname = lname def printName(self): print(self.fname, self.lname) class child(parent): def __init__(self, fname, lname, year): super().__init__(fname, lname) self.grad_year = year def printName(self): print(self.fname + " " + self.lname + " joined in", self.grad_year) class sampIter(): def __iter__(self): self.a = 1 return self def __next__(self): if self.a <= 20: self.a += 1 return self.a else: raise StopIteration mysamp = sampIter() y = iter(mysamp) for z in y: print(z) # x= child("mani","kandan",2020) # x.printName() pow
import numpy as np import matplotlib.pyplot as plt x = 4 theta = 90 sin = np.sin(theta) cos = np.cos(theta) print("theta is", theta) print("sinus is", sin) print("cosinus is",cos) print("It is Radian") meshPoints = np.linspace(-1,1,500) value53 = meshPoints[52] print("53th element of meshpoint is",value53) plt.plot(meshPoints, np.sin(2*np.pi*meshPoints)) plt.show()
# Factors numbers into Primes! # Anders Kouru 30 juni 2014, last modified 19 dec 2018 import math def introFunction(): print("This function Factors numbers into Primes!") return 0 def prime_Factor(prime_numb): divisor = 2.0 prime_save = prime_numb end = pow(prime_save,0.5) end_save = 1 end_save = int(end) prime_save = float(prime_save) prime = 1 # Vi assume that the number is Prime! numb_div = 0 rest = 1.0 test = 1.0 potens = 1.0 potens = 0 print("factorizing ! ") print("") print("Number ",prime_save," is factorized! ") prime_numb = prime_save while divisor <= prime_numb and prime_numb > 2: rest = prime_numb/divisor test = math.floor(rest) while rest == test and prime_numb >= divisor: prime_numb = rest rest = (prime_numb/divisor) # We shall see how many times test = math.floor(rest) # we can divide with divisor potens += 1 prime += 1 if potens > 0: print(divisor, end='') if potens > 1: numb_div += 1 print(" ^",potens, end='') potens = 0 if prime_numb > divisor: #här print(" * ", end='') divisor += 1 if prime == 1 or prime == 2 and numb_div <= 1: print(" is prime! ") return 0 def main(): forts = 1 while forts != 0: introFunction() inputFunction() print("") print("") forts = input("continue = 1, end = 0 ") if forts == '0': break return 0 def inputFunction(): print("inputFunction ") print("Which number should be factored? ") prime_numb = input("It should be 2 or larger. ") prime_numb = int(prime_numb) while prime_numb < 2: print(" ") prime_numb = input("It should be 2 or larger. ") prime_numb = int(prime_numb) prime_Factor(prime_numb) return 0 main()
# Solution 1 num = 1 while num < 11: print(' 😄 ' * num) num += 1 # Solution 2 for num in range(1, 11): print(' 😄 ' * num) # Solution 3 for num in range(1, 11): emoji = '' count = 1 while count <= num: emoji += ' 😄 ' count += 1 print(emoji)
print('How many kilometers did you cycle today?') kms = float(input()) # input always returns a str miles = round(kms / 1.6934, 2) print(f'Ok you said {miles} miles.') # age = input('How are you?\n') # if age and not(age != str): # int_age = int(age) # if int_age >= 10 and int_age < 21: # print('You can enter, but need a wristband!') # elif int_age >= 21: # print('You are good to enter and you can drink') # else: # print('You can\'t come in.😟') # else: # print('Make sure to provide age')
# There're built-in functions and methods in python names = ["Bianca", "Luca", "Philippe", "Pedro"] print(names) names.append("Ana") print(names) names.pop() names.pop() names.pop() print(names) names.append("Bianca") print(names.count("Bianca")) # number of ocurrances in list names.extend(["Philippe", "Pedro"]) # takes an array of elements print(names) names.insert(2, "New item") print(names) names.clear() print(names) names.insert(0, "Bianca") names.insert(0, "Luca") print(names) names.pop(0) print(names) names = ["Bianca", "Luca", "Pedro", "Philippe"] for name in names: print(names.index(name)) # slicing is done with list_name[:] new_names = names[:] # makes a new copy of names new_names_1 = names[:-1] # creates new list with last item in names new_names_2 = names[1:3] # copies items starting at 1 up, but not including 3 new_names_3 = names[1:-1] # copies items at index one to last items exclusive # stepping with slicing new_names_4 = names[::2] # start at 0 index and go to the end in steps of 2 new_names_5 = names[::-1] # start at the end and make a new reverse copy new_names_6 = names[:1:-1] # start at end and reverse up, but not including 1 new_names_7 = names[2::-1] # start at index 2 and reveserse till index 0 # slicing and stepping can be used on strings as well "Bianca"[1:] # 'ianca' "Bianca"[::-1] # acnaiB # swapping values in list print("original: ", names) names[0], names[1] = names[1], names[0] print("swapped: ", names) # list comprehension nums = [1, 2, 3, 4, 5] [name.lower() for name in names] # ['bianca', 'luca'] [num * 2 for num in nums] # [2, 4, 6, 8, 10] # list comprehension with logic nums_1 = [num * 2 for num in nums if num % 2 == 0] print(nums_1) # [4, 8] nums_2 = [num * 2 if num % 2 == 0 else num / 2 for num in nums] print(nums_2) # [0.5, 4, 1.5, 8, 2.5] with_vowels = "This is a great exercise" remove_vowels = "".join([char.lower() for char in with_vowels if char not in "aeiou"]) print(remove_vowels) # 'ths s grt xrcs' # list comprehension for nested lists nums_3 = [[1, 2, 3], [1, 2, 3], [1, 2, 3]] tictactoe_board = [ ["X" if num % 2 == 0 else "O" for num in range(1, 4)] for num in range(1, 4) ] print(tictactoe_board)
from random import randint print('Rock...') print('Paper...') print('Scissor...') options = ['rock', 'paper', 'scissor'] rand_idx = randint(0, 2) player_1 = input('Player 1, make your move: ') player_2 = options[rand_idx] print(f'Computer players {player_2}') if player_1 == player_2: print('It\'s a tie!') elif player_1 == 'rock': if player_2 == 'paper': print('player 2 wins') if player_2 == 'scissor': print('player 1 wins') elif player_1 == 'paper': if player_2 == 'rock': print('player 1 wins') if player_2 == 'scissor': print('player 2 wins') elif player_1 == 'scissor': if player_2 == 'paper': print('player 1 wins') if player_2 == 'rock': print('player 2 wins') else: print('something went wrong')
user_info = {} user_info['first_name'] = input('Enter your first name: ') user_info['last_name'] = input('Enter your last name: ') print(user_info)
# https://leetcode.com/problems/missing-number/description/ # Time: O(n) # Space: O(1) # # Given an array containing n distinct numbers taken from # 0, 1, 2, ..., n, find the one that is missing from the array. # # For example, # Given nums = [0, 1, 3] return 2. # # Note: # Your algorithm should run in linear runtime complexity. # Could you implement it using only constant extra space complexity? # # V0 class Solution(object): def missingNumber(self, nums): return sum(range(len(nums)+1)) - sum(nums) # V1 # http://bookshadow.com/weblog/2015/08/24/leetcode-missing-number/ class Solution(object): def missingNumber(self, nums): """ :type nums: List[int] :rtype: int """ n = len(nums) return n * (n + 1) / 2 - sum(nums) # V1' # http://bookshadow.com/weblog/2015/08/24/leetcode-missing-number/ # IDEA : BIT MANIPULATION # IDEA : XOR # https://stackoverflow.com/questions/14526584/what-does-the-xor-operator-do/14526640 # XOR is a binary operation, it stands for "exclusive or", that is to say the resulting bit evaluates to one if only exactly one of the bits is set. # "XOR" is same as "^" # a | b | a ^ b # --|---|------ # 0 | 0 | 0 # 0 | 1 | 1 # 1 | 0 | 1 # 1 | 1 | 0 class Solution(object): def missingNumber(self, nums): """ :type nums: List[int] :rtype: int """ a = reduce(operator.xor, nums) b = reduce(operator.xor, range(len(nums) + 1)) return a ^ b # V2 class Solution(object): def missingNumber(self, nums): return sum(range(len(nums)+1)) - sum(nums) # V3 import operator from functools import reduce class Solution(object): def missingNumber(self, nums): """ :type nums: List[int] :rtype: int """ return reduce(operator.xor, nums, \ reduce(operator.xor, range(len(nums) + 1)))
""" Given n nodes labeled from 0 to n - 1 and a list of undirected edges (each edge is a pair of nodes), write a function to find the number of connected components in an undirected graph. Example 1: Input: n = 5 and edges = [[0, 1], [1, 2], [3, 4]] 0 3 | | 1 --- 2 4 Output: 2 Example 2: Input: n = 5 and edges = [[0, 1], [1, 2], [2, 3], [3, 4]] 0 4 | | 1 --- 2 --- 3 Output: 1 Note: You can assume that no duplicate edges will appear in edges. Since all edges are undirected, [0, 1] is the same as [1, 0] and thus will not appear together in edges. """ # V0 # IDEA : DFS class Solution: def countComponents(self, n, edges): def helper(u): if u in pair: for v in pair[u]: if v not in visited: visited.add(v) helper(v) pair = collections.defaultdict(set) for u,v in edges: pair[u].add(v) pair[v].add(u) count = 0 visited = set() for i in range(n): if i not in visited: helper(i) count+=1 return count # V1 # IDEA : DFS # https://blog.csdn.net/qq_37821701/article/details/104371911 class Solution: def countComponents(self, n, edges): def helper(u): if u in pair: for v in pair[u]: if v not in visited: visited.add(v) helper(v) pair = collections.defaultdict(set) for u,v in edges: pair[u].add(v) pair[v].add(u) count = 0 visited = set() for i in range(n): if i not in visited: helper(i) count+=1 return count # V1 # IDEA : BFS # https://www.jiuzhang.com/solution/number-of-connected-components-in-an-undirected-graph/#tag-other-lang-python import collections class Solution: def countComponents(self, n, edges): if not edges: return n list_dict = collections.defaultdict(list) for i, j in edges: list_dict[i].append(j) list_dict[j].append(i) def bfs(node, visited): queue = [node] while queue: nd = queue.pop(0) for neighbor in list_dict[nd]: if neighbor not in visited: visited.append(neighbor) queue.append(neighbor) return visited def find_root(visited): for i in range(n): if i not in visited: return i return -1 visited = [] count = 0 # note : Given n nodes labeled from 0 to n - 1 for i in range(n): node = find_root(visited) if node != -1: count+=1 visited.append(node) visited = bfs(node, visited) else: return count # V1' # IDEA : UNION FIND # https://www.cnblogs.com/lightwindy/p/8487160.html # Time: O(nlog*n) ~= O(n), n is the length of the positions # Space: O(n) class UnionFind(object): def __init__(self, n): self.set = range(n) self.count = n def find_set(self, x): if self.set[x] != x: self.set[x] = self.find_set(self.set[x]) # path compression. return self.set[x] def union_set(self, x, y): x_root, y_root = map(self.find_set, (x, y)) if x_root != y_root: self.set[min(x_root, y_root)] = max(x_root, y_root) self.count -= 1 class Solution(object): def countComponents(self, n, edges): """ :type n: int :type edges: List[List[int]] :rtype: int """ union_find = UnionFind(n) for i, j in edges: union_find.union_set(i, j) return union_find.count # V1'' # IDEA : UNION FIND # https://blog.csdn.net/qq_37821701/article/details/104371911 class Solution: def countComponents(self, n, edges): def unionfind(p1,p2): nonlocal count # find root of p1 while root[p1]!=p1: p1 = root[p1] # find root of p2 while root[p2]!=p2: p2 = root[p2] #if roots of p1 and p2 are identicle, meaning they have already been merged if root[p1]==root[p2]: return # merge them if not merged else: root[p1] = p2 count -= 1 # initially, we have n connected path count = n # store original roots root = [i for i in range(n)] # go through each node pair for edge in edges: unionfind(edge[0],edge[1]) return count # V2 # Time: O(nlog*n) ~= O(n), n is the length of the positions # Space: O(n) class UnionFind(object): def __init__(self, n): self.set = range(n) self.count = n def find_set(self, x): if self.set[x] != x: self.set[x] = self.find_set(self.set[x]) # path compression. return self.set[x] def union_set(self, x, y): x_root, y_root = map(self.find_set, (x, y)) if x_root != y_root: self.set[min(x_root, y_root)] = max(x_root, y_root) self.count -= 1 class Solution(object): def countComponents(self, n, edges): """ :type n: int :type edges: List[List[int]] :rtype: int """ union_find = UnionFind(n) for i, j in edges: union_find.union_set(i, j) return union_find.count
# V0 # IDEA : MATRIX IN ORDER + BRUTE FORCE # Space: O(1) # Time: O(m+n) # worst case class Solution: def searchMatrix(self, matrix, target): if len(matrix) == 0: return False row, col = 0, len(matrix[0]) - 1 while row < len(matrix) and col >= 0: if matrix[row][col] == target: return True elif matrix[row][col] < target: row += 1 elif matrix[row][col] > target: col -= 1 return False # V0' # IDEA : BINARY SEARCH # Space: O(1) # Time: O(logm + logn) class Solution(object): def searchMatrix(self, matrix, target): """ :type matrix: List[List[int]] :type target: int :rtype: bool """ if not matrix: return False m, n = len(matrix), len(matrix[0]) left, right = 0, m * n while left < right: mid = left + (right - left) / 2 if matrix[int(mid / n)][int(mid % n)]>= target: right = mid else: left = mid + 1 return left < m * n and matrix[int(left / n)][int(left % n)] == target # V1 # https://leetcode.com/problems/search-a-2d-matrix/discuss/351404/Python-Simple-Solution class Solution: def searchMatrix(self, matrix, target): if len(matrix) == 0: return False row, col = 0, len(matrix[0]) - 1 while row < len(matrix) and col >= 0: if matrix[row][col] == target: return True elif matrix[row][col] < target: row += 1 elif matrix[row][col] > target: col -= 1 return False ### Test case s=Solution() assert s.searchMatrix([[1,2,3],[4,5,6],[7,8,9]], 9) == True assert s.searchMatrix([[1,2,3],[4,5,6],[7,8,9]], 1) == True assert s.searchMatrix([[1,2,3],[4,5,6],[7,8,9]], 99) == False assert s.searchMatrix([[]], 0) == False assert s.searchMatrix([[]], 100) == False assert s.searchMatrix([], 100) == False assert s.searchMatrix([[-1,3,4,-4]], -1) == False assert s.searchMatrix([[_ for _ in range(3)] for _ in range(4)], -1) == False assert s.searchMatrix([[_ for _ in range(3)] for _ in range(4)], 2) == True assert s.searchMatrix([[_ for _ in range(99)] for _ in range(999)], 2) == True # V1' # https://leetcode.com/problems/search-a-2d-matrix/discuss/592696/python-super-easy # IDEA : BRUTE FORCE class Solution: def searchMatrix(self, matrix: List[List[int]], target: int) -> bool: for x in matrix: if target in x: return True return False # V1'' # https://blog.csdn.net/fuxuemingzhu/article/details/79459314 # https://blog.csdn.net/fuxuemingzhu/article/details/79459200 class Solution(object): def searchMatrix(self, matrix, target): """ :type matrix: List[List[int]] :type target: int :rtype: bool """ if not matrix or not matrix[0]: return False rows = len(matrix) cols = len(matrix[0]) row, col = 0, cols - 1 while True: if row < rows and col >= 0: if matrix[row][col] == target: return True elif matrix[row][col] < target: row += 1 else: col -= 1 else: return False # V1' # https://blog.csdn.net/fuxuemingzhu/article/details/79459314 # https://blog.csdn.net/fuxuemingzhu/article/details/79459200 class Solution(object): def searchMatrix(self, matrix, target): """ :type matrix: List[List[int]] :type target: int :rtype: bool """ return any(target in row for row in matrix) # V2 # IDEA : BINARY SEARCH # Space: O(1) # Time: O(logm + logn) class Solution(object): def searchMatrix(self, matrix, target): """ :type matrix: List[List[int]] :type target: int :rtype: bool """ if not matrix: return False m, n = len(matrix), len(matrix[0]) left, right = 0, m * n while left < right: mid = left + (right - left) / 2 if matrix[int(mid / n)][int(mid % n)]>= target: right = mid else: left = mid + 1 return left < m * n and matrix[int(left / n)][int(left % n)] == target
# Suppose you are at a party with n people (labeled from 0 to n - 1) and among them, there may exist one celebrity. The definition of a celebrity is that all the other n - 1 people know him/her but he/she does not know any of them. # Now you want to find out who the celebrity is or verify that there is not one. The only thing you are allowed to do is to ask questions like: "Hi, A. Do you know B?" to get information of whether A knows B. You need to find out the celebrity (or verify there is not one) by asking as few questions as possible (in the asymptotic sense). # You are given a helper function bool knows(a, b)which tells you whether A knows B. Implement a function int findCelebrity(n). There will be exactly one celebrity if he/she is in the party. Return the celebrity's label if there is a celebrity in the party. If there is no celebrity, return -1. # Example 1: # Input: graph = [ # [1,1,0], # [0,1,0], # [1,1,1] # ] # Output: 1 # Explanation: There are three persons labeled with 0, 1 and 2. graph[i][j] = 1 means person i knows person j, otherwise graph[i][j] = 0 means person i does not know person j. The celebrity is the person labeled as 1 because both 0 and 2 know him but 1 does not know anybody. # Example 2: # Input: graph = [ # [1,0,1], # [1,1,0], # [0,1,1] # ] # Output: -1 # Explanation: There is no celebrity. # Note: # The directed graph is represented as an adjacency matrix, which is an n x n matrix where a[i][j] = 1 means person i knows person j while a[i][j] = 0 means the contrary. # Remember that you won't have direct access to the adjacency matrix. # V0 class Solution: # @param {int} n a party with n people # @return {int} the celebrity's label or -1 def findCelebrity(self, n): celeb = 0 for i in range(1, n): if Celebrity.knows(celeb, i): # if celeb knows i, then the given celeb must not a celebrity, so we move to the next possible celeb celeb = i # move from celeb to i # Check if the final candicate is the celebrity for i in range(n): if celeb != i and Celebrity.knows(celeb, i): # to check if the Celebrity really knows no one return -1 if celeb != i and not Celebrity.knows(i, celeb): # to check if everyone (except Celebrity) really knows the Celebrity return -1 return celeb # V1 # https://www.jiuzhang.com/solution/find-the-celebrity/#tag-highlight-lang-python # IDEA : # AS A CELEBRITY, HE/SHE MOST KNOW NO ONE IN THE GROUP # AND REST OF PEOPLE (EXCEPT CELEBRITY) MOST ALL KNOW THE CELEBRITY # SO WE CAN USE THE FACT 1) : AS A CELEBRITY, HE/SHE MOST KNOW NO ONE IN THE GROUP # -> GO THROUGH ALL PEOPLE IN THE GROUP TO FIND ONE WHO KNOW NO ONE, THEN HE/SHE MAY BE THE CELEBRITY POSSIBILY # -> THEN GO THROUGH REST OF THE PEOPLE AGAIN TO VALIDATE IF HE/SHE IS THE TRUE CELEBRITY """ The knows API is already defined for you. @param a, person a @param b, person b @return a boolean, whether a knows b you can call Celebrity.knows(a, b) """ class Solution: # @param {int} n a party with n people # @return {int} the celebrity's label or -1 def findCelebrity(self, n): celeb = 0 for i in range(1, n): if Celebrity.knows(celeb, i): # if celeb knows i, then the given celeb must not a celebrity, so we move to the next possible celeb celeb = i # move from celeb to i # Check if the final candicate is the celebrity for i in range(n): if celeb != i and Celebrity.knows(celeb, i): # to check if the Celebrity really knows no one return -1 if celeb != i and not Celebrity.knows(i, celeb): # to check if everyone (except Celebrity) really knows the Celebrity return -1 return celeb # V2 # Time: O(n) # Space: O(1) class Solution(object): def findCelebrity(self, n): """ :type n: int :rtype: int """ candidate = 0 # Find the candidate. for i in range(1, n): if knows(candidate, i): # noqa candidate = i # All candidates < i are not celebrity candidates. # Verify the candidate. for i in range(n): candidate_knows_i = knows(candidate, i) # noqa i_knows_candidate = knows(i, candidate) # noqa if i != candidate and (candidate_knows_i or not i_knows_candidate): return -1 return candidate
# V0 # IDEA : brute force + check subset of set # LOGIC : start from the given time, then "add 1 minute" in every loop, # if all the elements in the upddated time are also the subset of the original time set -> return True (find the answer) # CONCEPT : subset in python # https://stackoverflow.com/questions/16579085/how-can-i-verify-if-one-list-is-a-subset-of-another # >>> a = [1, 3, 5] # >>> b = [1, 3, 5, 8] # >>> c = [3, 5, 9] # >>> set(a) <= set(b) # True # >>> set(c) <= set(b) # False # >>> a = ['yes', 'no', 'hmm'] # >>> b = ['yes', 'no', 'hmm', 'well'] # >>> c = ['sorry', 'no', 'hmm'] # >>> # >>> set(a) <= set(b) # True # >>> set(c) <= set(b) # False from datetime import * class Solution: """ @param time: the given time @return: the next closest time """ def nextClosestTime(self, time): digits = set(time) while True: time = (datetime.strptime(time, '%H:%M') + timedelta(minutes=1)).strftime('%H:%M') if set(time) <= digits: # if set(time) is the "subset" of original set (which is digits) return time # V1 # https://www.jiuzhang.com/solution/next-closest-time/#tag-highlight-lang-python from datetime import * class Solution: """ @param time: the given time @return: the next closest time """ def nextClosestTime(self, time): digits = set(time) while True: time = (datetime.strptime(time, '%H:%M') + timedelta(minutes=1)).strftime('%H:%M') if set(time) <= digits: return time # V1' # http://bookshadow.com/weblog/2017/09/24/leetcode-next-closest-time/ # time = "23:59" # time = "2359" # stime = [2,3,5,9] # x = 3, time[x] = 9, y = 2 # x = 2, time[x] = 5, y = 3 # x = 1, time[x] = 3, y = 5 # x = 0, time[x] = 2, y = 9 class Solution(object): def nextClosestTime(self, time): """ :type time: str :rtype: str """ time = time[:2] + time[3:] isValid = lambda t: int(t[:2]) < 24 and int(t[2:]) < 60 stime = sorted(time) for x in (3, 2, 1, 0): for y in stime: if y <= time[x]: continue ntime = time[:x] + y + (stime[0] * (3 - x)) if isValid(ntime): return ntime[:2] + ':' + ntime[2:] return stime[0] * 2 + ':' + stime[0] * 2 # V2 # Time: O(1) # Space: O(1) class Solution(object): def nextClosestTime(self, time): """ :type time: str :rtype: str """ h, m = time.split(":") curr = int(h) * 60 + int(m) result = None for i in range(curr+1, curr+1441): t = i % 1440 h, m = t // 60, t % 60 result = "%02d:%02d" % (h, m) if set(result) <= set(time): break return result
# V0 class Solution(object): def reconstructQueue(self, people): people.sort(key = lambda x : (-x[0], x[1])) res = [] for p in people: res.insert(p[1], p) return res # V1 # https://blog.csdn.net/fuxuemingzhu/article/details/68486884 # IDEA : MAKE THE ARRAY IN DESCENDING ORDER, THEN INSERT SMALL ONE BACK # IDEA : PROCESS : # STEP 1) ORDER THE ARRAY IN DESCENDING ORDER # STEP 2) LOOP THE ARRAY AND DO THE INSERT OPERATION (BASED ON 1st VALUE) # IDEA : insert module in python # http://www.runoob.com/python/att-list-insert.html # list.insert(index, obj) # index : the index for inseeting # obj : the object to insert # DEMO: # In [25]: p= [[7,0], [4,4], [7,1], [5,0], [6,1], [5,2]] # In [26]: p.sort(key = lambda x : (-x[0], x[1])) # In [27]: p # Out[27]: [[7, 0], [7, 1], [6, 1], [5, 0], [5, 2], [4, 4]] # In [28]: p.insert(1, [6,1]) # In [29]: p # Out[29]: [[7, 0], [6, 1], [7, 1], [6, 1], [5, 0], [5, 2], [4, 4]] # In [30]: class Solution(object): def reconstructQueue(self, people): """ :type people: List[List[int]] :rtype: List[List[int]] """ people.sort(key = lambda x : (-x[0], x[1])) res = [] for p in people: res.insert(p[1], p) return res ### Test case : dev # V2 # https://leoeatle.github.io/techBlog/2017/01/11/LeetCode-406-Queue-Reconstruction-by-Height/ class Solution(object): def reconstructQueue(self, people): """ :type people: List[List[int]] :rtype: List[List[int]] """ if not people: return [] queue = [] for h, k in sorted(people, key=lambda h_k2: (-h_k2[0], h_k2[1])): queue.insert(k, [h , k]) return queue # V3 # Time: O(n * sqrt(n)) # Space: O(n) class Solution(object): def reconstructQueue(self, people): """ :type people: List[List[int]] :rtype: List[List[int]] """ people.sort(key=lambda h_k: (-h_k[0], h_k[1])) blocks = [[]] for p in people: index = p[1] for i, block in enumerate(blocks): if index <= len(block): break index -= len(block) block.insert(index, p) if len(block) * len(block) > len(people): blocks.insert(i+1, block[len(block)/2:]) del block[len(block)/2:] return [p for block in blocks for p in block] # V4 # Time: O(n^2) # Space: O(n) class Solution2(object): def reconstructQueue(self, people): """ :type people: List[List[int]] :rtype: List[List[int]] """ people.sort(key=lambda h_k1: (-h_k1[0], h_k1[1])) result = [] for p in people: result.insert(p[1], p) return result
# V0 # IDEA : MATH class Solution(object): def complexNumberMultiply(self, a, b): def split(s): tmp = s[:-1].split("+") return int(tmp[0]), int(tmp[1]) m, n = split(a) p, q = split(b) return '{}+{}i'.format((m*p - n*q),(m*q + n*p)) # V1 # http://bookshadow.com/weblog/2017/03/26/leetcode-complex-number-multiplication/ # IDEA : STRING OP class Solution(object): def complexNumberMultiply(self, a, b): """ :type a: str :type b: str :rtype: str """ extract = lambda s : map(int, s[:-1].split('+')) m, n = extract(a) p, q = extract(b) return '%s+%si' % (m * p - n * q, m * q + n * p) # V1' class Solution(object): # a : a1+a2*i # b : b2+b2*i def complexNumberMultiply(self, a, b): ra, ia = float(a.split('+')[0]), float(a.split('+')[1].split('i')[0]) rb, ib = float(b.split('+')[0]), float(b.split('+')[1].split('i')[0]) return '%d+%di' % ((ra*rb - ia*ib), ia*rb + ib*ra) # V2 # Time: O(1) # Space: O(1) class Solution(object): def complexNumberMultiply(self, a, b): """ :type a: str :type b: str :rtype: str """ ra, ia = list(map(int, a[:-1].split('+'))) rb, ib = list(map(int, b[:-1].split('+'))) return '%d+%di' % (ra * rb - ia * ib, ra * ib + ia * rb)
# Evaluate the value of an arithmetic expression in Reverse Polish Notation. # # Valid operators are +, -, *, /. Each operand may be an integer or another expression. # # Some examples: # ["2", "1", "+", "3", "*"] -> ((2 + 1) * 3) -> 9 # ["4", "13", "5", "/", "+"] -> (4 + (13 / 5)) -> 6 # V0 # IDEA : STACK # DEMO : call lambda via dict # In [13]: ops = { # ...: '+' : lambda y, x: x+y, # ...: '-' : lambda y, x: x-y, # ...: '*' : lambda y, x: x*y, # ...: '/' : lambda y, x: int(x/y) # ...: } # ...: # ...: a = 3 # ...: b = 4 # ...: # ...: # ...: for key in ops.keys(): # ...: print (ops[key]) # ...: print (ops[key](a,b)) # ...: # <function <lambda> at 0x7f8c068c4730> # 7 # <function <lambda> at 0x7f8c068c4048> # 1 # <function <lambda> at 0x7f8c068c4a60> # 12 # <function <lambda> at 0x7f8c068c48c8> # 1 class Solution: def evalRPN(self, tokens): """ :type tokens: List[str] :rtype: int """ if len(tokens) < 1: return None ops = { '+' : lambda y, x: x+y, '-' : lambda y, x: x-y, '*' : lambda y, x: x*y, '/' : lambda y, x: int(x/y) } result = [] for token in tokens: if token in ops.keys(): result.append(ops[token](result.pop(), result.pop())) else: result.append(int(token)) return result[0] # V1 # https://leetcode.com/problems/evaluate-reverse-polish-notation/discuss/143004/Python-solution-O(n)-descriptive-solution # https://leetcode.com/problems/evaluate-reverse-polish-notation/discuss/168183/Python-simple-functional-solution-(no-stack) # IDEA : STACK # STEPS: # 1) lets create a dictionary hashmap of what needs to happen when an operator is encountered. # 2) traverse through the tokens and catch all the numbers preceeding the operator. # 3) pop the last two numbers -> perform the operation and store it in the stack. # 4) keep repeating 2 and 3 # 5) you'll ultimately be left with the result in the stack class Solution: def evalRPN(self, tokens): """ :type tokens: List[str] :rtype: int """ if len(tokens) < 1: return None ops = { '+' : lambda y, x: x+y, '-' : lambda y, x: x-y, '*' : lambda y, x: x*y, '/' : lambda y, x: int(x/y) } result = [] for token in tokens: if token in ops.keys(): result.append(ops[token](result.pop(), result.pop())) else: result.append(int(token)) return result[0] ### Test case s=Solution() assert s.evalRPN([]) == None assert s.evalRPN(["0"]) == 0 assert s.evalRPN(["-1"]) == -1 assert s.evalRPN(["-0"]) == 0 assert s.evalRPN(["-1","1","-"]) == -2 assert s.evalRPN(["0","1","+"]) == 1 assert s.evalRPN(["0","1","-"]) == -1 assert s.evalRPN(["2", "1", "+", "3", "*"]) == 9 assert s.evalRPN(["4", "13", "5", "/", "+"]) == 6 assert s.evalRPN(["1","1", "*"]) == 1 assert s.evalRPN(["1","1", "1", "*", "+"]) == 2 # V1' # https://blog.csdn.net/fuxuemingzhu/article/details/79559703 class Solution(object): def evalRPN(self, tokens): """ :type tokens: List[str] :rtype: int """ stack = [] operators = ['+', '-', '*', '/'] for token in tokens: if token not in operators: stack.append(token) else: b = stack.pop() a = stack.pop() if token == '/': res = int(operator.truediv(int(a), int(b))) else: res = eval(a + token + b) stack.append(str(res)) return int(stack.pop()) # V1'' # https://blog.csdn.net/fuxuemingzhu/article/details/79559703 class Solution(object): def evalRPN(self, tokens): """ :type tokens: List[str] :rtype: int """ stack = [] operators = ['+', '-', '*', '/'] for token in tokens: if token not in operators: stack.append(token) else: b = stack.pop() a = stack.pop() if token == '/' and int(a) * int(b) < 0: res = eval('-' + '(' + '-' + a + '/' + b + ')') else: res = eval(a + token + b) stack.append(str(res)) return int(stack.pop()) # V1''' # https://leetcode.com/problems/evaluate-reverse-polish-notation/discuss/47537/6-7-lines-in-Python # IDEA : RECURSIVE class Solution(object): def evalRPN(self, tokens): t = tokens.pop() if t in '+-*/': b = self.evalRPN(tokens) a = self.evalRPN(tokens) t = eval(a+t+b+'.') return int(t) # V1'''' # https://leetcode.com/problems/evaluate-reverse-polish-notation/discuss/47549/A-Python-solution-with-8-lines class Solution(object): def evalRPN(self, tokens): stack = [] ops = {'+':lambda x, y: x+y, '-':lambda x, y: x-y, '*':lambda x, y: x*y, '/':lambda x, y: x/y} for s in tokens: try: stack.append( float( s ) ) except: stack.append( int( ops[s]( stack.pop(-2), stack.pop(-1) ) ) ) return int( stack[-1] ) # V1''''' # https://leetcode.com/problems/evaluate-reverse-polish-notation/discuss/47537/6-7-lines-in-Python # IDEA : ITERATION class Solution(object): def evalRPN(self, tokens): stack = [] for t in tokens: if t in '+-*/': b, a = stack.pop(), stack.pop() t = int(eval(a+t+b+'.')) stack += t, return int(stack[0]) # V2 # Time: O(n) # Space: O(n) import operator class Solution(object): # @param tokens, a list of string # @return an integer def evalRPN(self, tokens): numerals, operators = [], {"+": operator.add, "-": operator.sub, "*": operator.mul, "/": operator.div} for token in tokens: if token not in operators: numerals.append(int(token)) else: y, x = numerals.pop(), numerals.pop() numerals.append(int(operators[token](x * 1.0, y))) return numerals.pop()
# V0 # IDEA : REVERSE WHOLE STRING -> REVERSE EACH WORD class Solution(object): def reverseWords(self, s): s_ = s[::-1] s_list = s_.split(" ") return " ".join([ i[::-1] for i in s_list]) # V1 # http://www.voidcn.com/article/p-eggrnnob-zo.html class Solution(object): def reverseWords(self, s): """ :type s: a list of 1 length strings (List[str]) :rtype: nothing """ s.reverse() i = 0 while i < len(s): j = i while j < len(s) and s[j] != " ": j += 1 for k in range(i, i + (j - i) / 2 ): t = s[k] s[k] = s[i + j - 1 - k] s[i + j - 1 - k] = t i = j + 1 # V2 # Time: O(n) # Space:O(1) class Solution(object): def reverseWords(self, s): """ :type s: a list of 1 length strings (List[str]) :rtype: nothing """ def reverse(s, begin, end): for i in range((end - begin) / 2): s[begin + i], s[end - 1 - i] = s[end - 1 - i], s[begin + i] reverse(s, 0, len(s)) i = 0 for j in range(len(s) + 1): if j == len(s) or s[j] == ' ': reverse(s, i, j) i = j + 1
""" Given the head of a singly linked list, reverse the list, and return the reversed list. Example 1: Input: head = [1,2,3,4,5] Output: [5,4,3,2,1] Example 2: Input: head = [1,2] Output: [2,1] Example 3: Input: head = [] Output: [] Constraints: The number of nodes in the list is the range [0, 5000]. -5000 <= Node.val <= 5000 Follow up: A linked list can be reversed either iteratively or recursively. Could you implement both? """ # V0 # https://github.com/yennanliu/CS_basics/blob/master/data_structure/python/linkedList.py # IDEA : Linkedlist basics class Solution: def reverseList(self, head: ListNode): prev = None current = head while(current is not None): next_ = current.next current.next = prev prev = current current = next_ head = prev return head # V1 # https://blog.csdn.net/coder_orz/article/details/51306170 # IDEA : STACK # Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # self.next = None class Solution(object): def reverseList(self, head): """ :type head: ListNode :rtype: ListNode """ p = head newList = [] while p: newList.insert(0, p.val) p = p.next p = head for v in newList: p.val = v p = p.next return head # V1' # http://bookshadow.com/weblog/2015/05/05/leetcode-reverse-linked-list/ # IDEA : LINKED LIST class Solution: # @param {ListNode} head # @return {ListNode} def reverseList(self, head): dummy = ListNode(0) while head: next = head.next head.next = dummy.next dummy.next = head head = next return dummy.next # V1' # http://bookshadow.com/weblog/2015/05/05/leetcode-reverse-linked-list/ # IDEA : ITERATION class Solution: # @param {ListNode} head # @return {ListNode} def reverseList(self, head): return self.doReverse(head, None) def doReverse(self, head, newHead): if head is None: return newHead next = head.next head.next = newHead return self.doReverse(next, head) # V2 # Time: O(n) # Space: O(1) class ListNode(object): def __init__(self, x): self.val = x self.next = None def __repr__(self): if self: return "{} -> {}".format(self.val, repr(self.__next__)) # Iterative solution. class Solution(object): # @param {ListNode} head # @return {ListNode} def reverseList(self, head): dummy = ListNode(float("-inf")) while head: dummy.next, head.next, head = head, dummy.next, head.next return dummy.__next__ # Time: O(n) # Space: O(n) # Recursive solution. class Solution2(object): # @param {ListNode} head # @return {ListNode} def reverseList(self, head): [begin, end] = self.reverseListRecu(head) return begin def reverseListRecu(self, head): if not head: return [None, None] [begin, end] = self.reverseListRecu(head.__next__) if end: end.next = head head.next = None return [begin, head] else: return [head, head]
# 295. Find Median from Data Stream # Hard # # Median is the middle value in an ordered integer list. If the size of the list is even, there is no middle value. So the median is the mean of the two middle value. # # For example, # [2,3,4], the median is 3 # # [2,3], the median is (2 + 3) / 2 = 2.5 # # Design a data structure that supports the following two operations: # # void addNum(int num) - Add a integer number from the data stream to the data structure. # double findMedian() - Return the median of all elements so far. # # Example: # # addNum(1) # addNum(2) # findMedian() -> 1.5 # addNum(3) # findMedian() -> 2 # # Follow up: # # If all integer numbers from the stream are between 0 and 100, how would you optimize it? # If 99% of all integer numbers from the stream are between 0 and 100, how would you optimize it? # V0 from heapq import * class MedianFinder: def __init__(self): self.small = [] # the smaller half of the list, max heap (invert min-heap) self.large = [] # the larger half of the list, min heap def addNum(self, num): if len(self.small) == len(self.large): heappush(self.large, -heappushpop(self.small, -num)) else: heappush(self.small, -heappushpop(self.large, num)) def findMedian(self): if len(self.small) == len(self.large): return float(self.large[0] - self.small[0]) / 2.0 else: return float(self.large[0]) # V1 # https://leetcode.com/problems/find-median-from-data-stream/discuss/74062/Short-simple-JavaC%2B%2BPython-O(log-n)-%2B-O(1) from heapq import * class MedianFinder: def __init__(self): self.heaps = [], [] def addNum(self, num): small, large = self.heaps heappush(small, -heappushpop(large, num)) if len(large) < len(small): heappush(large, -heappop(small)) def findMedian(self): small, large = self.heaps if len(large) > len(small): return float(large[0]) return (large[0] - small[0]) / 2.0 # V1'' # https://leetcode.com/problems/find-median-from-data-stream/discuss/74047/JavaPython-two-heap-solution-O(log-n)-add-O(1)-find from heapq import * class MedianFinder: def __init__(self): self.small = [] # the smaller half of the list, max heap (invert min-heap) self.large = [] # the larger half of the list, min heap def addNum(self, num): if len(self.small) == len(self.large): heappush(self.large, -heappushpop(self.small, -num)) else: heappush(self.small, -heappushpop(self.large, num)) def findMedian(self): if len(self.small) == len(self.large): return float(self.large[0] - self.small[0]) / 2.0 else: return float(self.large[0]) # V1''' # https://leetcode.com/problems/find-median-from-data-stream/discuss/74044/Very-Short-O(log-n)-%2B-O(1) class MedianFinder: def __init__(s): h = [[], 1, -1, i := []] s.addNum = lambda n: heapq.heappush(h[-1], -heapq.heappushpop(h[0], n * h[1])) or h.reverse() s.findMedian = lambda: (h[0][0] * h[1] - i[0]) / 2 # V1'''' # https://leetcode.com/problems/find-median-from-data-stream/discuss/74044/Very-Short-O(log-n)-%2B-O(1) from heapq import * class MedianFinder: def __init__(self): self.data = 1, [], [] def addNum(self, num): sign, h1, h2 = self.data heappush(h2, -heappushpop(h1, num * sign)) self.data = -sign, h2, h1 def findMedian(self): sign, h1, h2 = d = self.data return (h1[0] * sign - d[-sign][0]) / 2.0 # V1''''' # http://bookshadow.com/weblog/2015/10/19/leetcode-find-median-data-stream/ # IDEA : HEAP from heapq import * class MedianFinder: def __init__(self): """ Initialize your data structure here. """ self.minHeap = [] self.maxHeap = [] def addNum(self, num): """ Adds a num into the data structure. :type num: int :rtype: void """ heappush(self.maxHeap, -num) minTop = self.minHeap[0] if len(self.minHeap) else None maxTop = self.maxHeap[0] if len(self.maxHeap) else None if minTop < -maxTop or len(self.minHeap) + 1 < len(self.maxHeap): heappush(self.minHeap, -heappop(self.maxHeap)) if len(self.maxHeap) < len(self.minHeap): heappush(self.maxHeap, -heappop(self.minHeap)) def findMedian(self): """ Returns the median of current data stream :rtype: float """ if len(self.minHeap) < len(self.maxHeap): return -1.0 * self.maxHeap[0] else: return (self.minHeap[0] - self.maxHeap[0]) / 2.0 # V1'''''' # http://bookshadow.com/weblog/2015/10/19/leetcode-find-median-data-stream/ # IDEA : HEAP import heapq class MedianFinder: def __init__(self): self.small = [] # the smaller half of the list, min-heap with invert values self.large = [] # the larger half of the list, min heap def addNum(self, num): if len(self.small) == len(self.large): heapq.heappush(self.large, -heapq.heappushpop(self.small, -num)) else: heapq.heappush(self.small, -heapq.heappushpop(self.large, num)) def findMedian(self): if len(self.small) == len(self.large): return float(self.large[0] - self.small[0]) / 2.0 else: return float(self.large[0]) # V1'''''''' # http://bookshadow.com/weblog/2015/10/19/leetcode-find-median-data-stream/ # IDEA : HEAP class Heap: def __init__(self, cmp): self.cmp = cmp self.heap = [None] def __swap__(self, x, y, a): a[x], a[y] = a[y], a[x] def size(self): return len(self.heap) - 1 def top(self): return self.heap[1] if self.size() else None def append(self, num): self.heap.append(num) self.siftUp(self.size()) def pop(self): top, last = self.heap[1], self.heap.pop() if self.size(): self.heap[1] = last self.siftDown(1) return top def siftUp(self, idx): while idx > 1 and self.cmp(idx, idx / 2, self.heap): self.__swap__(idx / 2, idx, self.heap) idx /= 2 def siftDown(self, idx): while idx * 2 <= self.size(): nidx = idx * 2 if nidx + 1 <= self.size() and self.cmp(nidx + 1, nidx, self.heap): nidx += 1 if self.cmp(nidx, idx, self.heap): self.__swap__(nidx, idx, self.heap) idx = nidx else: break class MedianFinder: def __init__(self): """ Initialize your data structure here. """ self.minHeap = Heap(cmp = lambda x, y, a: a[x] < a[y]) self.maxHeap = Heap(cmp = lambda x, y, a: a[x] > a[y]) def addNum(self, num): """ Adds a num into the data structure. :type num: int :rtype: void """ self.maxHeap.append(num) if self.minHeap.top() < self.maxHeap.top() \ or self.minHeap.size() + 1 < self.maxHeap.size(): self.minHeap.append(self.maxHeap.pop()) if self.maxHeap.size() < self.minHeap.size(): self.maxHeap.append(self.minHeap.pop()) def findMedian(self): """ Returns the median of current data stream :rtype: float """ if self.minHeap.size() < self.maxHeap.size(): return self.maxHeap.top() else: return (self.minHeap.top() + self.maxHeap.top()) / 2.0 # V2
# Time: O(n) # Space: O(1) # # The API: int read4(char *buf) reads 4 characters at a time from a file. # # The return value is the actual number of characters read. For example, it returns 3 if there is only 3 characters left in the file. # # By using the read4 API, implement the function int read(char *buf, int n) that reads n characters from the file. # # Note: # The read function will only be called once for each test case. # # The read4 API is already defined for you. # @param buf, a list of characters # @return an integer # V0 # V1 # http://www.voidcn.com/article/p-pfdpmnvw-qp.html # https://www.cnblogs.com/yrbbest/p/4489710.html # The read4 API is already defined for you. # @param buf, a list of characters # @return an integer # def read4(buf): class Solution(object): def read(self, buf, n): """ :type buf: Destination buffer (List[str]) :type n: Maximum number of characters to read (int) :rtype: The number of characters read (int) """ index = 0 while True: buf4 = [""]*4 current = min(read4(buf4), index) # use read4 method, save the read data in bur4 for i in range(current): buf[index] = buf4[i] # send value to buf, test case may need to check whether buf read the necessary characters index += 1 if current!=4: return index # V1' # https://www.jiuzhang.com/solution/read-n-characters-given-read4-ii-call-multiple-times/#tag-highlight-lang-python class Solution: def __init__(self): self.buf4, self.i4, self.n4 = [None] * 4, 0, 0 # @param {char[]} buf destination buffer # @param {int} n maximum number of characters to read # @return {int} the number of characters read def read(self, buf, n): # Write your code here i = 0 while i < n: if self.i4 == self.n4: self.i4, self.n4 = 0, Reader.read4(self.buf4) if not self.n4: break buf[i], i, self.i4 = self.buf4[self.i4], i + 1, self.i4 + 1 return i # V2 # Time: O(n) # Space: O(1) def read4(buf): global file_content i = 0 while i < len(file_content) and i < 4: buf[i] = file_content[i] i += 1 if len(file_content) > 4: file_content = file_content[4:] else: file_content = "" return i class Solution(object): def read(self, buf, n): """ :type buf: Destination buffer (List[str]) :type n: Maximum number of characters to read (int) :rtype: The number of characters read (int) """ read_bytes = 0 buffer = [''] * 4 for i in range(n / 4 + 1): size = read4(buffer) if size: size = min(size, n-read_bytes) buf[read_bytes:read_bytes+size] = buffer[:size] read_bytes += size else: break return read_bytes
# V0 class Solution: def tree2str(self, t): if not t: return '' if not t.left and not t.right: return str(t.val) ### NOTICE HERE if not t.left: return str(t.val) + '()' + '(' + self.tree2str(t.right) + ')' ### NOTICE HERE if not t.right: return str(t.val) + '(' + self.tree2str(t.left) + ')' ### NOTICE HERE return str(t.val) + '(' + self.tree2str(t.left) + ')' + '(' + self.tree2str(t.right) + ')' # V0' class Solution(object): def tree2str(self, t): if not t: return '' ans = str(t.val) if t.left or t.right: ans += '(' + self.tree2str(t.left) + ')' if t.right: ans += '(' + self.tree2str(t.right) + ')' return ans # V0'' class Solution(object): def tree2str(self, t): if not t: return "" res = "" left = self.tree2str(t.left) right = self.tree2str(t.right) if left or right: res += "(%s)" % left if right: res += "(%s)" % right return str(t.val) + res # V1 # http://bookshadow.com/weblog/2017/06/04/leetcode-construct-string-from-binary-tree/ # Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): def tree2str(self, t): """ :type t: TreeNode :rtype: str """ if not t: return '' ans = str(t.val) if t.left or t.right: ans += '(' + self.tree2str(t.left) + ')' if t.right: ans += '(' + self.tree2str(t.right) + ')' return ans ### Test case : dev # V1' # https://www.polarxiong.com/archives/LeetCode-606-construct-string-from-binary-tree.html class Solution: def tree2str(self, t): """ :type t: TreeNode :rtype: str """ if not t: return '' if not t.left and not t.right: return str(t.val) if not t.left: return str(t.val) + '()' + '(' + self.tree2str(t.right) + ')' if not t.right: return str(t.val) + '(' + self.tree2str(t.left) + ')' return str(t.val) + '(' + self.tree2str(t.left) + ')' + '(' + self.tree2str(t.right) + ')' # V1'' # https://leetcode.com/problems/construct-string-from-binary-tree/discuss/104090/Python-recursion # IDEA : RECURSION class Solution: def tree2str(self, t): """ :type t: TreeNode :rtype: str """ def preorder(root): if root is None: return "" s=str(root.val) l=preorder(root.left) r=preorder(root.right) if r=="" and l=="": return s elif l=="": s+="()"+"("+r+")" elif r=="": s+="("+l+")" else : s+="("+l+")"+"("+r+")" return s return preorder(t) # V1''' # https://leetcode.com/problems/construct-string-from-binary-tree/discuss/151806/Python3%3A-Iterative-Method-Using-stack # IDEA : STACK class Solution(object): def tree2str(self,t): if not t: return "" stack = [] stack.append(t) res = "" while stack: node = stack.pop() if node == ")": res += ")" continue res += "("+str(node.val) if not node.left and node.right: res += "()" if node.right: stack.append(")") stack.append(node.right) if node.left: stack.append(")") stack.append(node.left) return res[1:] # V1'''' # https://leetcode.com/problems/construct-string-from-binary-tree/discuss/103984/Python-Simple-Solution class Solution(object): def tree2str(self, t): """ :type t: TreeNode :rtype: str """ if not t: return "" res = "" left = self.tree2str(t.left) right = self.tree2str(t.right) if left or right: res += "(%s)" % left if right: res += "(%s)" % right return str(t.val) + res # V1''''' # https://leetcode.com/problems/construct-string-from-binary-tree/discuss/104000/Python-Straightforward-with-Explanation class Solution(object): def tree2str(self, t): if not t: return '' left = '({})'.format(self.tree2str(t.left)) if (t.left or t.right) else '' right = '({})'.format(self.tree2str(t.right)) if t.right else '' return '{}{}{}'.format(t.val, left, right) # V2 # Time: O(n) # Space: O(h) class Solution(object): def tree2str(self, t): """ :type t: TreeNode :rtype: str """ if not t: return "" s = str(t.val) if t.left or t.right: s += "(" + self.tree2str(t.left) + ")" if t.right: s += "(" + self.tree2str(t.right) + ")" return s
# V0 # IDEA :RECURSION, BST # IDEA : USE BST'S PROPERTY : # -> FOR EVERY NODE : right > node > left # -> USE ABOVE PROPERTY FOR BST TRIMMING class Solution: def trimBST(self, root, L, R): if not root: return # NOTICE HERE # SINCE IT'S BST # SO if root.val < L, THE root.right MUST LARGER THAN L # SO USE self.trimBST(root.right, L, R) TO FIND THE NEXT "VALIDATE" ROOT AFTER TRIM # THE REASON USE self.trimBST(root.right, L, R) IS THAT MAYBE NEXT ROOT IS TRIMMED AS WELL, SO KEEP FINDING VIA RECURSION if root.val < L: return self.trimBST(root.right, L, R) # NOTICE HERE # SINCE IT'S BST # SO if root.val > R, THE root.left MUST SMALLER THAN R # SO USE self.trimBST(root.left, L, R) TO FIND THE NEXT "VALIDATE" ROOT AFTER TRIM if root.val > R: return self.trimBST(root.left, L, R) root.left = self.trimBST(root.left, L, R) root.right = self.trimBST(root.right, L, R) return root # V1 # https://blog.csdn.net/fuxuemingzhu/article/details/83869684 class Solution: def trimBST(self, root, L, R): """ :type root: TreeNode :type L: int :type R: int :rtype: TreeNode """ if not root: return None if root.val > R: return self.trimBST(root.left, L, R) elif root.val < L: return self.trimBST(root.right, L, R) else: root.left = self.trimBST(root.left, L, R) root.right = self.trimBST(root.right, L, R) return root ### Test case : dev # V1' # https://www.polarxiong.com/archives/LeetCode-669-trim-a-binary-search-tree.html # Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def trimBST(self, root, L, R): """ :type root: TreeNode :type L: int :type R: int :rtype: TreeNode """ if not root: return root if root.val < L: return self.trimBST(root.right, L, R) if root.val > R: return self.trimBST(root.left, L, R) root.left = self.trimBST(root.left, L, R) root.right = self.trimBST(root.right, L, R) return root # V1'' # https://leetcode.com/problems/trim-a-binary-search-tree/discuss/107051/Python-Easy-to-Understand # Time: O(n) # Space: O(lgn) class Solution(object): def trimBST(self, root, L, R): def trim(node): if not node: return None node.left, node.right = trim(node.left), trim(node.right) # Node's value is not within range, # select one or none of its children as replacement. if not (L <= node.val <= R): node = node.left if node.left else node.right return node return trim(root) # V1''' # IDEA : RECURSION # https://leetcode.com/problems/trim-a-binary-search-tree/solution/ class Solution(object): def trimBST(self, root, L, R): def trim(node): if not node: return None elif node.val > R: return trim(node.left) elif node.val < L: return trim(node.right) else: node.left = trim(node.left) node.right = trim(node.right) return node return trim(root) # V1'''' # https://leetcode.com/problems/trim-a-binary-search-tree/discuss/107056/Python-Straightforward-with-Explanation class Solution(object): def trimBST(self, root, L, R): def trim(node): if node: if node.val > R: return trim(node.left) elif node.val < L: return trim(node.right) else: node.left = trim(node.left) node.right = trim(node.right) return node return trim(root) # V2 # Time: O(n) # Space: O(h) class Solution(object): def trimBST(self, root, L, R): """ :type root: TreeNode :type L: int :type R: int :rtype: TreeNode """ if not root: return None if root.val < L: return self.trimBST(root.right, L, R) if root.val > R: return self.trimBST(root.left, L, R) root.left, root.right = self.trimBST(root.left, L, R), self.trimBST(root.right, L, R) return root
# ################################################################# # # DATA STRUCTURE DEMO : Tree # ################################################################# # # build a tree # # https://github.com/OmkarPathak/Data-Structures-using-Python/blob/master/Trees/Tree.py # ################################################################################################################################## # # OP on tree # # Hint # # https://algorithm.yuanbin.me/zh-tw/basics_data_structure/binary_tree.html # # # # # # 1) Pre-order : root -> left -> right # # 2) In-order : left -> root -> right # # 3) Post-order : left -> right -> root # # 4) Breadth first (BFS) : layer 0 -> layer 1 -> ....layer N # # # # # ################################################################################################################################## # # -------------------------------------------------------------- # # CREARTE A TREE # class Node(object): # def __init__(self, data = None): # self.left = None # self.right = None # self.data = data # # for setting left node # def setLeft(self, node): # self.left = node # # for setting right node # def setRight(self, node): # self.right = node # # for getting the left node # def getLeft(self): # return self.left # # for getting right node # def getRight(self): # return self.right # # for setting data of a node # def setData(self, data): # self.data = data # # for getting data of a node # def getData(self): # return self.data # # OP ON TREE # # in this we traverse first to the leftmost node, then print its data and then traverse for rightmost node # def inorder(Tree): # if Tree: # inorder(Tree.getLeft()) # print(Tree.getData(), end = ' ') # inorder(Tree.getRight()) # return # # in this we first print the root node and then traverse towards leftmost node and then to the rightmost node # def preorder(Tree): # if Tree: # print(Tree.getData(), end = ' ') # preorder(Tree.getLeft()) # preorder(Tree.getRight()) # return # # in this we first traverse to the leftmost node and then to the rightmost node and then print the data # def postorder(Tree): # if Tree: # postorder(Tree.getLeft()) # postorder(Tree.getRight()) # print(Tree.getData(), end = ' ') # return # # -------------------------------------------------------------- # if __name__ == '__main__': # # PART 1) : CREATE A TREE # root = Node(1) # root.setLeft(Node(2)) # root.setRight(Node(3)) # root.left.setLeft(Node(4)) # ''' This will a create like this # 1 # / \ # 2 3 # / # 4 # ''' # # PART 2) OP ON TREE : Inorder/Preorder/Postorder # print('Inorder Traversal:') # inorder(root) # print('\nPreorder Traversal:') # preorder(root) # print('\nPostorder Traversal:') # postorder(root) # # OUTPUT: # # Inorder Traversal: root.getLeft().getLeft().getData() -> root.getLeft().getData() -> root.getData() -> root.getRight().getData() # # 4 2 1 3 # # Preorder Traversal: root.getData() -> root.getLeft().getData() -> root.getLeft().getLeft().getData() -> root.getRight().getData() # # 1 2 4 3 # # Postorder Traversal: root.getLeft().getLeft().getData() -> root.getLeft().getData() -> root.getRight().getData() -> root.getData() # # 4 2 3 1 # V1 # https://stackoverflow.com/questions/2358045/how-can-i-implement-a-tree-in-python class Node: """ Class Node """ def __init__(self, value): self.left = None self.data = value self.right = None class Tree: """ Class tree will provide a tree as well as utility functions. """ def createNode(self, data): """ Utility function to create a node. """ return Node(data) def insert(self, node , data): """ Insert function will insert a node into tree. Duplicate keys are not allowed. """ #if tree is empty , return a root node if node is None: return self.createNode(data) # if data is smaller than parent , insert it into left side if data < node.data: node.left = self.insert(node.left, data) elif data > node.data: node.right = self.insert(node.right, data) return node def search(self, node, data): """ Search function will search a node into tree. """ # if root is None or root is the search data. if node is None or node.data == data: return node if node.data < data: return self.search(node.right, data) else: return self.search(node.left, data) def deleteNode(self,node,data): """ Delete function will delete a node into tree. Not complete , may need some more scenarion that we can handle Now it is handling only leaf. """ # Check if tree is empty. if node is None: return None # searching key into BST. if data < node.data: node.left = self.deleteNode(node.left, data) elif data > node.data: node.right = self.deleteNode(node.right, data) else: # reach to the node that need to delete from BST. if node.left is None and node.right is None: del node if node.left == None: temp = node.right del node return temp elif node.right == None: temp = node.left del node return temp return node def traverseInorder(self, root): """ traverse function will print all the node in the tree. """ if root is not None: self.traverseInorder(root.left) print root.data self.traverseInorder(root.right) def traversePreorder(self, root): """ traverse function will print all the node in the tree. """ if root is not None: print root.data self.traversePreorder(root.left) self.traversePreorder(root.right) def traversePostorder(self, root): """ traverse function will print all the node in the tree. """ if root is not None: self.traversePostorder(root.left) self.traversePostorder(root.right) print root.data def main(): root = None tree = Tree() root = tree.insert(root, 10) print root tree.insert(root, 20) tree.insert(root, 30) tree.insert(root, 40) tree.insert(root, 70) tree.insert(root, 60) tree.insert(root, 80) print ("Traverse Inorder") tree.traverseInorder(root) print ("Traverse Preorder") tree.traversePreorder(root) print ("Traverse Postorder") tree.traversePostorder(root) # if __name__ == "__main__": # main()
# Follow up for problem “Populating Next Right Pointers in Each Node”. # # What if the given tree could be any binary tree? Would your previous solution still work? # # Note: # # You may only use constant extra space. # # For example, # # Given the following binary tree, # # 1 # / \ # 2 3 # / \ \ # 4 5 7 # # After calling your function, the tree should look like: # # 1 -> NULL # / \ # 2 -> 3 -> NULL # / \ \ # 4-> 5 -> 7 -> NULL # V0 # BFS # DFS (?) # V1 # https://blog.csdn.net/fuxuemingzhu/article/details/79560379 # IDEA : BFS class Solution: def connect(self, root): if not root: return queue = collections.deque() queue.append(root) while queue: _len = len(queue) for i in range(_len): node = queue.popleft() ### IF NOT LAST NODE, POINT NEXT TO FIRST NODE IN THE QUEUE if i < _len - 1: node.next = queue[0] if node.left: queue.append(node.left) if node.right: queue.append(node.right) return root ### Test case # dev # V1' # IDEA BFS # https://leetcode.com/problems/populating-next-right-pointers-in-each-node-ii/discuss/389389/Simply-Simple-Python-Solutions-Level-order-traversal-and-O(1)-space-both-approach class Solution(object): def connect(self, root): if not root: return root q = [] q.append(root) tail = root while len(q) > 0: node = q.pop(0) if node.left: q.append(node.left) if node.right: q.append(node.right) if node == tail: node.next = None tail = q[-1] if len(q) > 0 else None else: node.next = q[0] return root # V1'' # https://www.bbsmax.com/A/pRdBoNL2zn/ class Solution(object): def connect(self, root): """ :type root: TreeLinkNode :rtype: nothing """ if root: tmp,tmp1,tmp2 = root,None,None while tmp: if tmp.left: if tmp1: tmp1.next = tmp.left tmp1 = tmp.left if not tmp2: tmp2 = tmp1 if tmp.right: if tmp1: tmp1.next = tmp.right tmp1 = tmp.right if not tmp2: tmp2 = tmp1 tmp = tmp.next self.connect(tmp2) # V2
""" Represent the input m as a vector with (k − 1) components over Zp, where p is prime: m = (ak−1,...,a1); • Choose the polynomial P(x) = ak−1xk−1 +···+a1x (remark that P(0) = 0 - this property will be used for decoding); • Encode m as the vector y = (P(1), P(2),...,P(n)), where n = k + 2s, y = (y1,...,yn). """ print("---------- Input data ----------") m: str = "29" initial_m = int(m) print('m =', m) p = 11 # input() print('p =', p) k = len(m) + 1 print('k =', k) s = 1 print('s =', s) n = k + 2 * s print('n =', n) def modulo_p(a, p): """ :param a: number a :param p: prime number p (Zp) :return: a % p """ return a % p def convert_to_base_p(m, p): """ Function for computing the base p equivalent of a number m. :param m: number m :param p: base :return: a string representing the number m in base_p """ res = "" while m: digit = int(m % p) res += str(digit) if digit < 10 else chr(ord('A') + digit - 10) m = m // p # reversing string res = res[::-1] return res print("----- m as vector in Z(p) ------") m = convert_to_base_p(int(initial_m), p) # type str print("m =", initial_m, "in base", p, "is", m) def m_as_vector(m): """ Method for converting m ∈ Z(p) into a vector of coefficients for polynomial P(X). :param m: input m as string :return: m represented as vector with k-1 elements """ res = [] for c in m: res.append(int(c)) # returned reversed vector: return res[::-1] m = m_as_vector(m) print("P(X) =", m) def compute_polynomial_horner(coef, point): """ Function for computing the value of a polynomial in a given point using Horner. :param coef: vector of coefficients (ex: coef = (a2=2, a1=7)) :param point: value of polynomial in point value: P(point) = ... :return: computed polynomial (in Zp) """ res = coef[-1] for i in range(0, len(coef) - 1): res = res * point + coef[i] return modulo_p(res, p) def compute_polynomial(coef, point): """ Function for computing the value of a polynomial in a given point using Horner. :param coef: vector of coefficients (ex: coef = (a2=2, a1=7)) :param point: value of polynomial in point value: P(point) = ... :return: computed polynomial (in Zp) """ res = 0 xn = point # instead of computing the pow at every step, we will memorize the previously computed result # and multiply it by 'point' for i in range(0, len(coef)): res += xn * coef[i] xn *= point return modulo_p(res, p) def compute_y(n, m): """ Function for computing the encoding of input m as a vector y[] of size n. :param n: n = k + 2 * s :param m: input m represented as a vector of (k-1) Zp elements, where p is prime :return: y = (y1, y2, ..., yn) representing the encoding of input m """ encoded_m = [] for index in range(0, n): # P(1), P(2), ..., P(n): y_index = modulo_p(compute_polynomial(m, index + 1), p) # y_index = modulo_p(compute_polynomial_horner(m, index + 1), p) encoded_m.append(y_index) return encoded_m print("------- m encoded as y[] -------") y = compute_y(n, m) print("y =", y)
import sys sys.stdin = open("input.txt") def be_upper(words): return words.upper() phrase = input() print(be_upper(phrase)) #The_headline_is_the_text_indicating_the_nature_of_the_article_below_it.
numbers = [3,9,4,7,5,0,1,2,6,8] def quick_sort(numbers): N = len(numbers) if N <= 1: return numbers else: pivot = numbers[0] # 우선 첫번째 값을 둠 left, right = [], [] # 빈 리트를 만들어줌 # 지금 numbers[0]인 3보다 작은애들은 left에, 큰 애들은 right에 넣어줌. for idx in range(1,N): # numbers[0]이 피봇의 자리니까. if numbers[idx] > pivot: right.append(numbers[idx]) else: left.append(numbers[idx]) sorted_left = quick_sort(left) sorted_right = quick_sort(right) # 지금은 [0,1,2] 3 [4,5,6,7] # L Pivot R # 그냥 이렇게만 있음. return [*sorted_left, pivot, *sorted_right] # *는 언팩킹임. print(numbers) print(quick_sort(numbers))
from affine import Affine from alberti import Alberti from atbash import Atbash from caesar import Caesar import os def clear(): """Clears text off the console screen""" os.system('cls' if os.name == 'nt' else 'clear') def print_underlined(text): """Prints the text underlined with ='s""" print(text) print('=' * len(text)) def run_console_ui(): """Runs the console user interface Allows the user to encrypt or decrypt a message, and to select which kind of cipher to use""" main_menu = [ '1: Encrypt a Message', '2: Decrypt a Message', 'Q: Quit'] cipher_menu = [ '1: Affine Cipher', '2: Alberti Cipher', '3: Atbash Cipher', '4: Caesar Cipher', 'B: Back to Main Menu', 'Q: Quit'] quit_ui = False while not quit_ui: # prompt 1: choose to encrypt or decrypt clear() print_underlined('Secret Messages!') print('Choose to encrypt or decrypt a message:') [print(option) for option in main_menu] user_choice = input('> ') if user_choice == '1': cipher_method = 'encrypt' elif user_choice == '2': cipher_method = 'decrypt' elif user_choice.upper() == 'Q': break else: continue # prompt 2: choose which cipher to use while True: clear() print_underlined('Secret Messages! {} MODE'.format(cipher_method.upper())) print('Which cipher would you like to use for {}ion?:'.format(cipher_method)) [print(option) for option in cipher_menu] cipher_choice = input('> ') if cipher_choice == '1': clear() print_underlined('Affine Cipher | {} Mode'.format(cipher_method.title())) print("Please provide two numbers as the key for the Affine Cipher") # get the keys, loop through input until a valid number is provided affine_key_a = '' while not isinstance(affine_key_a, int): affine_key_a = input('Enter the first key number: ') try: affine_key_a = int(affine_key_a) except ValueError: print('please provide an integer...') else: if not Affine.is_valid_key_a(affine_key_a): print('The first key cannot share any common factors (other than 1)') print('...with the length of the alphabet: {}'.format(len(Affine.ALPHABET))) print('...hint: try an odd number (but, not 13)') input('press enter to try again...') affine_key_a = '' affine_key_b = '' while not isinstance(affine_key_b, int): affine_key_b = input('Enter the second key number: ') try: affine_key_b = int(affine_key_b) except ValueError: print('please provide an integer...') cipher = Affine(affine_key_a, affine_key_b) elif cipher_choice == '2': outer_ring = 'ABCDEFGIKLMNOPQRSTVWXZ1234' inner_ring = 'hdveqylrijtcbpxwosmzfnakgu' while True: clear() print_underlined('Alberti Cipher | {} Mode'.format(cipher_method.title())) print('This cipher models an ancient device that aligns two disks:') print('an outer disk with Plain Text, and an inner disk with Ciphertext') print('Enter the inner ring character to align with outer ring A:') print('Outer Ring: {}'.format(outer_ring)) print('Inner Ring: {}'.format(inner_ring)) key = input('> ') key = key.lower() if key in inner_ring: inner_ring = Alberti.rotate_cipher(inner_ring, key) clear() print_underlined('Alberti Cipher') print('This cipher models an ancient device that aligns two disks:') print('an outer disk with Plain Text, and an inner disk with Ciphertext') print('Enter the inner ring character to align with outer ring A:') print('Outer Ring: {}'.format(outer_ring)) print('Inner Ring: {}'.format(inner_ring)) if input('Is this right [Y/n]?').lower() != 'n': break cipher = Alberti(key=key, cipher_disk=inner_ring) elif cipher_choice == '3': clear() print_underlined('Atbash Cipher | {} Mode'.format(cipher_method.title())) cipher = Atbash() elif cipher_choice == '4': clear() print_underlined('Caesar Cipher | {} Mode'.format(cipher_method.title())) cipher = Caesar() elif cipher_choice.upper() == 'B': break elif cipher_choice.upper() == 'Q': quit_ui = True break else: continue # get the user's message and translate it using the chosen cipher & method users_message = input('Input a message to {}: '.format(cipher_method)) # validate input for OTP is at least as long as the message long_enough = False while not long_enough: one_time_pad = input('please enter a one time pad: ') # otp text must be at least as long as the message to be encrypted if cipher_method == 'encrypt' and len(one_time_pad) >= len(users_message): long_enough = True # otp text might be shorter for decrypt because of the spaces added for 5 char block output... elif cipher_method == 'decrypt' and len(one_time_pad) >= len(users_message) - int(len(users_message)/6): long_enough = True else: print('sorry, the one time pad must be at least as long as your message. Please try again...') translation = getattr(cipher, cipher_method)(users_message, one_time_pad) print('Translation: {}'.format(translation)) input('press enter to continue...') print('bye!') if __name__ == '__main__': run_console_ui()
class Car: color = "" def description(self): description_string = "This is a %s car." % self.color # we'll explain self parameter later in task 4 return description_string car1 = Car() car2 = Car() car1.color = "blue" car2.color = "red" print(car1.description()) print(car2.description())
# ask for age # 18-21 wristband # 21+ normal entry # too young import sys try: age = int(input("How old are ya lad?")) except: print("Valid numbers please!") sys.exit() print(age) if age >= 21: print('cul') elif age >= 18: print('cul') else: print('get lost lad')
class ContactList(list): def search(self, name): """Return all contacts that contain the search value in their name.""" matching_contacts = [] for contact in self: if name in contact.name: matching_contacts.append(contact) return matching_contacts class Contact: all_contacts = ContactList() def __init__(self, name, email): self.name = name self.email = email self.all_contacts.append(self)
name = "John" age = 17 print(name == "John" or age == 17) # checks that either name equals to "John" OR age equals to 17 print(name == 'John' and age != 23)
class MyClass: variable = 'hi' def foo(self): # we'll explain self parameter later in task 4 print("Hello from function foo") my_object = MyClass() # variable "my_object" holds an object of the class "MyClass" that contains the variable and the "foo" function
print('ur age pls') age = input() print('how tall r u') heigh = input() print(''' Aha you,re %r age old and %r heavy.Nice to know ''' % (age, heigh))