text
stringlengths
37
1.41M
try: import numpy as np def rotate(times,dir="right"): np_dir= np.empty(9) np_matrix= np.arange(1,10) np_changer= np.arange(1,10) #EX: right(-2) == left(+2) if times < 0: times= abs(times) if dir == "right": dir = "left" elif dir == "left": dir = "right" if dir=="right": np_dir= np.array([3,0,1,6,4,2,7,8,5]) elif dir=="left": np_dir= np.array([1,2,5,0,4,8,3,6,7]) #Iterating the indexes and overwriting the values for time in range(times): for index in range(9): np_changer[index]= np_matrix[np_dir[index]] np_matrix = np_changer np_changer= np.arange(1,10) return np_matrix def RotateMatrix(): dirn= str(input("\nMove to which Direction( l or r): ")) #First priority : right if nothing else is true dirn= "left" if dirn.startswith("l") or dirn.startswith("L") else "right" times= int(input("Rotate to {0} by how many times: ".format(dirn))) array= rotate(times,dirn) matrix= array.reshape(1,3,3) # Go one dimn down matrix= matrix[0] print("After rotating {0} times to the {1}, the matrix will look like: \n\n".format(str(times),dirn)) for x in range(len(matrix)): for y in range(3): print("\t",matrix[x][y],end=" ") print("") if __name__ == "__main__": RotateMatrix() except ImportError: def rotate(times,dir="right"): dir_index= list() matrix= list(range(1,10)) changer= list(range(1,10)) #EX: right(-2) == left(+2) if times < 0: times= abs(times) if dir == "right": dir = "left" elif dir == "left": dir = "right" if dir=="right": dir_index= [3,0,1,6,4,2,7,8,5] elif dir=="left": dir_index= [1,2,5,0,4,8,3,6,7] #Iterating the indexes and overwriting the values for time in range(times): for index in range(9): changer[index]= matrix[dir_index[index]] matrix = changer changer= list(range(1,10)) return matrix def RotateMatrix(): dirn= str(input("\nMove to which Direction(l or r [Default: r]): ")) dirn= "left" if dirn.startswith("l") or dirn.startswith("L") else "right" times= int(input("Enter how many times you want to rotate the matrix to the {0}: ".format(dirn))) array= rotate(times,dirn) print("After moving {0} times to the {1}, the matrix will look like: \n\n".format(str(times),dirn)) for num in range(1,10): print("\t",array[num-1],end=" ") if num%3==0: print("") if __name__ == "__main__": RotateMatrix()
#Functions only for list manupulation #Copies data from list to other list and deletes original def cutlist(froms, to): try: for x in range(len(froms)): to.append(froms[x]) for x in range(len(to)): froms.remove(froms[0]) return to; except IndexError: IndexException= "{ IndexError: argument 2 values should be left null }" return IndexException #Copies data from a list to another without deleting original def copylist(froms, to): for x in range(len(froms)): to.append(froms[x]) return to; #Randlist function for creating a random list of integers def randlist(strt, end, args=5): from random import randint try: arr= []; while True: num= randint(strt, end) arr.append(num); if len(arr) is args: break; return arr except ValueError: ValueException= "{ ValueError: rangrand function argument2 should be larger than argument1 }" return ValueException #random.choice edited, allows multiple choices def randchoices(arr,num=1): from random import randint times= len(arr); newarr= []; for x in range(num): randnum= randint(0,times-1); newarr.append(arr[randnum]) return newarr; #Loop function for creating instance loops as list def looper(x, y,z=1): arr=[]; if x<y: z=z else: if z<0: z=z else: z=-z for args in range(x, y, z): arr.append(args) return arr #Index function 2ndV , returns multiple values if multiple nums true def find(arr,num): arr2 =[]; for c in range(len(arr)): if arr[c] == num : arr2.append(c) if len(arr2) is 1: return arr2[0]; elif len(arr2)> 1: return arr2 else: return None; def remove(arr,index): lst= [] copylist(arr,lst) if index == len(lst) - 1 : lst.remove(lst[index]) else: lst= [] for arg in range(len(arr)): if arg == index: continue lst.append(arr[arg]) return lst
word = str(input("Enter word: ")) letter = str(input('Enter letter to search from word: ')) count = 0 for ltr in word: if ltr == letter: count+=1 print(f"Letter '{letter}' was repeated {count} times in the word")
""" Objective Today, we're learning about Key-Value pair mappings using a Map or Dictionary data structure. Check out the Tutorial tab for learning materials and an instructional video! Task Given names and phone numbers, assemble a phone book that maps friends' names to their respective phone numbers. You will then be given an unknown number of names to query your phone book for. For each queried, print the associated entry from your phone book on a new line in the form name=phoneNumber; if an entry for is not found, print Not found instead. """ if __name__ == '__main__': n = int(input()) split_input = [input().split(' ') for i in range(n)] phonebook = {name: number for name, number in split_input} while True: try: name = input() if name in phonebook: print('{}={}'.format(name, phonebook[name])) else: print('Not found') except: break
# Return none if arguments or flags are not valid # george import random def SpONgeBoBtEXt(args): #initialize spongetext variable spongetext = "" for char in args[0]: #check if the character is in the alphabet if char.isalpha(): random_num = random.random() #change the character to a capital letter if random_num > 0.5: spongetext += char.upper() #change the character to a lowercase letter else: spongetext += char.lower() #if the character is not in the alphabet, add it to the output without changing else: spongetext += char return spongetext # Creates an Array of favorite songs where you can add or remove songs song_list = [] def djooshAdd(args): if args not in song_list: song_list += args return "Song successfully added" else: return "Song already added" def djooshRemove(args): if args in song_list: song_list.remove(args) return "Song successfully removed" else: return "Song does not exist"
import torch from myModel import Net from utils.utils import * import matplotlib.pyplot class TrainModel: def __init__(self): self.lossFunction = torch.nn.MSELoss() self.neuralNetwork = Net(INPUT_LAYER_SIZE, HIDDEN_LAYER_SIZE, OUTPUT_LAYER_SIZE).double() self.optimizerBatch = torch.optim.SGD(self.neuralNetwork.parameters(), lr=LEARN_SPEED) # load the training data data pairedTensor = torch.load(FILE_PATH) self.inputTensor = pairedTensor.narrow(1, 0, 2) # just the first 2 columns self.outputTensor = pairedTensor.narrow(1, 2, 1) # just the last column def train(self): """ Following the example from file train_Batch.py declare and train your ANN """ lossList = [] averageLossList = [] batchCount = int(NUMBER_OF_RANDOM_POINTS / BATCH_SIZE) splitInputData = torch.split(self.inputTensor, BATCH_SIZE) splitOutputData = torch.split(self.outputTensor, BATCH_SIZE) for epoch in range(EPOCH_COUNT): lossSum = 0 for batchIndex in range(batchCount): # we compute the output for this batch prediction = self.neuralNetwork(splitInputData[batchIndex].double()) # we compute the loss for this batch loss = self.lossFunction(prediction, splitOutputData[batchIndex]) # we save it for graphics lossList.append(loss) # we add to the sum for the average list lossSum += loss.item() # we set up the gradients for the weights to zero (important in pytorch) self.optimizerBatch.zero_grad() # we compute automatically the variation for each weight (and bias) of the network loss.backward() # we compute the new values for the weights self.optimizerBatch.step() averageLossList.append(lossSum / batchCount) # we print the loss for all the dataset for each 10th epoch if epoch % 100 == 99: y_pred = self.neuralNetwork(self.inputTensor.double()) loss = self.lossFunction(y_pred, self.outputTensor) print('\repoch: {}\tLoss = {:.5f}'.format(epoch, loss)) matplotlib.pyplot.plot(averageLossList) matplotlib.pyplot.show() def saveToFile(self): """ Save your trained network in file myNetwork.pt """ torch.save(self.neuralNetwork.state_dict(), NETWORK_FILE_PATH)
stack = [] # Add in entries stack.append('a') stack.append('b') stack.append('c') # The last entry added was 'c' so the first entry that comes out will be 'c' out = stack.pop() print(out) # 'c'
#!/usr/bin/env python # coding: utf-8 # In[1]: # 986. Interval List Intersections class Solution(object): def intervalIntersection(self, firstList, secondList): """ :type firstList: List[List[int]] :type secondList: List[List[int]] :rtype: List[List[int]] """ # ANSWER 03122021 ans = [] i = j = 0 while i < len(firstList) and j < len(secondList): # check if firstList[i] intersects secondList[j]. # lo - the startpoint of the intersection # hi - the endpoint of the intersection lo = max(firstList[i][0], secondList[j][0]) hi = min(firstList[i][1], secondList[j][1]) if lo <= hi: ans.append([lo, hi]) if firstList[i][1] < secondList[j][1]: i +=1 else: j +=1 return ans
#!/usr/bin/env python # coding: utf-8 # In[6]: # 57. Insert Interval class Solution(object): def insert(self, intervals, newInterval): """ :type intervals: List[List[int]] :type newInterval: List[int] :rtype: List[List[int]] """ # SECOND TRY 03132021 new_start, new_end = newInterval idx, n = 0, len(intervals) output = [] # add all intervals before newInterval while idx<n and new_start > intervals[idx][0]: output.append(intervals[idx]) idx +=1 # add newInterval # if no overlap, then add the interval if not output or output[-1][1] < new_start: output.append(newInterval) # if there is an overlap, merge with the last interval else: output[-1][1] = max(output[-1][1], new_end) # add the remaining intervals, merge with newInterval if needed while idx < n: start, end = intervals[idx] # if no overlap, just add an interval if output[-1][1] < start: output.append(intervals[idx]) # if with overlap, merge with the last element in the output else: output[-1][1] = max(output[-1][1], end) idx += 1 return output # # FIRST TRY 03132021 # intervals.append(newInterval) # intervals.sort() # ans = [intervals[0]] # for i in range(1, len(intervals)): # if ans[-1][1] < intervals[i][0]: # ans.append(intervals[i]) # else: # ans[-1][1] = max(ans[-1][1], intervals[i][1]) # return ans
# 基于个人理解的深度优先算法 20210520 TianzeGao def search_depth_first(g, s): s -= 1 marked_nodes = [s] node_list = [s] current_node=s while len(node_list) != 0: for arc in range(0, len(g[0])): if g[current_node][arc] == 1: g[current_node][arc] = 0 for node in range(current_node + 1, len(g)): if g[node][arc] == -1: if node not in marked_nodes: node_list.insert(0,node) marked_nodes.append(node) current_node = node_list[0] break if 1 not in g[current_node]: node_list.remove(current_node) if len(node_list) != 0: current_node = node_list[0] print("可达点为:") print(sorted([i+1 for i in marked_nodes])) return 0 if __name__ == '__main__': G = [[1, 1, 0, 0, 0, 0, 0, 0, 0], [-1, 0, 1, 1, 1, 0, 0, 0, 0], [0, -1, -1, 0, 0, 1, 0, 0, 0], [0, 0, 0, -1, 0, -1, 1, -1, 0], [0, 0, 0, 0, -1, 0, 0, 1, 1], [0, 0, 0, 0, 0, 0, -1, 0, -1]] search_depth_first(G, 1) # 输入G矩阵和几号点
#Import required modules and classes import time from datetime import datetime, timedelta import csv from flight_search import FlightSearch from notification_manager import NotificationManager #Create search and notification objects notification_manager = NotificationManager() flight_search = FlightSearch() #retrieve destinations file and set origin city, in this case London file = "locations.csv" ORIGIN_CITY_IATA = "LON" #If the destination cities do not have IATA codes, the following section adds IATA codes in the 3rd column with open(file,"r") as f: reader = csv.reader(f,delimiter=',') writer = csv.writer(open('locations_IATA.csv', 'w',newline="")) data = [] for row in reader: if row[2] == "": row[2] = flight_search.get_destination_code(row[0]) data.append(row) writer.writerows(data) # Searching for flights between tomorrow and 6 months from today tomorrow = datetime.now() + timedelta(days=1) six_month_from_today = datetime.now() + timedelta(days=(6 * 30)) while True: with open("locations_IATA.csv", "r") as locations: reader = csv.reader(locations,delimiter=',') #Check flights for each destination using Teqiula API for row in reader: flight = flight_search.check_flights( ORIGIN_CITY_IATA, row[2], from_time=tomorrow, to_time=six_month_from_today ) #If the flight prices are lower than the users lowest price. Twilio API sends the flight details to the user via sms. try: if flight.price < float(row[1]): notification_manager.send_sms( message=f"Low price alert! Only £{flight.price} to fly from {flight.origin_city}-{flight.origin_airport} to {flight.destination_city}-{flight.destination_airport}, from {flight.out_date} to {flight.return_date}." ) except AttributeError: pass #5 minute wait before checking again to prevent sending too many requests to the APIS. time.sleep(300)
x = 1 if x == 1: # indented four spaces print("x is 1.") print("Hello World") print(x) myfloat = 1.2 print(myfloat) myfloat = float(1.2) print(myfloat) mystring = 'hi' print(mystring) one = 1 two = 2 three = one + two print(three) hello = "hello" world = "world" helloWorld = hello + " " + world print(helloWorld) a, b = 3, 4 print(a, b) mylist = [] mylist.append(1) mylist.append(2) mylist.append(3) print(mylist) for x in mylist: print(x) number = 1 + 2 + 3 / 4.0 print(number) remainder = 11 % 3 print(remainder) squared = 7 ** 2 print(squared) helloworld = "je" * 10 print(helloworld) even_numbers = [2, 4, 6, 8] odd_numbers = [1, 3, 5, 7] all_numbers = even_numbers + odd_numbers print(all_numbers * 2) name = "IK" ki = 12 print("LP %s %d" % (name, ki)) data = ("John", "Doe", 53.44) format_string = "Hello %s %s. Your current balance is $%f" test = format_string print(format_string % data) astring = "Hello world" print(astring[3:7]) print(astring.upper()) print(astring.lower()) print(astring.startswith("1 "))
class User: """ Class that generates new instances of users """ user_list = [] # Empty user list def __init__(self,first_name,last_name,number,email): def test_save_user(self): """def test_save_user(self): """ test_save_user test case to test if the user object is saved into the users array """ self.new_user.save_user_details() # saving the new user self.assertEqual(len(User.user_list), 1) test_save_user test case to test if the user object is saved into the user list """ self.new_user.save_user_details() # saving the new user self.assertEqual(len(User.user_list), 1) # docstring removed for simplicity self.first_name = first_name self.last_name = last_name self.phone_number = number self.email = email def save_user(self): """ saves the new user account """ User.user_list.append(self) @classmethod def display_users(cls): """ a method that crates and returns the class users """ return cls.users_list
import re class Set: def __init__(self, parent, rank): self.parent = parent self.rank = rank # Размер дерева def find_set(set, a): if a == set[a].parent: return a set[a].parent = find_set(set, set[a].parent) return set[a].parent def union_set(set, a, b): a = find_set(set, a) b = find_set(set, b) if a != b: if set[a].rank > set[b].rank: set[b].parent = a set[a].rank += set[b].rank else: set[a].parent = b set[b].rank += set[a].rank with open("input.txt", "r") as fin: set = [] k_p = 0 line_p = '' for line in fin: k = 0 j = 0 for i in range(len(line)): if line_p and line_p[i] == ' ': j += 1 if line[i] != ' ': continue set.append(Set(len(set), 0)) l = len(set) - 1 if i >= 1 and line[i - 1] == ' ': union_set(set, l, l - 1) if line_p and line_p[i] == ' ': b = l-k-k_p+j-1 union_set(set, l, b) k += 1 line_p = line k_p = k count = 0 for i in range(len(set)): if find_set(set, i) == i: count+= 1 with open('output.txt', 'w') as fout: fout.write(str(count))
#3-8 travel = ['shanghai','xian','beijing','xizang','xinjiang'] print(travel) print(sorted(travel)) print(travel) print(sorted(travel,reverse=True)) print(travel) travel.reverse() print(travel) travel.reverse() print(travel) travel.sort() print(travel) travel.sort(reverse=True) print(travel) #3-9 invite = ['teddy','john','mark'] print('一共邀请了' + str(len(invite)) + '位嘉宾。') #3-10 like = ['1','2','3','4','5','6','7','9','8'] like.sort() print(like) like.sort(reverse=True) print(like) print(sorted(like)) print(sorted(like,reverse=True)) like.reverse() print(like) like.reverse() print(like) print(len(like))
import random N_GAME=3 def main(): """ Rock Paper Scissor Game Game: Each player chooses a move simultaneously from the choices: Rock Paper Scissors if they choose the same move its a tie rock beats scissor scissor beats paper paper beats rock In this game human plays against the computer. The game is repeated N_Games times if it is a win 1 pt.If the player loses -1. if both chose the same move its a tie. """ welcome() total_score=0 # let's get the ai move for i in range(N_GAME): ai_move=get_ai_move() # let's get the human move human_move=get_human_move() # decide the winner winner=get_winner(ai_move,human_move) total_score = update_score(winner,total_score) print("AI move is ",ai_move) print("The winner is",winner) print("total score is: ",total_score) print("") def update_score(winner,total_score): if winner=="ai": total_score -=1 if winner=="human": total_score +=1 if winner=="tie": total_score=0 return total_score def get_ai_move(): """ This function returns the move of the AI """ number=random.randint(1,3) if number==1: return "rock" if number==2: return "paper" if number==3: return "scissor" def get_human_move(): """ This function returns the move of human """ while True: human_move=input("Enter your move: ") if valid_move(human_move): return human_move print("invalid move") return human_move def valid_move(human_move): """ This function validates if user input is either rock paper or scissor returns a boolean value >>> valid_move("rock") True >>> valid_move("paper") True >>> valid_move("scissor") True >>> valid_move("unicorn") False """ if human_move=="rock": return True if human_move=="paper": return True if human_move=="scissor": return True else: return False def get_winner(ai_move,human_move): """ >>> get_winner("rock","scissor") "ai" >>> get_winner("paper","scissor") "human" >>> get_winner("rock","rock") "tie" """ if ai_move==human_move: return "tie" if ai_move=="rock": if human_move=="paper": return "human" return "ai" if ai_move=="paper": if human_move=="scissor": return "human" return "ai" if ai_move=="scissor": if human_move=="rock": return "human" return "ai" def welcome(): print("Welcome to the exciting game of Rock Paper Scissor") print("You will play",str(N_GAME),"games against the AI") print("Rock beats Scissor") print("Scissor beeats paper") print("Paper beats Rock") print("-----------------------------------------------------") print("") if __name__ == '__main__': main()
def czyAnagram(): s1 = input("wpisz słowo, sprawdzę czy jest anagramem ") s2 = input("wpisz drugie słowo ") alist1 = list(s1) alist2 = list(s2) alist1.sort() alist2.sort() #print (alist1) pos = 0 matches = True while pos < len(s1) and matches: if alist1[pos]==alist2[pos]: pos = pos + 1 else: matches = False print (matches) if __name__ == "__main__": czyAnagram() def czyPalindrom(): s1 = input("wpisz słowo sprawdzę czy jest palindromem ") lista1 = list(s1) lista2 = list(s1) lista2.reverse() #print (lista1) #print (lista2) pos = 0 matches = True while pos < len(s1) and matches: if lista1[pos] == lista2[pos]: pos = pos + 1 else: matches = False print(matches) if __name__ == "__main__": czyPalindrom()
## ## Author: Kristina Striegnitz ## ## Version: Fall 2011 ## ## This file defines a ball class that can move in two dimensions and ## can bounce off other balls. It also bounces off the edges of the ## screen. import pygame import math from vector import Vector class MovingBall : r = 25 #velocity vector speedlimit = Vector(10000.0, 10000.0) color = pygame.color.Color('darkgreen') def __init__ (self, x, y, r, color, xv, yv): self.position = Vector(float(x), float(y)) self.r = r self.color = color self.v = Vector(float(xv),float(yv)) def stop_v (self): """ Reset the velocity to 0 if it gets very close. """ if self.v.length() < 3: self.v = Vector (0,0) def draw (self, window): pygame.draw.circle(window, self.color, (int(self.position.x),int(self.position.y)), self.r)
locations = ['Alaska', 'Ireland', 'New Zealand', 'Antartica', 'The Moon'] print(locations) print(sorted(locations)) print(locations) print(sorted(locations, reverse=True)) print(locations) locations.reverse() print(locations) locations.reverse() print(locations) locations.sort() print(locations) locations.sort(reverse=True) print(locations)
pets = [] August = {'kind': 'dog', 'owner_name': 'Douglas'} sammy = {'kind': 'cat', 'owner_name': 'David'} JJ = {'kind': 'cat', 'owner_name': 'Oliver'} pets.append(August) pets.append(sammy) pets.append(JJ) for pet in pets: print("\nkind: " + pet['kind']) print("belongs to: " + pet['owner_name'])
current_users = ['gusgus', 'frogger', 'Dtucker', 'miranda', 'admin'] current_users_lower = [] for user in current_users: current_users_lower.append(user.lower()) new_users = ['Gusgus', 'frogger', 'firefly', 'parsival', 'gregory'] for user in new_users: if user.lower() in current_users_lower: print("Username already in use, please choose another name") else: print("Username accepted")
usernames = ['gusgus', 'frogger', 'Dtucker', 'miranda', 'firefly', 'admin'] if usernames: for user in usernames: if user == "admin": print("hello admin, would you like to see a status report?") else: print("greetings " + user + "! thank you for logging in.") else: print("we need to find some users!")
cities = { "Manteca": {'country': 'USA', 'population': 120000, 'fact': 'home town'}, "Fresno": {'country': 'USA', 'population': 1200000, 'fact': 'College'}, "Boise": {'country': 'USA', 'population': 180000, 'fact': 'New home'}, } for city, info in cities.items(): print(city) print("\t" + info['country']) print("\t" + str(info['population']) + " people") print("\t" + info['fact'])
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9] for numb in numbers: if numb == 1: print(str(numb) + "st") elif numb == 2: print(str(numb) + "nd") elif numb == 3: print(str(numb) + "rd") else: print(str(numb) + "th")
import numpy n,m = map(int, input().split(" ")); matrix = [] for i in range(n): matrix.append(list(map(int, input().split(" ")))) matrix = numpy.array(matrix); print(numpy.transpose(matrix)) print(matrix.flatten())
''' Given an array nums containing n distinct numbers in the range [0, n], return the only number in the range that is missing from the array. Follow up: Could you implement a solution using only O(1) extra space complexity and O(n) runtime complexity? Example 1: Input: nums = [3,0,1] Output: 2 Explanation: n = 3 since there are 3 numbers, so all numbers are in the range [0,3]. 2 is the missing number in the range since it does not appear in nums. Example 2: Input: nums = [0,1] Output: 2 Explanation: n = 2 since there are 2 numbers, so all numbers are in the range [0,2]. 2 is the missing number in the range since it does not appear in nums. Example 3: Input: nums = [9,6,4,2,3,5,7,0,1] Output: 8 Explanation: n = 9 since there are 9 numbers, so all numbers are in the range [0,9]. 8 is the missing number in the range since it does not appear in nums. Example 4: Input: nums = [0] Output: 1 Explanation: n = 1 since there is 1 number, so all numbers are in the range [0,1]. 1 is the missing number in the range since it does not appear in nums. Constraints: n == nums.length 1 <= n <= 104 0 <= nums[i] <= n All the numbers of nums are unique. ''' ''' Constraints of this problem is to just use extra O(1) space and O(n) as time ''' class Solution: def missingNumber(self, nums): # convert the list to a set since it faster than the List # and we cannot take advantage of the constant look up time of the dictionary since we cannot convert the list to a dict in no time. num_set = set(nums) for number in range(len(nums)+1): if number not in num_set: return number s = Solution() print(s.missingNumber([1,2,3])) # missing: 0 print(s.missingNumber([0,1,3])) # missing: 2
''' some fucking boy was playing with the natural numbers and trying to rearrange them so he has come up with a silly idea to to put the odd numbers first and then the even numbers like this 1 2 3 4 5 5 6 7 8 after rearranging 1 3 5 7 2 4 6 8 ''' def nonOptimaGetPos(n, k): h = {} # check upon the number range is even or odd to be able to decide where the last index of # odd numbers will be if n % 2 == 0: even_idx = int(n / 2) + 1 else: even_idx = int(n // 2) + 2 # iterate over the numbers and hash each number with its pos as key odd_idx = 1 for i in range(n): value = i + 1 if value % 2 != 0: h[odd_idx] = value odd_idx += 1 else: h[even_idx] = value even_idx += 1 return h[k] def optimaGetPos(n, k): #check if the pos in the even side or in the odd side if n % 2 == 0: mid = int(n / 2) # odd number if k <= mid: return int(k * 2 - 1) else: # even number in the even part pos = k - mid return int(pos * 2) # odd range else: mid = int(n / 2) + 1 # odd number in odd part if k <= mid: return int(k * 2 - 1) else: # even number in the even part pos = k - mid return int(pos * 2) if __name__ == '__main__': n, k = map(int, input().split()) print(nonOptimaGetPos(n, k)) print(optimaGetPos(n, k))
def formTeams(students): teams = { 1: [], 2: [], 3: [] } # encode the students into the dict for i in range(len(students)): if students[i] == 1: teams[1].append(i+1) elif students[i] == 2: teams[2].append(i+1) elif students[i] == 3: teams[3].append(i+1) number_of_teams = min(len(teams[1]), len(teams[2]), len(teams[3])) return number_of_teams, teams if __name__ == '__main__': n = int(input()) students = list(map(int, input().split())) # print number of teams number_of_teams, teams = formTeams(students) # each team consistes of 3 students print(number_of_teams) # print indecies for i in range(number_of_teams): print(teams[1][i], teams[2][i], teams[3][i]) print()
''' here you are going to iterate over the n and check if the guess is valid or not ''' def getSqrt(n): guess = 1 while guess ** 2 != n: guess += 1 return guess if __name__ == '__main__': num = int(input()) print(getSqrt(num)) ''' the runtime for this algorithm is O(sqrt(n)) because the iteration condition is equievelant to this: guess != sqrt(n) '''
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sat Apr 21 16:28:27 2018 @author: xingyichong """ import math HANDLE_MISSING = '' # define the way to handle the node without right child. class Tree: def __init__(self, value = None, left = None, right = None): self.value = value self.leftTree = left self.rightTree = right def __str__(self): if self.leftTree == None or self.rightTree == None: return '\nThis node is leaf: ' + str(self.value) return '\nThis node is: ' + str(self.value) + '\nLeft Child is: ' + str(self.leftTree.value) + '\nRight Child is: ' + str(self.rightTree.value) def _nextlvl(cur_level): # return the length of the parent level. if type(cur_level) != int: raise ValueError('The level# must be an integer!') return math.ceil(cur_level/2) def _get_Hierarchy(mystring): # return a int list containing the tree hierarchy. lvl_list = [len(mystring)] i = 1 while lvl_list[-1]>1: lvl_list.append(_nextlvl(lvl_list[i-1])) i += 1 return lvl_list def Build_Tree(mystring): # the main function to build a tree without hashing. Tree_dict = dict([ ((1,i),Tree(mystring[i])) for i in range(len(mystring))]). # Dumping in the leaf info. height = math.ceil(math.log(len(mystring),2)) + 1 Tree_hierarchy = _get_Hierarchy(mystring) for i in range(2, height+1): # i is the index of level. for j in range(Tree_hierarchy[i-1]): # j is the index of node in current level. Left_value = Tree_dict[i-1,j*2].value right_child = None try: Right_value = Tree_dict[i-1,j*2+1].value right_child = Tree_dict[i-1,j*2+1] except: Right_value = HANDLE_MISSING Tree_dict[(i,j)] = Tree(Left_value+Right_value, Tree_dict[i-1,j*2], right_child) return Tree_dict ################### # Test: def main(mystring): TreeDict = Build_Tree(mystring) for i in TreeDict: print(i,':', TreeDict[i]) if __name__ == "__main__": x = 'dsawsdw1jcmsetkspbx[' main(x)
""" 9. 점수 구간에 해당하는 학점이 아래와 같이 정의되어 있다. 점수를 입력했을 때 해당 학점이 출력되도록 하시오. 81~100 : A 61~80 : B 41~60 : C 21~40 : D 0~20 : F """ num = int(input('점수를 입력해주세요 : ')) if 80 < num < 101 : print('A') elif 60 < num < 81 : print('B') elif 40 < num < 61 : print('C') elif 20 < num < 41 : print('D') elif 0 <= num < 101 : print('F') else : print('error')
"""4. 삼각형의 가로와 높이를 받아서 넓이를 출력하는 함수를 작성하시오.""" width = float(input('삼각형의 가로를 입력하세요 : ')) height = float(input('삼각형의 높이를 입력하세요 : ')) print('삼각형의 넓이 : {}'.format(round(width*height/2, 3)))
num =int(input("enter a number:")) result = num**0.5 print("the square root of %0.3f is %f"%(num,result))
import os import csv #Creating a path for the budget data bankbudget = os.path.join("budget_data.csv") # Open csv file with open(bankbudget, 'r') as csvfile: #Split the csv file readCSV = csv.reader(csvfile, delimiter=',') #Read header first csv_header= next(readCSV) #Get the number of months row_count = sum(1 for row in readCSV) csvfile.seek(0) next(readCSV) print ("Financial Analysis") print ("------------------------------") print (f"Total Months : {row_count}") # Assigning values at 0 so that totalmonths = 0 totalvalue = 0 averagePL = [] highPL = 0 lowPL = 0 sum_profit = 0 lowdate = '' highdate = '' # In my four loop the white line goes from for row down to total value because thats what Ive specified # as a scope. The reason I have loops is to test the same code and test it on multiple numbers/objects # Whatever is in scope gets called for all different objects. for row in readCSV: profit = int(row[1]) totalvalue = totalvalue + profit averagePL = averagePL +[profit] # We need to find the highest profit and lowest. Max is a function to give us the highest. Put it towards averagePL and you will #get the greatest profit. Same with the lowest if(int(row[1]) == max(averagePL)): highPL = max(averagePL) highdate = row[0] if(int(row[1]) == min(averagePL)): lowPL = min(averagePL) lowdate = row[0] print(f"Total: {totalvalue}") print(f"Average Change: {sum(averagePL)/len(averagePL)}") #Do all the writing and printing.....n???? f = open("budget_results.txt", "w") f.write("Budget Info\n") #Greatest increase of profits (current month total - previous total) print ("Highest Increase " + highdate + " " + str(highPL)) f.write("Highest Increase " + highdate + " " + str(highPL)+" \n") print("Highest Decrease " + lowdate + " " + str(lowPL)) f.write ("Highest Decrease " + lowdate + " " + str(lowPL)+" \n")
import heapq import argparse import sys import os.path if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument('Path') args = parser.parse_args() string = str(args) #a,'\'',c,'\'',d = string a,b,c = string.split('\'') print "Your file is : "+b if not os.path.exists(b): raise Exception("The file specified does not exist!") with open(b,"r") as f: n = f.readline() try: n += 1 if n <= 0: raise Exception("Number of lines needs to be greater than 0") except TypeError: print "The number needs to be an integer" lines = open(b).readlines() heap = heapq.nlargest(int(n),lines,len) print "".join(heap)
import sys import os import re def doStuff(orig,list2): checker = [] def replaceOkay(orig,el0,el1): def allGood(checker,pos,l1): for i in range(0,l1): if pos+i in checker: return False for i in range(0,l1): checker.append(pos+i) return True #First find the occurences of substring occurs = [m.start() for m in re.finditer(el0, orig)] #Now see if any of those elements were changed earlier for pos in occurs: if allGood(checker,pos,len(el1)): return pos return 0 for el in list2: if el[0] in orig: #print "replacing "+el[0]+" with "+el[1] pos = replaceOkay(orig,el[0],el[1]) if pos != 0: print "replacing "+el[0]+" with "+el[1] print "Position is : "+str(pos) temp = orig[(pos+len(el[0])):] print "Temp is "+temp print orig[0:pos] orig = orig[0:pos]+el[1] print "Left part now is : "+orig orig += temp print orig return orig if __name__ == '__main__': filename = sys.argv[1] if not os.path.exists(filename): raise Exception("Your file ain't nowhere bro") with open(filename,'r') as f: lines = f.readlines() for line in lines: orig, rest = line.split(';') rest = rest.strip('\n') if len(rest)%2 == 1:raise Exception("Not even!") listin = rest.split(',') list2 = zip(listin[0::2],listin[1::2]) answer = doStuff(orig,list2) print answer
import exifread from File import File """ Purpose: This class defines a picture file, as distinguished by the "*.jpg" file extension. This class inherits from the File class. """ class PictureFile(File): # Constructor def __init__(self, filename, source_directory, destination_directory): # Call the Constructor of the super class super(PictureFile, self).__init__(filename, source_directory, destination_directory) if self.date_created == "": # Open the picture file for reading the meta data (binary mode) f = open((self.source_directory + self.filename), 'rb') # Return Exif tags exif_tags = exifread.process_file(f) for tag in exif_tags.keys(): # print "Current tag: %s" % tag # if tag in ('EXIF DateTimeOriginal'): if tag == 'EXIF DateTimeOriginal': date_file = str(exif_tags[tag]) photo_date = date_file[0:10] self.date_created = str.replace(photo_date, ":", "-") self.destination_directory += self.date_created + '/' # print "Picture created on %s" % self.date_created # print "Picture dest dir: %s" % self.destination_directory if self.date_created == "": # print "***EXIF Date Created not found!!!***" self.destination_directory += 'no_date_available' + '/' else: self.destination_directory += self.date_created + '/'
#use of zip function a=[1,2,3] #list b=(7,8,9) #tuple for i,j in zip(a,b): #zip is used to aggregate values in a n b print(i+j) # import string file=open('new.txt','w') for l,k in zip(string.ascii_lowercase[0::2],string.ascii_lowercase[1::2]): file.write(l + k + "\n" ) file.close() #abc3.txt import string letters=string.ascii_lowercase + ' ' slice1=letters[0::3] slice2=letters[1::3] slice3=letters[2::3] with open('abc3.txt','w') as f: for s1,s2,s3 in zip(slice1,slice2,slice3): f.write(s1 + s2 +s3 + "\n") #txt26.txt #import string
#find the error and solve def foo(a=1, b=2): return a + b x = foo() - 1 #a function should always have paranthesis print(x) #alternative def foo(): global c c = 1 return c foo() print(c) #create a function that takes any string as input # and return the number of words in the string def sentence(): str='hi how are you' i=len(str.split()) return i print(sentence()) #words.txt file=open('words1.txt','r') nws=file.read() strl=len(nws.split()) print(strl) file.close() #words2.txt file=open('words2.txt','r') txt=file.read() srt=txt.replace(',',' ') srtw=len(srt.split()) print(srtw) file.close() #squareroot import math print(math.sqrt(9)) #cosine import math print(math.cos(1)) #create a text file and generate english alphabets in it import string with open("letters.txt", "w") as file: for letter in string.ascii_lowercase: file.write(letter + "\n") file.close() import string file=open('english.txt','w') for letter in string.ascii_uppercase: file.write(letter + "\n") file.close()
def student_discount(price): price = price - (price * 10) / 100 return price def additional_discount(newprice): newprice = newprice - (newprice * 5) / 100 return newprice selling_price = 600 # applying both discounts simultaneously print(additional_discount(student_discount(selling_price))) #Calculate the value of mathematical expression x*(x+5)^2 where x= 5 using lambda expression. import math result= (lambda x:(x*(x+5))**2)(5) print(result)
letters = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j"] #print out the second item of the list print(letters[1]) #expected output [d,e,f] using slicing print(letters[3:6]) #expected output [a,b,c] using slicing print(letters[:3]) #expected output[i] print(letters[8:9]) #expected output [i] using negative index print(letters[-2]) #expected output [h,i,j] usnig negative index print(letters[-3:]) # expected output [a,c,e,g,i] using slicing print(letters[::2])
def arithmetic_arranger(problems, isResult = False): row1 = "" row2 = "" separator = "" result = "" def addColumn(row): column = " " # four space character if row != "": row += column return row def addOperandus(row, len1, len2, rightAlign, operandus): if len1 > len2: row += str(operandus) else: row += " " * (rightAlign) + str(operandus) return row # validate the argument (problems): if len(problems) > 5: return "Error: Too many problems." for problem in problems: # accept only addition and subtraction: operator = "-" if "-" in problem else "+" if "+" in problem else "" if not(operator): return "Error: Operator must be '+' or '-'." # split the string at the operator to get the numbers: numbers = problem.split(operator); operandus1 = None for num in numbers: # removes any whitespace from the beginning or the end: num = num.strip() # constructs an integer number from string: try: integer = int(num) # check if the num is a floating number: floating = float(num) if integer != floating: return "Error: Numbers must only contain digits." except: return "Error: Numbers must only contain digits." # check the value of integer: if integer > 9999: return "Error: Numbers cannot be more than four digits." # save the operandus for later use: if operandus1 is None: operandus1 = integer else: operandus2 = integer # the given argument checked and did not find any error: len1 = len(str(operandus1)) len2 = len(str(operandus2)) rightAlign = abs(len1 - len2) # start to build the return string: # create row1: # add column if necessary: row1 = addColumn(row1) # add extra space before the first operandus: row1 += " " # add the first operandus: row1 = addOperandus(row1, len1, len2, rightAlign, operandus1) # create row2: # add column if necessary: row2 = addColumn(row2) # add the operator and an extra space: row2 += operator + " " # add the second operandus: row2 = addOperandus(row2, len2, len1, rightAlign, operandus2) # create separator: # add column if necessary: separator = addColumn(separator) biggestDigit = len1 if len1 > len2 else len2 separator += "-" * (2 + biggestDigit) # create result: if isResult: if operator == "-": res = str(operandus1 - operandus2) else: res = str(operandus1 + operandus2) # add column if necessary: result = addColumn(result) result += " " * (biggestDigit + 2 - len(res)) + res if isResult: arranged_problems = """{} {} {} {}""" return arranged_problems.format(row1, row2, separator, result) else: return f"""{row1} {row2} {separator}"""
import deck from player_class import Player d = deck.create_deck() #d= [('Spades', 10), ('Diamonds', 'King'), ('Hearts', 'Ace'), ('Spades', 'Ace'), ('Diamonds', 7), ('Diamonds', 4)] deck.shuffle_deck(d) print(d) def check_total(a,b): if a > 21 and b is True: print("You Lost") exit() if a > 21 and b is False: print("You Won!!") exit() h = [d.pop(),d.pop()] c = [d.pop()] def update_hand(h,c): hm = Player(h) com = Player(c) print("Your") hm.display() m = hm.total() print(f"Your total is {m}") check_total(m, True) print("Computer's") com.display() t= 0 for x in range(0,len(c)): if c[x][1] =='Ace': if (t+11)<= 21: t+=11 else: t+=1 elif c[x][1] =='King' or c[x][1] == 'Queen' or c[x][1] == 'Jack': t+=10 else: t+=c[x][1] print(f"Computer's total is {t}") check_total(t, False) print("---------------------------") return (m,t) def check_result(m): if abs(21-m[0])<abs(21-m[1]): print ("You Won ") elif abs(21-m[0])==abs(21-m[1]): print ("Draw") else: print ("You Lost") def ip(): u = str(input("Do you want to HIT or STAY?")) print(u) if u.lower() == 'hit': h.append(d.pop()) update_hand(h,c) ip() if u.lower() == 'stay': c.append(d.pop()) f= update_hand(h,c) check_result(f) update_hand(h,c) ip()
# Petit programme pour calculer si M1 ou M2 a le plus d'influence sur la plage. """Entrée""" M1 = float(input()) M2 = float(input()) N = float(input()) """AIRE ENTRE M1 ET M2 = (M2-M1)""" """Aire de M1""" AM1 = M1+((M2-M1)/2) """Aire de M2""" AM2 = N - M2 +((M2-M1)/2) winner = 5 if AM2 < AM1: winner = 1 elif AM2 > AM1: winner = 2 elif AM1 == AM2: winner = 0 else: print("Something went wrong..") print(winner)
def binary_search (arr, n): mid = arr[len(arr)//2] print (mid) arr = [1,2,3,4,5,6] binary_search (arr,6) # 1st: what if the search number isn't in the array? # 2nd: what if the number is found? # 3rd: conditional for the lower and upper half based on our find input
import unittest import pytest from myparser import * class ParserTest(unittest.TestCase): def test_init(self): text = "1+1" i = Parser(text) assert(i._current_token.value == 1) assert(i._current_token.type == INTEGER) def test_eat_happy(self): text = "1+1" i = Parser(text) try: i._eat(INTEGER) except: pytest.fail("It shouldn't throw") assert(i._current_token.value == '+') assert(i._current_token.type == PLUS) def test_eat_wrong(self): text = "1+1" i = Parser(text) try: i._eat(PLUS) except: assert(i._current_token.value == 1) assert(i._current_token.type == INTEGER) i = Parser(text) try: i._eat(EOF) except: assert(i._current_token.value == 1) assert(i._current_token.type == INTEGER) def test_term_happy(self): text = "1+1" i = Parser(text) try: res = i._term() assert(res == 1) except: pytest.fail("It shouldn't throw") def test_term_happy(self): text = "1+1" i = Parser(text) try: res = i._term() res = i._term() pytest.fail("PLUS is not a term") except: assert(res.expr.value == 1) def test_expr_multidigit(self): text = "10+1" i = Parser(text) result = i.expr() assert(type(result) == BinOp) assert(result.op == PLUS) assert(result.left.value == 10) assert(result.right.value == 1) def test_expr_zero(self): text = "1-1" i = Parser(text) result = i.expr() assert(type(result) == BinOp) assert(result.op == MINUS) assert(result.left.value == 1) assert(result.right.value == 1) def test_expr_negative(self): text = "6-7" i = Parser(text) result = i.expr() assert(type(result) == BinOp) assert(result.op == MINUS) assert(result.left.value == 6) assert(result.right.value == 7) def test_expr_mul(self): text = "2*3" i = Parser(text) result = i.expr() assert(type(result) == BinOp) assert(result.op == MUL) assert(result.left.value == 2) assert(result.right.value == 3) def test_expr_div(self): text = "4/2" i = Parser(text) result = i.expr() assert(type(result) == BinOp) assert(result.op == DIV) assert(result.left.value == 4) assert(result.right.value == 2) def test_expr_multi_operands(self): text = "6-7+0+10" i = Parser(text) result = i.expr() assert(type(result) == BinOp) assert(result.op == PLUS) assert(type(result.left) == BinOp) assert(type(result.right) == NumOp) assert(result.right.value == 10) text = "6-7*2" i = Parser(text) result = i.expr() assert(type(result) == BinOp) assert(result.op == MINUS) assert(type(result.left) == NumOp) assert(type(result.right) == BinOp) assert(result.right.right.value == 2) text = "(3+2)*8" i = Parser(text) result = i.expr() assert(type(result) == BinOp) assert(result.op == MUL) assert(type(result.left) == BinOp) assert(type(result.right) == NumOp) assert(result.right.value == 8) text = "(3*2)*8" i = Parser(text) result = i.expr() assert(type(result) == BinOp) assert(result.op == MUL) assert(type(result.left) == BinOp) assert(type(result.right) == NumOp) assert(result.right.value == 8) text = "(((3)))" i = Parser(text) result = i.expr() assert(type(result) == NumOp) assert(result.value == 3)
import numpy as np a = np.zeros((3, 3)) n = 0 for i in range(3): for j in range(3): a[i, j] = n n += 1 print(a) print(np.sum(a, axis=0))
#!/usr/bin/python3 def multiply_by_2(my_dict): new_dict = {} for n in my_dict: new_dict[n] = my_dict[n] * 2 return new_dict
#!/usr/bin/python3 """ Input/ output module """ def number_of_lines(filename=""): """ Number of lines in a file function """ with open(filename, encoding="utf-8") as my_file: l = 0 for line in my_file: l += 1 return l
#!/usr/bin/python3 """ Input output module """ def read_file(filename=""): """ Read a file with a with statement """ with open(filename, encoding="utf-8") as my_file: print(my_file.read())
class Vehicle: # 定义交通工具类 Country = 'China' def __init__(self, name, speed, load, power): self.name = name self.speed = speed self.load = load self.power = power def run(self): print('开动啦...') class Subway(Vehicle): # 地铁 def __init__(self, name, speed, load, power, line): Vehicle.__init__(self, name, speed, load, power) self.line = line def run(self): print('地铁%s号线欢迎您' % self.line) Vehicle.run(self) line13 = Subway('中国地铁', '180m/s', '1000人/箱', '电', 13) line13.run()
import re text = "JGood is a handsome boy, he is cool, clever, and so on..." print(re.sub(r'\s+', '-', text)) # 执行结果如下: JGood-is-a-handsome-boy,-he-is-cool,-clever,-and-so-on... # 其中第二个函数是替换后的字符串;本例中为'-' 第四个参数指替换个数。默认为0,表示每个匹配项都替换。 # 使用re替换string中每一个匹配的子串后返回替换后的字符串。 # 格式: re.sub(pattern, repl, string, count) # re.sub还允许使用函数对匹配项的替换进行复杂的处理。 # 如:re.sub(r'\s', lambda m: '[' + m.group(0) + ']', text, 0);将字符串中的空格' '替换为'[ ]' print(re.sub(r'\s+', lambda m:'['+m.group(0)+']', text,0)) # 执行结果如下: JGood[ ]is[ ]a[ ]handsome[ ]boy,[ ]he[ ]is[ ]cool,[ ]clever,[ ]and[ ]so[ ]on...
# n = 10 # while True: # n = int(n/2) # print(n) # if n == 0: # break # def trues(n): # n = int(n/2) # return n # result = trues(10) # result2 = trues(result) # result3 = trues(result2) # print( result,"\n",result2,"\n",result3) # import sys # sys.setrecursionlimit(100) # def trues(n): # n = int(n/2) # print(n) # if n > 0: # trues(n) # trues(10) # import sys # sys.setrecursionlimit(100) # def trues(n): # n = int(n/2) # print(n) # if n > 0: # trues(n) # print(n) # trues(10) 函数是一层一层推出的。 # def trues(n,count): # print(n,count) # if count < 5: # trues(n/2,count+1) # trues(180,1) # def trues(n,count): # print(n,count) # if count < 5: # trues(n/2,count+1) # return # # res = trues(180,1) # print(res) # def trues(n,count): # print(n,count) # if count < 5: # return trues(n/2,count+1) # else: # return n # res = trues(180,1) # print("res",res) 解决了返回值问题
# 给你一个整数数组 arr,请你帮忙统计数组中每个数的出现次数。 # # 如果每个数的出现次数都是独一无二的,就返回 true;否则返回 false。 class Solution: def uniqueOccurrences(self, arr: List[int]) -> bool: res=dict() for i in arr: res[i]=res.get(i,0)+1 temp=res.values() if len(temp)==len(set(temp)): return True return False
import datetime ano = datetime.date.today().year entrada = input('Digite o nome do arquivo que deseja abrir, juntamente com sua extensão: ') saida = input('Digite o nome da saída: ') lista1 = list() lista2 = list() with open(f'{entrada}', 'w') as arq: for r in range(2): nome = input('Digite seu nome: ') lista1.append(nome) nascimento = int(input('Digite o ano de seu nascimento: ')) lista2.append(nascimento) arq.write(nome) arq.write(' ') arq.write(str(nascimento)) arq.write('\n') with open(f'{saida}', 'w') as pasta: for i in range(2): idade = ano - lista2[i] pasta.write(lista1[i]) pasta.write(' ') if idade < 18: pasta.write('Menor de idade\n') elif idade == 18: pasta.write('Entrando na maioridade\n') else: pasta.write('Maior de idade\n')
""" Try, Except, Else, Finally Dica de quando e onde tratar código: TODA ENTRADA DO USUARIO DEVE SER TRATADA! OBS.: A função do usuário é DESTRUIR seu sistema num = 0 # Else -> É executado somente se nao ocorrer o erro. try: num = int(input('Informe um numero: ')) except ValueError: print('Valor incorreto') else: print(f'Voce digitou {num}') # Finally -> try: num = int(input('Informe um numero: ')) except ValueError: print('Você não digitou um valor válido.') else: print(f'Você digitou o número {num}') finally: print('Executamos o finally') # Obs.: O bloco finally é SEMPRE executado. Independente se houver exceção ou não. # O finally é ,geralmente, utilizado para fechar ou desalocar recursos. # Exemplo mais complexo ERRADO def dividir(a, b): return a / b num1 = int(input('Informe o primeiro numero: ')) try: num2 = int(input('Informe o segundo numero: ')) except ValueError: print('O valor precisa ser numerico') try: print(dividir(num1, num2)) except NameError: print('Valor incorreto') # Exemplo mais complexo CORRETO # OBS.: Você é responsável pelas entradas das suas funções. Então, trate-as! def dividir(a, b): try: return int(a) / int(b) # Tratamento genérico except ValueError: #except: print('Valor incorreto') return 'Ocorreu um problema' except ZeroDivisionError: return 'Não é possível realizar uma divisão por zero' num1 = input('Informe o primeiro numero: ') num2 = input('Informe o segundo numero: ') print(dividir(num1, num2)) # Exemplo mais complexo CORRETO - Semi - Genérico # OBS.: Você é responsável pelas entradas das suas funções. Então, trate-as! def dividir(a, b): try: return int(a) / int(b) except (ValueError, ZeroDivisionError) as err: return f'Ocorreu um problema: {err}' num1 = input('Informe o primeiro numero: ') num2 = input('Informe o segundo numero: ') print(dividir(num1, num2)) """
cont = 0 lista_dicionario = [] while True: variavel = 'variavel_' + str(cont) # valor pode ser substituido por pegar valor automaticamente valor = input('Digite valor: ') if valor: lista_dicionario.append({variavel: valor}) cont += 1 else: break # Verificando se está tudo certo print('---------------------------') for i in lista_dicionario: for chave, valor in i.items(): print(f'{chave} = {valor}') print('--------------------------')
""" Dunder Main e Dunder Name Dunder -> Double Under Dunder Name -> __name__ Dunder Main -> __main__ Em Python, são utilizados Dunder para criar funções, atributos, propriedades e etc utilizando Double Under para não gerar conflito com os nomes desses elementos na programação. # Na linguagem C, temos um programa da seguinte forma: int main(){ return 0; } # Na linguagem Java, temos um programa da seguinte forma: public static void main(String[] args){ } # Em Python, se executarmos um módulo Python diretamente na linha de comando, internamente o Python atribuira à variavel __name__ o valor __main__ indicando que este modulo é o módulo de execução principal. Main -> Significa principal. from funcoes_com_parametro import soma_impares print(soma_impares([1, 2, 3, 4, 5, 6])) """ import primeiro import segundo
""" _Loop for_ Loop -> Estrutura de repetição For -> Uma dessas estruturas #Python for item in interavel: //execução do loop Utilizamos loops para iterar sobre sequências ou sobre valores iteráveis Exemplos de iteráveis: - String nome = 'Geek University' - String lista = [1, 3, 5, 7, 9] - Range numeros = range(1,10) nome = 'Geek University' lista = [1,,3, 5, 7, 9] números = range(1,10) for letra in nome: print(letra) for numero in lista: print(numero) for numero in range(1,10): print(numero) Obs.: range(valor_inicial, valor_final) #Vai do 1 ao 9!!! """ """ Enumerate: ((0, 'G'), (1, 'e'), (2, 'e'),...) for indice, letra in enumerate(nome): print(nome[indice]) for _, letra in enumerate(nome): Obs.: Quando não precisamos de um valor, podemos descartá-lo print(letra) utilizando um underline (_) for valor in enumerate(nome): print(valor) qtd = int(input('Quantas vezes esse loop deve rodar?' )) soma = 0 for n in range(1, qtd): num = int(input(f'Informe o {n}/{qtd} valor: ')) soma += soma + num print(f'A soma é {soma}') nome = 'Geek university' for letra in nome: print(letra, end='') Tabela de Emojis Unicode: https://apps.timwhitlock.info/emoji/tables/unicode """
""" Reversed Obs.: Não confunda com a função reverse() que estudamos em listas A função reverse() só funciona em listas. Já a função reversed() funciona com qualquer iterável. Sua função é inverter o iterável. A função reversed() retorna um iteravel chamado List Reverse Iterator # Exemplos listas = [1, 2, 3, 4, 5] res = reversed(lista) print(res) print(type(res)) # Podemos converter o elemento retornado para uma Lista, Tupla ou Conjunto # Lista print(list(reversed(lista))) # Tupla print(tuple(reversed(lista))) # Obs.: Em conjuntos, não definimos a ordem dos elementos # Conjunto(set) print(set(lista))) # Podemos iterar sobre o reversed for letra in reversed('Geek University'): print(letra, end=' ') print('\n') # Podemos fazer o mesmo sem o uso do for print(''. join(list(reversed('Geek University')))) # Já vimos como fazer isso mais fácil com o slice de strings print('Geek University'[::-1]) # Podemos também utilizar o reversed() para fazer um loop for reverso for n in reversed(range(0, 10)): print(n) # Apesar que também já vimos como fazer isso utilizamos o próprio range() for n in range(9, -1, -1): print(n) """
""" Função com retorno numeros = [1, 2, 3] ret_pop = numeros.pop() print(f'Retorno de pop: {ret_pop}') ret_pr = print(numeros) print(f'Retorno de print: {ret_pop}') # Exemplo função def quadrado_de_7(): print(7 * 7) ret = quadrado_de_7() print(f'Retorno {ret}') OBS.: Em Python, quando uma função não retorna nenhum valor, o retorno é None # Vamos refatorar essa função para que ela retorne o valor # Obs.: Funções Python que retornam valores, devem retornar estes valores com a palavra reservada return # Obs.: Não precisamos necessariamente criar uma variavel para receber retorno de uma função. Podemos passa a execução da função para outras funções. def quadrado_de_7(): return 7 * 7 ret = quadrado_de_7() print(f'Retorno {ret}') print(f'Retorno: {quadrado_de_7() + 1}') # Refatorando a primeira função def diz_oi(): return 'oi' alguem = 'Pedro' print(diz_oi() + alguem) Obs.: Sobre a palavra reservada return 1 - Ela finaliza a função, ou seja, ela sai da execução da função; 2 - Podemos ter, em uma função, diferentes returns; 3 - Podemos, em uma função, retornar qualquer tipo de dados e até mesmo múltiplos valores; # Exemplos 1 - Ela finaliza a função, ou seja, ela sai da execução da função; def diz_oi(): return 'oi' print('Estou sendo executado após o retorno...') # Nunca será executado print(diz_oi()) # Exemplo 2 - Podemos ter, em uma função, diferentes returns; def nova_funcao(): variavel = True if variavel: return 4 elif variavel is None: return 3.2 return 'b' print(nova_funcao) # Exemplo 3 - Podemos, em uma função, retornar qualquer tipo de dados e até mesmo múltiplos valores; def outra_funcao(): return 2, 3, 4, 5 num1, num2, num3, num4 = outra_funcao() print(num1, num2, num3, num4) print(outra_funcao()) # Tupla print(type(outra_funcao())) # Vamos criar uma funçao para jogar a moeda from random import random def joga_moeda(): #Gera um numero pseudo-randomico entre 0 e 1 valor = random() if valor > 0.5: return 'Cara' return 'Coroa' print(joga_moeda()) # Erros comuns na utilização do retorno, que na verdade nem é erro, mas sim codificação desnecessaria def eh_impar(): numero = 5 if numero % 2 != 0: return True return False # Não foi necessario utilizar um else print(eh_impar()) """
""" Verificar se o numero é quadrado perfeito """ def quadrado_perfeito(n): if n == int(n) and n != 0: raiz = n ** 0.5 if raiz == int(raiz) and n > 0: return f'O número {n} é um quadrado perfeito' else: return f'O número {n} não é um quadrado perfeito' n = int(input('Digite um valor para saber se é quadrado perfeito: ')) print(quadrado_perfeito(n))
""" Módulo Collection - Deque https://docs.python.org/3/library/collections.html#collections.deque Podemos dizer que o deque é uma lista de alta performance. # Importa from collection import deque # Criando deques deq = deque('geek') print(deq) # Adicionando elementos no deque deq.append('y') # Adiciona no final print(deq) deq.appendleft('k') # Adiciona no começo print(deq) # Remover elementos print(deq.pop()) # Remove e retorna o último elemento print(deq) print(deq.popleft()) #Remove e retorna o primeiro elemento print(deq) """
""" Soma dos elementos acima da diagonal principal da matriz """ from random import randint def soma_diag_superior(matriz): acima_diagonal_principal = [] for l in range(0, 3): for c in range(0, 3): if l < c: acima_diagonal_principal.append(matriz[l][c]) return f'A soma dos delementos acima da diagonal principal possui valor: {sum(acima_diagonal_principal)}' matriz1 = [] for i in range(0, 3): linha = [] for j in range(0, 3): linha.append(randint(0, 10)) matriz1.append(linha) print('-'*20) for i in range(0, 3): for j in range(0, 3): print(f'[{matriz1[i][j]}]', end='') print() print('-'*20) print(soma_diag_superior(matriz1))
""" Soma de algarismos """ def soma(num): result = 0 while num > 0: result += num % 10 num = num // 10 return result n = int(input('Digite um numero para saber a soma de algarismos: ')) print(f'A soma dos algarismos de "{n}" é {soma(n)} ')
""" Pacotes Módulo -> É apenas um arquivo Python, que pode ter diversas funções para utilizarmos Pacote -> É um diretório contendo uma coleção de módulos Obs.: Nas versões 2.X do Pthon, um pacote Python deveria conter dentro dele um arquivo chamado __init__.py Nas versões do Python 3.x não é mais obrigatória a utolização deste arquivo, mas normalmente ainda é utilizado para manter compatibilidade. from geek import geek1, geek2 from geek.university import geek3, geek4 print(geek1.pi) print(geek1.funcao1(4, 6)) print(geek2.curso) print(geek2.funcao2()) print(geek3.funcao3()) print(geek4.funcao4()) from geek.university import funcao1 from geek.university.geek4 import funcao4 print(funcao1(6, 9)) print(funcao4()) """
X = list(map(int, input().split())) if X[0] == X[1]: print(X[2]) elif X[1] == X[2]: print(X[0]) elif X[0] == X[2]: print(X[1]) else: print(0)
# Helper functions are placed here so as not to clutter main files import numpy as np # Converts various types of input data to a binary representation def to_binary(data): if isinstance(data, str): return ''.join([ format(ord(i), "08b") for i in data ]) elif isinstance(data, bytes) or isinstance(data, np.ndarray): return [ format(i, "08b") for i in data ] elif isinstance(data, int) or isinstance(data, np.uint8): return format(data, "08b") else: raise TypeError("Type not supported.")
def fizzbuzz(): fizz_string = "" for i in range(1,101): if(i % 3 == 0) and (i % 5 == 0): fizz_string = fizz_string + " fizzbuzz" elif(i % 3 == 0): fizz_string = fizz_string + " fizz" elif(i % 5 == 0): fizz_string = fizz_string + " buzz" else: str_i = str(i) fizz_string = fizz_string + " " + str_i return fizz_string fizzbuzz()
class Solution: def CheckPermutation(self, s1: str, s2: str) -> bool: if len(s1) != len(s2): return False else: for i in s1: if s1.count(i)!=s2.count(i): return False return True
# -*- coding: utf-8 -*- """ Created on Fri Nov 27 18:57:54 2020 @author: CALVIN """ import turtle a=turtle.Turtle() bg=turtle.Screen() bg.bgcolor('black') a.color('red') a.shape('turtle') a.penup() for i in range(1,150): a.stamp() a.forward(10+i) a.left(20) turtle.done()
#!python class BinaryTreeNode(object): def __init__(self, data): """Initialize this binary tree node with the given data.""" self.data = data self.left = None self.right = None def __repr__(self): """Return a string representation of this binary tree node.""" return 'BinaryTreeNode({!r})'.format(self.data) def is_leaf(self): """Return True if this node is a leaf (has no children).""" # TODO: Check if both left child and right child have no value # return ... and ... if self.left is None and self.right is None: return True return False def is_branch(self): """Return True if this node is a branch (has at least one child).""" # TODO: Check if either left child or right child has a value if self.is_leaf() == True: return False return True def height(self): """Return the number of edges on the longest downward path from this node to a descendant leaf node""" # The reason this works is due to the fact that recursive calls dont remember the past calls until it works # its way back up if not self.root: return 0 return 1 + max(self.height(self.left), self.height(self.right)) class BinarySearchTree(object): def __init__(self, items=None): """Initialize this binary search tree and insert the given items.""" self.root = None self.size = 0 if items is not None: for item in items: self.insert(item) def __repr__(self): """Return a string representation of this binary search tree.""" return 'BinarySearchTree({} nodes)'.format(self.size) def is_empty(self): """Return True if this binary search tree is empty (has no nodes).""" return self.root is None def height(self): """Return the height of this tree (the number of edges on the longest downward path from this tree's root node to a descendant leaf node). TODO: Best and worst case running time: ??? under what conditions?""" # TODO: Check if root node has a value and if so calculate its height if self.root is None: self.size = 0 return self.size else: return self.size def tree_is_empty(self): if self.root is None: return True return False def contains(self, item): """Return True if this binary search tree contains the given item. TODO: Best case running time: ??? under what conditions? TODO: Worst case running time: ??? under what conditions?""" if self.tree_is_empty() is True: return False return self.search(item) # def search(self, item): """Return an item in this binary search tree matching the given item, or None if the given item is not found. TODO: Best case running time: ??? under what conditions? TODO: Worst case running time: ??? under what conditions?""" # Find a node with the given item, if any # node = self._find_node(item) # # TODO: Return the node's data if found, or None # return node.data if ... else None if self.tree_is_empty() is True: return None current_node = self.root if item == current_node.data: return current_node.data while current_node is not None: if current_node.is_leaf() is True and current_node.data != item: return None elif item > current_node.data: current_node = current_node.right elif item < current_node.data: current_node = current_node.left elif item == current_node.data: return current_node.data def insert(self, item): """Insert the given item in order into this binary search tree. TODO: Best case running time: ??? under what conditions? TODO: Worst case running time: ??? under what conditions?""" if self.tree_is_empty(): # If the tree is empty and since we know a binary tree starts with the root node the item that the user # wants to insert becomes the root node self.root = BinaryTreeNode(item) self.size += 1 return parent_node = self._find_parent_node(item) if item > parent_node.data: parent_node.right = BinaryTreeNode(item) elif item < parent_node.data: parent_node.left = BinaryTreeNode(item) self.size += 1 # def _find_parent_node(self, item): # Start with the root node and keep track of its parent current_node = self.root # Checking if the root node is the item the user is looking for or if the tree is empty then we return None # before we start iterating if current_node.data == item or self.tree_is_empty() is True: return None parent = None # No tree is infinite therefore the very bottom level node will be a leaf # at_leaf = False # at leaf is false will always be true but we will implement a condition that can bring us out while current_node is not None: # So if on the first iteration if the current nodes data is equal to the item then we return the parent # is the root node but if its not then we continue and the parent node will be eqaul to the one above the # the current node if current_node.data == item: return parent # If the current nodes data is less than the item then we set the parent node to the current node and move # the current node to the right elif item > current_node.data: parent = current_node current_node = current_node.right elif item < current_node.data: parent = current_node current_node = current_node.left return parent # This space intentionally left blank (please do not delete this comment) def items_in_order(self): """Return an in-order list of all items in this binary search tree.""" items = [] if not self.is_empty(): # Traverse tree in-order from root, appending each node's item self._traverse_in_order_recursive(self.root, items.append) # Return in-order list of all items in tree return items def _traverse_in_order_recursive(self, node, visit): """Traverse this binary tree with recursive in-order traversal (DFS). Start at the given node and visit each node with the given function. TODO: Running time: ??? Why and under what conditions? TODO: Memory usage: ??? Why and under what conditions?""" # Traverse left subtree, if it exists if node.left is not None: self._traverse_in_order_recursive(node.left, visit) # Visit this node's data with given function visit(node.data) # Traverse right subtree, if it exists if node.right is not None: self._traverse_in_order_recursive(node.right, visit) # def _traverse_in_order_iterative(self, node, visit): # """Traverse this binary tree with iterative in-order traversal (DFS). # Start at the given node and visit each node with the given function. # TODO: Running time: ??? Why and under what conditions? # TODO: Memory usage: ??? Why and under what conditions?""" # # TODO: Traverse in-order without using recursion (stretch challenge) # while node is not None: # if node.left.is_leaf() is True: # visit(node.left.data) # node = node.left # # if node.right.is_leaf() is True: # visit(node.right.data) # node = node.right # # def items_pre_order(self): # """Return a pre-order list of all items in this binary search tree.""" # items = [] # if not self.is_empty(): # # Traverse tree pre-order from root, appending each node's item # self._traverse_pre_order_recursive(self.root, items.append) # # Return pre-order list of all items in tree # return items # # def items_pre_order_iterative(self): # """Return a pre-order list of all items in this binary search tree.""" # items = [] # if not self.is_empty(): # # Traverse tree pre-order from root, appending each node's item # self._traverse_pre_order_iterative(self.root, items.append) # # Return pre-order list of all items in tree # return items # def _traverse_pre_order_recursive(self, node, visit): # """Traverse this binary tree with recursive pre-order traversal (DFS). # Start at the given node and visit each node with the given function. # TODO: Running time: ??? Why and under what conditions? # TODO: Memory usage: ??? Why and under what conditions?""" # # TODO: Visit this node's data with given function # visit(node.data) # ... # # TODO: Traverse left subtree, if it exists # if node.left is not None: # self._traverse_pre_order_recursive(node.left, visit) # ... # # TODO: Traverse right subtree, if it exists # if node.right is not None: # self._traverse_pre_order_recursive(node.right, visit) def _traverse_pre_order_iterative(self, node, visit): """Traverse this binary tree with iterative pre-order traversal (DFS). Start at the given node and visit each node with the given function. TODO: Running time: ??? Why and under what conditions? TODO: Memory usage: ??? Why and under what conditions?""" # TODO: Traverse pre-order without using recursion (stretch challenge) while node is not None: visit(node.data) if node.left is not None: node = node.left if node.right is not None: node = node.right def items_post_order(self): """Return a post-order list of all items in this binary search tree.""" items = [] if not self.is_empty(): # Traverse tree post-order from root, appending each node's item self._traverse_post_order_recursive(self.root, items.append) # Return post-order list of all items in tree return items def _traverse_post_order_recursive(self, node, visit): """Traverse this binary tree with recursive post-order traversal (DFS). Start at the given node and visit each node with the given function. TODO: Running time: ??? Why and under what conditions? TODO: Memory usage: ??? Why and under what conditions?""" # TODO: Traverse left subtree, if it exists if node.left is not None: self._traverse_post_order_recursive(node.left, visit) # TODO: Traverse right subtree, if it exists if node.right is not None: self._traverse_post_order_recursive(node.right, visit) # TODO: Visit this node's data with given function visit(node.data) # def _traverse_post_order_iterative(self, node, visit): # """Traverse this binary tree with iterative post-order traversal (DFS). # Start at the given node and visit each node with the given function. # TODO: Running time: ??? Why and under what conditions? # TODO: Memory usage: ??? Why and under what conditions?""" # # TODO: Traverse post-order without using recursion (stretch challenge) # # def items_level_order(self): # """Return a level-order list of all items in this binary search tree.""" # items = [] # if not self.is_empty(): # # Traverse tree level-order from root, appending each node's item # self._traverse_level_order_iterative(self.root, items.append) # # Return level-order list of all items in tree # return items # # def _traverse_level_order_iterative(self, start_node, visit): # """Traverse this binary tree with iterative level-order traversal (BFS). # Start at the given node and visit each node with the given function. # TODO: Running time: ??? Why and under what conditions? # TODO: Memory usage: ??? Why and under what conditions?""" # # TODO: Create queue to store nodes not yet traversed in level-order # queue = ... # # TODO: Enqueue given starting node # ... # # TODO: Loop until queue is empty # while ...: # # TODO: Dequeue node at front of queue # node = ... # # TODO: Visit this node's data with given function # ... # # TODO: Enqueue this node's left child, if it exists # ... # # TODO: Enqueue this node's right child, if it exists # ... # # def test_binary_search_tree(): # # Create a complete binary search tree of 3, 7, or 15 items in level-order # # items = [2, 1, 3] # items = [4, 2, 6, 1, 3, 5, 7] # # items = [8, 4, 12, 2, 6, 10, 14, 1, 3, 5, 7, 9, 11, 13, 15] # print('items: {}'.format(items)) # # tree = BinarySearchTree() # print('tree: {}'.format(tree)) # print('root: {}'.format(tree.root)) # # print('\nInserting items:') # for item in items: # tree.insert(item) # print('insert({}), size: {}'.format(item, tree.size)) # print('root: {}'.format(tree.root)) # # print('\nSearching for items:') # for item in items: # result = tree.search(item) # print('search({}): {}'.format(item, result)) # item = 123 # result = tree.search(item) # print('search({}): {}'.format(item, result)) # # print('\nTraversing items:') # print('items in-order: {}'.format(tree.items_in_order())) # print('items pre-order: {}'.format(tree.items_pre_order())) # print('items post-order: {}'.format(tree.items_post_order())) # print('items level-order: {}'.format(tree.items_level_order())) # if __name__ == '__main__': test_binary_search_tree()
class BinaryNode(object): def __init__(self, data): '''Initalize the binary node with the given data''' self.previous_pointer=None self.data = data self.next_pointer=None def __repr__(self): '''Return a string representation of this node''' return 'Node({!r})'.format(self.data) class DoublyLinkedList(object): def __init__(self, iterable=None): '''Initalize this linked list and append given items if any''' self.head = None self.tail = None self.size = 0 # The amount of nodes in the doubly linked list if iterable is not None: for item in iterable: self.append(item) def __str__(self): """Return a formatted string representation of this linked list.""" items = ['({!r})'.format(item) for item in self.items()] return '[{}]'.format(' -> '.join(items)) def __repr__(self): """Return a string representation of this linked list.""" return 'LinkedList({!r})'.format(self.items()) def items(self): '''Return a list of all items in the linked list''' # This will not be different from the regular linked list because there is no need for the previous property current_node = self.head result_list = [] # Have a empty list so that we can contain all the nodes that we have iterated upon while current_node is not None: result_list.append(current_node.data) # We do this step so that we can continue iterating through the list current_node = current_node.next_pointer return result_list def is_empty(self): '''Returns a boolean value indicating whether or not our linked list is empty or not''' if self.size == 0: return True return False def length_of_linked_list(self): return self.size def get_at_index(self, index): '''Return item at given index or raise Value Error if list index is out of range or return None if list is empty''' # Checks if the index is out of range of the linked list if not (0 <= index < self.size): raise ValueError('List index out of range: {}'.format(index)) # Checks if the linked list is empty if so returns None if self.is_empty() == True: return None else: current_node = self.head counter = 0 if counter == index: return current_node.data while current_node is not None: if counter == index: return current_node.data counter += 1 current_node = current_node.next_pointer def append(self, item): '''Appends an a node to the end of a linked list''' new_node = BinaryNode(item) # To save time complexity we first check if the list is empty if self.is_empty() == True: # If the list is empty then we want to set the head to the new node self.head = new_node else: # Thats why they say that doubly linked lists are easier to work with therefore what is happening is that we # are setting the node that comes before the new node to the tail new_node.previous_pointer = self.tail # The reason that we set the tail to the node before this node and then back again is because since we are # saving time by going directly to the tail we are not keeping in mind the other nodes therefore we have to in # a sense backtrack to the node before and keep that in memory where as opposed to when we are iterating # through the linked list what we can do is that we can keep all of them in memory but that wastes more time # And then to append to simply save time we want to go to the tail directly since we know that when appending # we have to add right on to the end we can go to the tail directly and set its next pointer to the next node self.tail.next_pointer = new_node # Once we set the tails NEXT pointer to the new node we then set the tail to the new node self.tail = new_node # Since we are appending increase the size by 1 self.size += 1 def prepend(self, item): '''Prepends an item to the beginning of a list''' current_node = self.head new_node = BinaryNode(item) # Let us account for our first edge case is if the linked list is empty if self.is_empty() == True: self.head = new_node self.tail = new_node self.size += 1 return else: current_node.previous_pointer = new_node self.head = new_node self.size += 1 def find(self, quality): # Set the current node to be equal to the head current_node = self.head # Iterating through the nodes in the linked list so we do not get a list index error out of range while current_node is not None: # Passing it through the lambda function checking if the current nodes data is equal to the item that the # user is looking for if quality(current_node.data): # If we have found it then we return the current nodes data return current_node.data # But if we did not then iterate to the next node in the doubly linked list current_node = current_node.next_pointer # If we iterate through the entire doubly linked list and do not find the item that the user is looking for then # we return the value None return None def delete(self, item): '''Delete the item from the DoublyLinkedList that the user is looking for''' current_node = self.head previous_node = None print(current_node) # We account for the first edge case and that being is that if we have an empty list if self.is_empty() == True: raise ValueError # Then we have other two edge cases if the user is trying to delete the head or the tail if item == self.get_at_index(0): self.head = current_node.next_pointer elif item == self.get_at_index(self.size - 1): # Take the node where the tail is pointing and set the pointer going back to the previous node which we just # created node_before_the_tail = self.tail.previous_pointer # And then set the tail to the previous node self.tail = node_before_the_tail if self.size == 1: self.head = None self.tail = None # Now we account for the cases where the item the user is trying to delete is not the head or the tail of the # the linked list while current_node is not None: if current_node.data == item: current_node.previous_pointer = previous_node previous_node = current_node.next_pointer current_node = current_node.next_pointer self.size -= 1 Doubly = DoublyLinkedList Binary_Node = BinaryNode
class Athlete: def __init__(self,ht,wt,bodyfat): self.__ht = ht self.__wt = wt self.__bf = bodyfat def get_ht(self): return self.__ht def get_wt(self): return self.__wt def get_bf(self): return self.__bf class Football_Player(Athlete): # inherites athelte traist but also adds more traits-- #position, team --> need 5 traits to create a player # 3 for "athelete, 2 more for football player" def __init__(self,ht,wt,bodyfat,position,team): Athlete.__init__(self,ht,wt,bodyfat) self.__position = position self.__team = team # only need two get clauses because they are accessed in the #super clause def get_position(self): return self.__position def get_team(self): return self.__team
def sleep(): print("You go to sleep after a long day. Get some well deserved rest :)\n\nPlay again? (y/n)\n") choice = input().lower() while True: if choice == "y": return "initial_room" elif choice == "n": return "end" else: print("I don't understand that command...") choice = input().lower()
import sys n = int(sys.stdin.readline()) def level(x, y, divider): divider //= 3 while divider > 1: if (x // divider) % 3 == 1 and (y // divider) % 3 == 1: return divider else: divider //= 3 return 1 def isMidpos(x, y, lv): return (x // lv) % 3 == 1 and (y // lv) % 3 == 1 for y in range(n): for x in range(n): lv = level(x, y, n) DoNotPrint = (x // lv) % 3 == 1 and (y // lv) % 3 == 1 # print(level(x, y, n), end="") print("*" if not DoNotPrint else " ", end="") print()
class Position: x: int y: int def __init__(self, x: int, y: int): self.x = x self.y = y def manhattan(a: Position, b: Position): return abs(a.x - b.x) + abs(a.y - b.y) def middle(a: Position, b: Position): if a.x == b.x: return [Position(a.x, (a.y + b.y) // 2)] if a.y == b.y: return [Position((a.x + b.x) // 2, a.y)] return [Position(a.x, b.y), Position(b.x, a.y)] def p_iter(place): for i, row in enumerate(place): for j, item in enumerate(row): if item != "P": continue yield Position(i, j) def check_social_distancing(place): p_locations = [] for cur in p_iter(place): for prev in p_locations: d = manhattan(prev, cur) if d > 2: continue if d == 1: return 0 if d == 2: mid_list = middle(prev, cur) if any(place[mid.x][mid.y] != "X" for mid in mid_list): return 0 p_locations.append(cur) return 1 def solution(places): return [check_social_distancing(p) for p in places] def main(): assert solution([["POOOP", "OXXOX", "OPXPX", "OOXOX", "POXXP"], ["POOPX", "OXPXP", "PXXXO", "OXXXO", "OOOPP"], ["PXOPX", "OXOXP", "OXPOX", "OXXOP", "PXPOX"], ["OOOXX", "XOOOX", "OOOXX", "OXOOX", "OOOOO"], ["PXPXP", "XPXPX", "PXPXP", "XPXPX", "PXPXP"]]) == [1, 0, 1, 1, 1] if __name__ == '__main__': main()
# 심심 from abc import * class Phone: @staticmethod def row(button): return (button - 1) / 3 @staticmethod def col(button): return (button - 1) % 3 @staticmethod def button_distance(src, dst): return abs(Phone.row(src) - Phone.row(dst)) + abs(Phone.col(src) - Phone.col(dst)) class Hand: __location: int def __init__(self, location): self.__location = location @abstractmethod def press(self, item): pass @abstractmethod def distance(self, item): pass INF = 888 class LeftHand(Hand): def press(self, item): if item in Phone.RIGHT_SIDE: raise ValueError self.__location = item def distance(self, item): if item in Phone.RIGHT_SIDE: return INF elif item in Phone.LEFT_SIDE: return 0 loc = self.__location dist = 0 if loc in Phone.LEFT_SIDE: loc += 1 dist = 3 dist += abs(loc - item) return dist class RightHand(Hand): def press(self, item): if item in Phone.LEFT_SIDE: raise ValueError self.__location = item def distance(self, item): if item in Phone.LEFT_SIDE: return INF elif item in Phone.RIGHT_SIDE: return 0 loc = self.__location dist = 0 if loc in Phone.RIGHT_SIDE: loc -= 1 dist = 3 dist += abs(loc - item) return dist class Person: left: LeftHand right: RightHand default: Hand def __init__(self, default): self.left = LeftHand(10) self.right = RightHand(12) if default == "left": self.default = self.left else: # "right" self.default = self.right def click(self, n): ref = self.default if n == 0: n = 11 ld = self.left.distance(n) rd = self.right.distance(n) if ld < rd: ref = self.left elif ld > rd: ref = self.right ref.press(n) return "L" if ref == self.left else "R" def solution(numbers, hand): answer = "" person = Person(hand) for n in numbers: answer += person.click(n) return answer def main(): assert solution([1, 3, 4, 5, 8, 2, 1, 4, 5, 9, 5], "right") == "LRLLLRLLRRL" assert solution([7, 0, 8, 2, 8, 3, 1, 5, 7, 6, 2], "left") == "LRLLRRLLLRR" assert solution([1, 2, 3, 4, 5, 6, 7, 8, 9, 0], "right") == "LLRLLRLLRL" if __name__ == '__main__': main()
def solution(s): st = [] for ch in s: if st[-1:] == [ch]: st.pop() else: st.append(ch) return 0 if st else 1 def main(): assert solution("baabaa") == 1 assert solution("cdcd") == 0 if __name__ == '__main__': main()
def is_prime(n): if n < 2: return False sq = int(n ** 0.5) for i in range(2, sq + 1): if n % i == 0: return False return True def solution(n): answer = 0 for i in range(2, n + 1): if is_prime(i): answer += 1 return answer def main(): assert solution(10) == 4 assert solution(5) == 3 if __name__ == '__main__': main()
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2017/10/31 14:39 # @File : leetCode_541.py ''' 思路: 从0开始,步长为 2k, 取前k个字段反转,后k个字段保持 ''' class Solution(object): def reverseStr(self, s, k): """ :type s: str :type k: int :rtype: str """ res = "" for i in range(0, len(s), 2*k): res += s[i:i + k][::-1] res += s[i + k: i + 2*k] return res ss = "abcdefg" s = Solution() print(s.reverseStr(ss, 2))
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2017/10/17 16:52 # @File : leetCode_20.py class Solution(object): def isValid(self, s): """ :type s: str :rtype: bool """ if len(s) < 1: return True if len(s) == 1: return False stack = [] for sub in s: if sub in ("(", "[", "{"): stack.append(sub) elif len(stack) == 0: return False if sub in (")", "]", "}") and stack: if sub == ")" and stack[-1] == "(": stack.pop() continue elif sub == "]" and stack[-1] == "[": stack.pop() continue elif sub == "}" and stack[-1] == "{": stack.pop() continue else: stack.append(sub) break if sub in (")", "]", "}") and len(stack) == 0: stack.append(sub) break # print(stack) # 参考代码 # sample = { # "}": "{", # "]": "[", # ")": "(" # } # for sub in s: # if sub in ("(", "[", "{"): # stack.append(sub) # else: # if len(stack) == 0: # return False # temp = stack.pop() # if sample[sub] == temp: # continue # else: # return False return len(stack) == 0 import time start = time.time() s = Solution() assert s.isValid("") == True assert s.isValid("((())){{{}}}[[[]]]") == True assert s.isValid("()[]{}") == True assert s.isValid("()") == True assert s.isValid("(]") == False assert s.isValid("([)]") == False assert s.isValid("([)]") == False assert s.isValid("]]][[[") == False assert s.isValid("(])") == False assert s.isValid("[])") == False print(time.time() - start)
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2017/10/26 14:32 # @File : leetCode_13.py ''' 罗马数字转换为int 思路:从头向后转,定义一个转换字典 如果新的数比 已经转换的最后一个数大,则已经转换的最后一个数设置为负, 最后求和 ''' class Solution(object): def romanToInt(self, s): """ :type s: str :rtype: int """ roma = { "I": 1, "V": 5, "X": 10, "L": 50, "C": 100, "D": 500, "M": 1000 } # Ⅰ(1)、X(10)、C(100)、M(1000)、V(5)、L(50)、D(500) res = [] for k in s: if res and roma[k] > res[-1]: res[-1] = - res[-1] res.append(roma[k]) print(res) # for i in res[::-1]: return sum(res) s = Solution() print(s.romanToInt("MCMLXXX")) # 1980 MMMCMXCIX 3999 print(s.romanToInt("MMMCMXCIX"))
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2017/11/6 16:55 # @File : leetCode_557.py class Solution(object): def reverseWords(self, s): """ :type s: str :rtype: str """ #ss = s.split(" ") return " ".join([t[::-1] for t in s.split(" ")]) # return ' '.join(s.split()[::-1])[::-1] ss = "Let's take LeetCode contest" s = Solution() dd = s.reverseWords(ss) print(ss) print(dd)
person={ "name": "luis", "last_name": "salazar", "age": "35", "favorite_movies": ['uno', 'dos', 'tres'], "favorites_books":[{ "title":"primer libro", "author": "primer autor" }, { "title":"segundo libro", "author": "segundo autor" } ] } print (person) print (person['name']) print (person['favorite_movies']) print (person['favorites_books']) print (person.keys()) print (person.values()) #remove a key del person['age'] print (person) #get default value if key does not exist print (person.get("age", "Unknown"))
import numpy as np import math class Line: def __init__(self, a, b): """Two endpoints in the form of [x, y]""" self.a = list(a) self.b = list(b) def is_vertical(self): if self.a[0] == self.b[0]: return True return abs((self.a[1] - self.b[1]) / (self.a[0] - self.b[0])) > 1 def to_polyline(self): return np.array([ self.a, self.b ]).astype(dtype=np.int32) @property def com(self): """Center of mass [x, y]""" return [(self.a[0] + self.b[0]) / 2, (self.a[1] + self.b[1]) / 2] @property def length(self): """Line length""" return ((self.a[0] - self.b[0])**2 + (self.a[1] - self.b[1])**2) ** 0.5 @property def angle(self): return math.atan2((self.b[1] - self.a[1]), (self.b[0] - self.a[0])) def __str__(self): return "Line([%d, %d], [%d, %d])" % \ (self.a[0], self.a[1], self.b[0], self.b[1]) def __repr__(self): return str(self) def intersect(self, that): """Intersection point of two lines""" denom = (self.a[0]-self.b[0])*(that.a[1]-that.b[1]) - (self.a[1]-self.b[1])*(that.a[0]-that.b[0]) if denom == 0: print("Lines are parallel!") return [0, 0] return [ ((self.a[0]*self.b[1]-self.a[1]*self.b[0])*(that.a[0]-that.b[0]) - (self.a[0]-self.b[0])*(that.a[0]*that.b[1]-that.a[1]*that.b[0])) / denom, ((self.a[0]*self.b[1]-self.a[1]*self.b[0])*(that.a[1]-that.b[1]) - (self.a[1]-self.b[1])*(that.a[0]*that.b[1]-that.a[1]*that.b[0])) / denom ]
# create a mapping of state to abbriavation states= { 'Oregon' : 'OR', 'Florida' : 'FL', 'California': 'CA', 'New York': 'NY', 'Michigan': 'MI' } #create a basic set of status and some cities in them cities= { 'CA': 'San Fransisco', 'MI': 'Detroit', 'FL': 'Jacksonville' } #add some more cities cities['NY']= 'New York' cities['or']= 'Portland' print '-' * 10 print "NY State has: ", cities['NY'] print "OR State has: ", cities['OR'] #print some states print '-'* 10 print "Michigan is abbrivated as:" states['Michigan'] print "Florida is abbrivated as:" sataes['Florida'] #do it by using states than the cities print '-'*10 print "Michigan is abrivated as:"states[cities['MI']] print "Florida is abbrivated as:"states[cities['FL']] #print every state's is abbrivation print "*" * 10 for state, abbrev in states.items(): print "%s is abbrivated %s"% (state, abbrev) #print every city in state print '-' * 10 for abbrev, city in cities.items(): print "%s has the city %s" % (abbrev, city) #now do both at the same time print '$' * 10 for state, abbrev in states.items(): print "%s state is abbreviated %s and has city %s"% (state, abbrev, cities[abbrev]) print '@'* 10 #safly get an abbreviation by state that might not be there state= states.get('Texas',None) if not state: print "Sorry, no Texas." #get a city with a default value city = cities.get('TX','Does Not Exist') print "The city for the state 'TX' is: %s" %city
#This is butifull example illustrating the Reccursion, extend and append def flat_list(li): res=[] for el in li: if type(el) is list: res.extend(flat_list(el)) else: res.append(el) return res if __name__=="__main__": li=[['a',['b',['c','d'],'e'],'f']] v0=flat_list(li) print v0
#국민대학교 20113274 김한결 # 로또 번호 생성기 import random s = set() times = 50 while times: while s.__len__() <6: #집합의 원소가 6개가 될때까지 반복 s.add(random.randrange(1,47)) print(s) s.clear() times -=1
import sqlite3 from tkinter import Tk, Text, BOTH, W, N, E, S, Listbox, StringVar,END from tkinter.ttk import Frame, Button, Label, Style, Entry #UI 클래 class BookManagerUi(Frame): def __init__(self, parent): Frame.__init__(self, parent) self.parent = parent self.initUI() self.db = dao('blist') #데이터베이스 관리 클래스 생성 def initUI(self): self.parent.title("Book Manager") self.style = Style() self.style.theme_use("default") self.pack(fill=BOTH, expand=1) self.columnconfigure(0, pad=3) self.columnconfigure(1, pad=3) self.columnconfigure(2, pad=3) self.rowconfigure(0, pad=3) self.rowconfigure(1, pad=3) self.rowconfigure(2, pad=3) self.rowconfigure(3, pad=3) self.rowconfigure(4, pad=3) self.rowconfigure(5, pad=3) self.rowconfigure(6, pad=3) self.input_bname='' self.input_aname='' self.input_price=0 self.delete='' lb_bookname = Label(self, text="bookname:") lb_bookname.grid(row=0, column =0 ,sticky=W, pady=4, padx=5) self.entry_bookname = Entry(self) self.entry_bookname.grid(row=0, column = 1 ) lb_author = Label(self, text="author:") lb_author.grid(row=0, column =2,sticky=W, pady=4, padx=5) self.entry_author = Entry(self) self.entry_author.grid(row=0, column = 3 ) lb_price = Label(self, text="price:") lb_price.grid(row=0, column =4 ,sticky=W, pady=4, padx=5) self.entry_price = Entry(self) self.entry_price.grid(row=0, column = 5 ,padx=15) abtn = Button(self, text="Add", command=lambda:self.clicked_add()) abtn.grid(row=0, column=6) sbtn = Button(self, text="Serach", command = lambda:self.clicked_search()) sbtn.grid(row=1, column=6, pady=4) dbtn = Button(self, text="Delete", command = lambda:self.clicked_delete()) dbtn.grid(row=2, column=6, pady=4) self.lb = Listbox(self) self.lb.grid(row=3,column = 0, columnspan = 6,rowspan= 4, sticky = E+W+S+N) self.lb.bind("<<ListboxSelect>>", self.onSelect) #삭제를 위한 select부분 def onSelect(self,val): sender = val.widget idx = sender.curselection() value = sender.get(idx) self.delete = value # 데이터 추가 버튼 def clicked_add(self): bname =self.entry_bookname.get() aname = self.entry_author.get() price = self.entry_price.get() self.lb.delete(0,END) # 입력받을 데이터가 모자란지 검사 if(len(bname) >0 and len(aname)>0 and len(price)>0 ): #가격에 문자를 입력했을 경우 처리 try: priceI = eval(price) except: self.lb.insert(END,"you input wrong price. it must be integer") #사용자가 입력한 내용중 중복된 책이름이 있을 경우(저자는 책이 여러가지일 수 있으니 제외) rec = self.db.excute_select(bname,'') if ( len(rec) >0): self.lb.insert(END,bname +" is already in the database") else: self.db.insert_data(bname,aname,priceI) # 모든 조건 만족시 데이터 입력 수행 r =self.db.excute_select(bname,aname) for rs in r: self.lb.insert(END,str(rs)) else: s = StringVar() self.entry_price.config(textvariable = s) self.lb.insert(END,"you have to input more values") #검색버튼 def clicked_search(self): bname =self.entry_bookname.get() aname = self.entry_author.get() self.lb.delete(0,END) #책이름 또는 저자이름 둘중 하나만입력 되어도 검색 가능하도록 if(len(bname)>0 or len(aname)>0 ): rec = self.db.excute_select(bname,aname) for r in rec: self.lb.insert(END,str(r)) else: self.lb.insert(END,"you have to input more values(bookname or author") #삭제 버튼 def clicked_delete(self): self.lb.delete(0,END) q = self.db.excute_delete(self.delete) self.lb.insert(END,q+' is delete from database') def main(): root = Tk() root.geometry("800x300+300+300") app = BookManagerUi(root) root.mainloop() #데이터베이스 접속 객체 class dao: def __init__(self,db_file): #데이터베이스 및 테이블 생성 self.conn = sqlite3.connect(db_file) self.cursor = self.conn.cursor() self.cursor.execute('''CREATE TABLE IF NOT EXISTS booklist(bname VARCHAR(20), aname VARCHAR(20), price INT(5))''') self.conn.commit() self.delete_s='' # 데이터 입력 부분 def insert_data(self,bname,aname,price): query = "INSERT INTO booklist VALUES('{0}','{1}',{2})".format(bname,aname,price) self.cursor.execute(query) self.conn.commit() #데이터 조회 부분 def excute_select(self,bname,aname): query = "SELECT * FROM booklist WHERE bname='{0}' OR aname='{1}'".format(bname,aname) self.cursor.execute(query) return self.cursor.fetchall() #데이터 삭제 부분 책이름이 중복되지 않으므로 삭제가 가능하다. def excute_delete(self,d): self.delete_s = d.split(',') self.delete_s = self.delete_s[0] self.delete_s = self.delete_s[2:-1] query = "DELETE FROM booklist WHERE bname='{0}'".format(self.delete_s) self.cursor.execute(query) self.conn.commit() return self.delete_s if __name__ == '__main__': main()
class GeographicPoint(object): def __init__(self, lat, lon, alt): self._latitude = lat self._longitude = lon self._altitude = alt @property def latitude(self): return self._latitude @property def longitude(self): return self._longitude @property def altitude(self): return self._altitude def equals(self, pt): return self._latitude == pt.latitude and self._longitude == pt.longitude
from Node import Node class printCommonPart(object): def print_common_part(self, head1: Node, head2: Node): while head1 is not None and head2 is not None: if head1.value < head2.value: head1 = head1.next elif head1.value > head2.value: head2 = head2.next else: print(head1.value) head1 = head1.next head2 = head2.next # print('\n') if __name__ == '__main__': node3 = Node(3, None) node2 = Node(2, node3) node1 = Node(1, node2) node6 = Node(4, None) node5 = Node(3, node6) node4 = Node(2, node5) printCommonPart = printCommonPart() printCommonPart.print_common_part(node1, node4)
class TwoNumSum(object): # 暴力解法 def two_num_sum1(self, nums: list, target: int) -> list: if nums.__len__() < 2: return [] for i in range(0, nums.__len__()): for j in range(i+1, nums.__len__()): if nums[i] + nums[j] == target: return [i, j] return [] # 哈希 def two_num_sum2(self, nums: list, target: int) -> list: if nums.__len__() < 2: return [] map = {} for index, num in enumerate(nums): another = target - num if another in map: return [map[another], index] map[num] = index return [] def two_num_sum3(self, nums: list, target: int) -> list: if nums.__len__() < 2: return [] hashmap = dict() for i in range (0, nums.__len__()): another = target - nums[i] if hashmap.__contains__(another): return [hashmap.__getitem__(another), i] hashmap.__setitem__(nums[i], i) return [] if __name__ == "__main__": nums = [0, 1, 2, 3, 4, 5, 6, 7] target = 13 twoNumSum = TwoNumSum() result = twoNumSum.two_num_sum3(nums, target) print(result)
from math import sqrt, ceil import random # We can generate a random number using the randint method random_number = random.randint(0, 10) print(random_number) x = sqrt(9) print(x) y = ceil(x) print(y)
# print product of elements in a list and even numbers in it def mult(r): mux=1 for i in r: mux=mux*i print("mult result is : ",mux) print("even numbers : ") for i in r: if i%2==0: print(i) # reverse the string def strrec(sad): print(sad) mad="" for i in range(len(sad)-1,-1,-1): mad=mad+sad[i] print(mad) # factorial number def factorial(s): if s==0: return 1 else: return s*factorial(s-1) # dictionary with keys=1-20 and values = squares of keys def dictr(): dictr={i:i**2 for i in range(1,21)} print(dictr) # remove duplicates and reverse sort the list def list1(sd): red=[] print("remove duplicates and reverse sort ") for i in sd: if i not in red: red.append(i) print("removed duplicates : ",red) red.sort(reverse=True) print("reverse sorted : ",red) sdfg=[12,24,35,24,88,120,155,88,120,155] z=[2,3,4,5,6,7] sdf="pranay" mult(z) strrec(sdf) print("fac result : ",factorial(4)) dictr() list1(sdfg) # find numbers of rabbits and chickens given number of heads and legs def animals(heads,legs): for i in range(1,heads+1): for j in range(1,heads+1): if i+j == heads: if i*4+j*2 == legs: print("number of rabbits : ",i) print("number of chickens : ",j) animals(35,94)
var=int(input("enter a number")) #increasing stars for i in range(1,var+1): print("*"*i) #other format of incresing stars(this is standard format from youtube) for i in range(1,var+1): for j in range(1,i+1): print("*",end="") print() # #decreasing stars for i in range(var,0,-1): print("*"*i) #to print 1,22,333,4444.... for i in range(1,var+1): print(str(i)*i) #to print ....55555,4444,333,22,1 for i in range(var,0,-1): print(str(i)*i) # to print star *,***,***** .... like a triangle x=int((var/2)-1) print("the triangle shape") for i in range(1,int(var/2)+1): print(" "*(x-i+5),end="") print("*"*(2*i-1)) # to print * in diamond shape x=int((var/2)-1) print("the diamond shape") for i in range(1,int(var/2)): print(" "*(x-i+5),end="") print("*"*(2*i-1)) for i in range(int(var/2),0,-1): print(" "*(x-i+5),end="") print("*"*(2*i-1))
# find an element in a list L=["digital","lync","hyderabad","gachibowli","kukatpally"] A="Lync" flag1=0 for i in L: if i is A: flag1=flag1+1 if flag1>=1: print("present in the sequence") else: print("not present in the sequence") # perform bitwise operations a=45 b=65 print("bitwise and = ",a&b) print("bitwise or = ",a|b) print("bitwise xor = ",a^b) # find sum of digits of a number a3=int(input("enter a number : ")) sum1=0 while a3>0: sum1=(a3%10)+sum1 a3=a3//10 print("sum of digits = ",sum1) # perform relational operations a1=15 b1=2 print("a1>b1 = ",a1>b1) print("a1<b1 = ",a1<b1) print("a1==b1 = ",a1==b1) print("a1!=b1 = ",a1!=b1)
n=int(input("enter a number : ")) # to print stars first inc then dec for i in range(1,n+1): if i!=n: print("*"*i) else: for j in range(n,0,-1): print("*"*j) print() # to print stars from right side for r in range(1,n+1): print(" "*(n-r)+"*"*r) print() #to print abcde for s in range(ord("a"),ord("a")+n): for f in range(ord("a"),s+1): print(chr(f),end="") print() print() #to print abcde from right side x=ord("a")+n-1 for e in range(ord("a"),ord("a")+n): print(" "*(x-e),end="") for a in range(ord("a"),e+1): print(chr(a),end="") print()
# print('hello world') # name=input('what is your name:\n') # print('hi,%s'%name) # last=input('ur surname:') # print('%s' %last) # x=int(input('enter integer:')) # y=float(input('enter a float:')) # print(x+y) # r=float(input('enter a radius of circle:')) # print('area:',3.14*r**2) # print('perimeter:',2*3.14*r) # s=float(input('enter side:')) # print('primeter:',4*s) # swaping # x=int(input()) # y=int(input()) # x=x+y # y=x-y # x=x-y # print(x,y) # a=int(input('enter a number:')) # if a%2==0: # print('even') # else: # print('odd') # sum=0 # for i in range(1,5): # sum+=i # # print(sum) # # lst=[23,45,7] # sum=0 # for i in lst: # sum+=i # print(sum) # # # #while # sum=0 # i=0 # while i<10: # sum+=i # i+=1 # # print(sum) # for i in 'apple': # if i == 'l': # break # else: # print(i) # year = int(input('year:')) # if (year % 4) == 0: # if (year % 100) == 0: # if (year % 400) == 0: # print("{0} is a leap year".format(year)) # else: # print("{0} is not a leap year".format(year)) # else: # print("{0} is a leap year".format(year)) # else: # print("{0} is not a leap year".format(year)) x=int(input('enter x')) y=int(input('enter y')) if x > y: smaller = y else: smaller = x for i in range(1, smaller+1): if((x % i == 0) and (y % i == 0)): hcf = i print('hcf:',hcf)
# nums1=list(map(float,input('enter nums1:').split())) # nums2=list(map(float,input("enter nums2:").split())) # sum = len(nums1) + len(nums2) # merged = [] # l, r = 0, 0 # if sum % 2 != 0: # # index = [sum / 2] # while (l + r) < (sum / 2): # if nums1[l] < nums2[r]: # merged.append(nums1[l]) # l += 1 # elif nums1[l] == nums2[r]: # merged.append(nums1[l]) # merged.append(nums2[r]) # l += 1 # r += 1 # else: # merged.append(nums2[r]) # r += 1 # print('this is merged',merged) # print('median:',merged[-1]) # # else: # # index = [sum / 2, (sum / 2) + 1] # while (l + r) < (sum / 2) + 1: # if nums1[l] < nums2[r]: # merged.append(nums1[l]) # l += 1 # elif nums1[l] == nums2[r]: # merged.append(nums1[l]) # merged.append(nums2[r]) # l += 1 # r += 1 # else: # merged.append(nums2[r]) # r += 1 # print('this is merged:',merged) # print('median:',(merged[-1] + merged[-2]) / 2) # # m= int(input()) lm = list(map(int,input().split(' '))) n = int(input()) ln = list(map(int,input().split(' '))) for i in lm: if i in ln: ln.remove(i) else: ln.append(i) print(ln) ln1 =set(ln) for i in sorted(ln1): print(i)