text
stringlengths
37
1.41M
user_in = input("입력:").split() amount = user_in[0] currency = user_in[1] if currency == "달러" : ratio = 1167 elif currency == "엔" : ratio = 1.096 elif currency == "유로" : ratio = 1268 else : ratio = 171 print(ratio * int(amount), "원")
user_in = input() if user_in.islower(): user_in = user_in.upper() else : user_in = user_in.lower() print(user_in)user_in = input("제가좋아하는계절은:") if user_in in fruit.keys() : print("정답입니다") else : print("오답입니다")
# list of prices for same item in index for each list store1 = [10.00, 11.00, 12.34, 2.34] store2 = [9.00, 11.10, 12.34, 2.01] # compare item to item price between the two stores to find the best price # python utilizes lazy evaluation for efficient memory management cheapest = map(min, store1, store2) people = ['Dr. Christopher Brooks', 'Dr. Kevyn Collins-Thompson', 'Dr. VG Vinod Vydiswaran', 'Dr. Daniel Romero'] def split_title_and_name(person): return person.split()[0] + " " + person.split()[-1] list(map(split_title_and_name, people))
import pandas as pd dataframe = pd.read_csv('/Users/cbohara/Desktop/INTRO_DS/data/olympics.csv', index_col=0, skiprows=1) dataframe.head() for col in dataframe.columns: if col[:2] == '01': dataframe.rename(columns={col:'Gold'+col[4:]}, inplace = True) if col[:2] == '02': dataframe.rename(columns={col:'Silver'+col[4:]}, inplace = True) if col[:2] == '03': dataframe.rename(columns={col:'Bronze'+col[4:]}, inplace = True) # boolean mask returns true or false whether the country has won at least one gold medal dataframe['Gold'] > 0 # use where function to apply boolean mask to the series and return series of the same shape only_gold = dataframe.where(dataframe['Gold'] > 0) # replaces data of countries that have not won a gold to NaN only_gold.head() # print(only_gold) # print(only_gold['Gold'].count()) # better way for querying that eliminates countries that have not won a gold rather than replace with NaN only_gold = dataframe[dataframe['Gold']>0] only_gold.head() # print(only_gold) dataframe['country'] = dataframe.index dataframe = dataframe.set_index('Gold') # print(dataframe)
import abc #元类编程 class BaseService(metaclass=abc.ABCMeta): #1. 第一种解决方案: 在父类的方法中抛出异常 #2. 第二种解决方案: 使用抽象基类 @abc.abstractmethod def login(self): pass @abc.abstractmethod def check_cookie(self, cookie_dict): pass class Lagou(BaseService): name = "lagou" #强制性的效果 def login(self): print("login in {}".format(self.name)) if __name__ == "__main__": l = Lagou() l.login()
t = 'a pattern matching algorithm' p = 'matchinga' def last_occurrence(s): return p.rfind(s) def solve(t, p): lent = len(t) lenp = len(p) jump = [lenp - 1] j = lenp - 1 for i in range(lenp - 1, lent): if not i in jump: continue if not p[j] == t[i]: jump.append(i + lenp - min(j, 1 + last_occurrence(t[i]))) j = lenp - 1 continue if p[j] == t[i]: j -= 1 i -= 1 while j >= 0: if p[j] == t[i]: j -= 1 i -= 1 else: jump.append(i + lenp - min(j, 1 + last_occurrence(t[i]))) j = lenp - 1 break if j == 0: return 'exist' print('not exist') if __name__ == '__main__': print(solve(t, p))
import random def reroll(percentOne): percentTwo = 100-percentOne if ((isinstance(percentOne, int)==True)): my_list = [0]*percentTwo+[1]*percentOne choose = random.choice(my_list) #print(choose) x=(choose) return(x) else: print("error please only use integers") #testing #reroll(100)
""" Cleaning up the file for complaining data """ import pandas as pd import numpy as np import glob FILE_NAMES = [] #dummmy data for file name FILE_NAMES.append("01 - Jan'17 Complaint.xlsx") SHEET_NAME = ['CTT','SR','AMDOCS'] def get_file_name(path): files = glob.glob(path+"/*.xlsx") return files """ Function to read all the name of the file for cleaning up Input: List of file name (String) Output: List of dataframe from execl file split into sheet name """ """ Read the excel file from provided path """ def read_excel_files(file_names): complete_data = {} for x in range(len(file_names)): for y in range(len(SHEET_NAME)): data = pd.read_excel(file_names[x],dtype=object,sheet_name=SHEET_NAME[y]) complete_data[file_names[x]+"|"+SHEET_NAME[y]] = data print(file_names[x]+"|"+SHEET_NAME[y]) return complete_data """ This function will product a data in csv form based on individual sheet name Input: data: a pandas dataframe for specific sheet_name sheet_name: a string value Output: string value represent in the form of CSV if condition is meet otherwise is NULL value """ def clean_based_sheet_name(data,sheet_name): result = "" if sheet_name == 'CTT': for i in range(len(data)): result=result+"CTT"+","+str(data.at[i,"TT_NUMBER"])+","+str(data.at[i,"PRE_OR_POST"])\ +","+str(data.at[i,"SERIAL_NUMBER"])+","+str(data.at[i,"CUSTOMER_SEGMENT_GROUP"])\ +","+str(data.at[i,"SOURCE"])+","+str(data.at[i,"STATUS"])+","+str(data.at[i,"TT_TYPE"])\ +","+str(data.at[i,"CATEGORY"])+",,"+str(data.at[i,"PLAN"])+","+str(data.at[i,"PRODUCT"])+","\ +","+str(data.at[i,"PROBLEM_CAUSED"])+","+str(data.at[i,"RESOLUTION_CODE"])+","+str(data.at[i,"OWNER_ID"])\ +","+str(data.at[i,"CREATOR_ID"])+","+str(data.at[i,"CREATED_DATE"])+","+str(data.at[i,"CLOSED_DATE"])\ +","+str(data.at[i,"ESCALATION_TIME"])+",,"+str(data.at[i,"NETWORK_INDICATOR"])+","+str(data.at[i,"REGION"])\ +","+str(data.at[i,"SERVICE_AFFECTED"])+"\n" elif sheet_name == 'SR': for i in range(len(data)): result=result+"SR"+","+str(data.at[i,"SR_NUMBER"])+","+str(data.at[i,"CON_TYPE"])\ +","+str(data.at[i,"SERVICE_NUMBER"])+","+str(data.at[i,"CUSTOMER_SEGMENT_GROUP"])\ +","+str(data.at[i,"SOURCE"])+","+str(data.at[i,"SR_STATUS"])+","+str(data.at[i,"SR_TYPE"])\ +","+str(data.at[i,"CATEGORY"])+","+str(data.at[i,"SUBCATEGORY"])+","+str(data.at[i,"PLAN"])+","+str(data.at[i,"PRODUCT_NAME"])\ +","+str(data.at[i,"PRODUCT_TYPE"])+","+str(data.at[i,"PROBLEM_CAUSE"])+","+str(data.at[i,"RESOLUTION_CODE"])+","+str(data.at[i,"OWNER_ID"])\ +","+str(data.at[i,"CREATOR_ID"])+","+str(data.at[i,"CREATED_DATE"])+","+str(data.at[i,"CLOSED_DATE"])\ +","+str(data.at[i,"ESCALATION_TIME"])+","+str(data.at[i,"DISPUTE_AMOUNT"])+",,"+str(data.at[i,"SD_REGION"])+",\n" elif sheet_name == 'AMDOCS': for i in range(len(data)): result=result+"AMDOCS"+",,,"+str(data.at[i,"Service Num"])+",,,"+str(data.at[i,"Status"])+","+str(data.at[i,"Type"])\ +",,,,,"+str(data.at[i,"Prod Type"])+","+str(data.at[i,"Prob Category"])\ +",,"+str(data.at[i,"Owner"])+",,"+str(data.at[i,"Creation Time"])+","+str(data.at[i,"X Close Date"])\ +",,,,,\n" return result """ """ def cleaning_up(complete_data): complete_clean_up = "" for key,value in complete_data.items(): file_name,sheet_name = key.split("|") complete_clean_up = complete_clean_up + clean_based_sheet_name(value,sheet_name) return complete_clean_up def main(): print("Job begins") data = "FILE_TYPE,COMPL_NUMBER,CON_TYPE,SERVICE_NUMBER,CUSTOMER_SEGMENT_GROUP,\ SOURCE,STATUS,TYPE,CATEGORY,SUBCATEGORY,PLAN,PRODUCT,PRODUCT_TYPE,PROBLEM_CAUSE,\ RESOLUTION_CODE,OWNER_ID,CREATOR_ID,CREATED_DATE,CLOSED_DATE,ESCALATION_TIME,DISPUTE_AMOUNT,\ NETWORK_INDICATOR,REGION,SERVICE_AFFECTED\n" data = data + cleaning_up(read_excel_files(get_file_name("../Data"))) with open("complain_file_after_clean_up.csv","w") as open_file: open_file.write(data) print("Job Finish") main()
from tkinter import * import random root = Tk() root.title("Tarea POO") titulo1 = Label(root, text= "Ingrese sus datos", bg= "purple2", fg= "white").grid(row=0, column=0,columnspan=18, sticky= W+E+N+S) Label(root, text="Título").grid(row=1, column=0, sticky= W) Label(root, text="Ruta").grid(row=2, column=0, sticky= W) Label(root, text="Descripción").grid(row=3, column=0, sticky= W) e1 = Entry(root) e2 = Entry(root) e3 = Entry(root) e1.grid(row=1, column=1, sticky=W) e2.grid(row=2, column=1, sticky=W) e3.grid(row=3, column=1, sticky=W) datos=[e1,e2,e3] def entradadatos(): print("Título: " + e1.get()+ '\n'+ "Ruta: " + e2.get()+ '\n'+ "Descripción: " + e3.get()) def changecolor(): global f f= random.choice(list(colores)) root["bg"]=f colores=["blanched almond", "Skyblue2", "coral1", "plum2", "misty rose", "IndianRed1", "ivory3", "lime green", "dodger blue"] a = Button(root, text="Alta", fg= "black", command=entradadatos). grid( row=4, column=1, padx=5,pady=2, sticky= N) b = Button(root, text="Sorpresa", fg= "black", command=changecolor). grid( row=4, column=8, padx=45,pady=2, sticky= SE) mainloop()
import turtle from turtle import * turtle.bgcolor("black") title("Recuperatorio") pencolor("white") pensize(5) for i in range(1,9): forward(200) right(225) begin_fill() fillcolor('purple') end_fill()
import os add = input("nhập địa chỉ cần tạo thư mục: ") foldername = input("nhập tên thư mục cần tạo: ") filename = input("nhập tên file cần tạo: ") file = os.path.join(add,foldername) os.mkdir(file) os.chdir(file) f = open(filename, "x") f.close() print("tạo thành công file",filename,"trong",add,foldername)
''' Each of these functions takes an email.message.Message and returns a string, boolean, float or int. Or None. ''' import builtins as _builtins import re as _re from io import StringIO as _StringIO def _body(email) -> str: return _payload(email)[0].get_payload() def _payload(email) -> str: p = email.get_payload() if isinstance(p, _builtins.str): return [email] else: return p def _ilen(iterable) -> int: 'Calculate the length iteratively.' return sum(1 for _ in iterable) def body_characters(email) -> int: 'Number of characters in the body text' return len(_body(email)) def body_words(email) -> int: 'Number of words in the body text' text = ' '.join(filter(lambda line: not line.startswith('>'), _body(email).split('\n'))) return _ilen(filter(None, _re.split(' +', text))) def body_lines(email) -> int: 'Number of lines in the body' return _body(email).count('\n') def _n_at_signs(string): return string.count('@') def to_addresses(email) -> int: 'Number of addresses in the "To:" field' return _n_at_signs(email.get('to', '')) def cc_addresses(email) -> int: 'Number of addresses in the "CC:" field' return _n_at_signs(email.get('cc', '')) def hops(email) -> int: 'Number of "Received" headers in the email' return len(email.get_all('received')) def subject_re(email) -> bool: 'Whether the subject indicates a reply (starts with /^re:/)' subject = email.get('subject') return _re.match(r'^re:.*$', subject, flags = _re.IGNORECASE) != None def subject_fwd(email) -> bool: 'Whether the subject indicates a forward (starts with /^fwd:/)' subject = email.get('subject') return _re.match(r'^fwd:.*$', subject, flags = _re.IGNORECASE) != None def gmail(email) -> bool: ''' Whether the email was sent from a Gmail address (whether the earliest/lowest "Received:" header includes "google.com ") ''' return 'google.com ' in email.get_all('received')[-1] def binary_attachments(email) -> int: 'Number of non-text attachments' msgs = _payload(email) def is_attachment(msg) -> bool: return None == _re.match(r'^text/.*$', msg.get_content_type()) return _ilen(filter(is_attachment, msgs))
for i in range(1,9): print(i) r = range(1, 9) print(r) numbers = [12,37,5,42,8,3] temp = numbers[:] even = [] odd = [] while len(numbers)>0: number = numbers.pop() if(number%2 == 0): even.append(number) else: odd.append(number) print(temp) print(numbers) print(even) print(odd)
# -*- coding: UTF-8 -*- # from time import sleep import time class HotDog: def __init__(self): self.cooked_level = 0 self.cooked_string = "rav" self.condiments = [] def __str__(self): msg = 'HotDog' if len(self.condiments) > 0: msg = msg + ' with ' for i in self.condiments: msg = msg + i + ", " msg = msg.strip(", ") msg = self.cooked_string + " " + msg + "." return msg def cook(self, time): self.cooked_level = self.cooked_level + time if self.cooked_level > 8: self.cooked_string = '大于8' if self.cooked_level > 5: self.cooked_string = '大于5' if self.cooked_level > 3: self.cooked_string = "大于3" else: self.cooked_string = "以上都不是" def add_condiment(self, condiment): self.condiments.append(condiment) class X(HotDog): def __init__(self): HotDog.__init__(self) myDog = HotDog() myDog.cook(4) print myDog.cooked_level time.sleep(4) print myDog.cooked_string print myDog.condiments print myDog myDog.add_condiment('rose') myDog.add_condiment('benjamin') print myDog
# Note problem from # https://www.hackerrank.com/challenges/tree-height-of-a-binary-tree/problem import math def height_complete_binary_tree(root): number_of_leaves = count_leaves(root, 0) return math.log(number_of_leaves, 2) def count_leaves(node, count): if node.left: count = count_leaves(node.left, count) if node.right: count = count_leaves(node.right, count) if not node.left and not node.right: return count + 1 return count def height_binary_tree(node): if node.left: count_left = 1 + height_binary_tree(node.left) if node.right: count_right = 1 + height_binary_tree(node.right) if node.left and not node.right: return count_left if node.right and not node.left: return count_right if node.left and node.right: return max(count_left, count_right) return 0
from urllib.request import urlopen from urllib.parse import quote import json # These functions make HTTP calls to Seattle's GIS server. If you use it too # frequently, the server may stop responding. def geocode(addr): """ Input: First line of a Seattle address, in string form (eg "111 S Jackson St") Output: tuple, (latitude, longitude) """ # construct a url for the webservice request base = "https://gisrevprxy.seattle.gov" \ "/ArcGIS/rest/services/locators/SND/GeocodeServer/" \ "findAddressCandidates?Single+Line+Input={}&outSR=4326&f=pjson" url = base.format(quote(addr)) # make the webservice request resp = json.load( urlopen(url) ) # if there are no results, return None if "candidates" not in resp or len(resp["candidates"])==0: return None # return location on (latitude, longitude) form loc = resp["candidates"][0]["location"] return loc['y'], loc['x'] def findbeat(addr): """ Input: First line of a Seattle address, in string form (eg "111 S Jackson St") Output: Beat code, in string form (eg "J2"), or None if none could be found. """ coord = geocode(addr) if coord is None: return None lat, lon = coord baseurl ="https://gisrevprxy.seattle.gov/ArcGIS/rest/services/DoIT_ext/" \ "SP_Precincts_Beats/MapServer/2/query?" \ "text=&geometry={},{}" \ "&geometryType=esriGeometryPoint&inSR=4326" \ "&spatialRel=esriSpatialRelIntersects&relationParam=&objectIds=" \ "&where=&time=&returnCountOnly=false&returnIdsOnly=false" \ "&returnGeometry=false&maxAllowableOffset=&outSR=&outFields=&f=pjson" url = baseurl.format(lon, lat) #coord is in lon/lat format print(url) # make the webservice request resp = json.load( urlopen(url) ) # get the first feature from the response features = resp.get("features") if features is None: return None if len(features)==0: return None feature = features[0] # get the list of attributes for the feature attributes = feature.get("attributes") if attributes is None: return None # get the beat from the attributes return attributes.get("beat") if __name__ == '__main__': import sys if len(sys.argv)!=2: print( "usage: %s \"address\""%(sys.argv[0]) ) exit() addr = sys.argv[1] print( findbeat(addr) )
def task1(method): """ #1 Пять способов поменять значения переменных местами """ x = int(input('Введите первое число: ')) y = int(input('Введите второе число: ')) if method == 1: # способ 1 tmp = x x = y y = tmp elif method == 2: # способ 2 x, y = y, x elif method == 3: # способ 3 x = x + y y = x - y y = x - y elif method == 4: # способ 4 x = x ^ y y = x ^ y x = x ^ y elif method == 5: # способ 5 tmp = [x, y] x = tmp[1] y = tmp[0] else: x = 'не указан' y = 'способ' print('Результат: ', x, y) if __name__ == "__main__": task1(method=5) # (1-5) Пять способов поменять значения переменных местами
class Node: def __init__(self,element=None): self.element=element self.next=None class SingleLinkedList: def __init__(self): self.head=None def insert_at_beginning(self,element): '''this function inserts the element at the beginning of the single linked list''' if self.head is None: self.head=Node(element) else: new_node=Node(element) new_node.next=self.head self.head=new_node def insert_at_ending(self,element): '''this function inserts the element at the end of the single linked list''' if self.head is None: self.head=Node(element) else: itr=self.head while itr.next: itr=itr.next new_node=Node(element) itr.next=new_node def print_elements(self): '''this functions prints all the elements present in the single linked list''' if self.head is None: return "Single Linked list is empty to print any elements!!" singlelinkedlist_string='' itr=self.head while itr: singlelinkedlist_string+=str(itr.element)+'->' itr=itr.next return singlelinkedlist_string def count_elements(self): '''this functions counts and returns the number of elements presnet in the single linked list''' if self.head is not None: count=1 itr=self.head while itr.next: count+=1 itr=itr.next return count else: return 0 def search_element(self,search_element): '''this function checks whether the element is present in the single linked list''' itr=self.head while itr: if itr.element==search_element: return f"{search_element} is present in the single linked list" itr=itr.next if itr is None: return f"{search_element} is not present in the single linked list" def delete_at_index(self,index): '''this function deletes a node at the ending of the single linked list''' if self.head is None: return f"single linked list is empty" elif index<=0 or index> self.count_elements(): raise Exception("pass the index with in the range 1 to length of list") else: count=1 itr=self.head while itr.next: if count==index: itr.next=itr.next.next count+=1 itr=itr.next def insert_after_value(self, data_after, data_to_insert): '''this function inserts an element after an provided element''' if self.head is None: raise Exception("there is only one element in the single linked list") else: itr=self.head while itr.next: if itr.element==data_after: new_node=Node(data_to_insert) new_node.next=itr.next itr.next=new_node itr=itr.next def insert_values(self,list_of_elements): '''this function clears all the elements present in the list and creates a new list of elements in the single linked list''' self.head=None for element in list_of_elements: self.insert_at_ending(element) def remove_by_value(self,search_element): '''this function looks for a particular element and removes the element from the single linked list ''' if self.head is None: return "Linked list is empty to remove an element" elif self.head.element==search_element: self.head=self.head.next else: itr=self.head while itr.next: if itr.next.element==search_element and itr is not None: itr.next=itr.next.next break itr=itr.next if __name__=='__main__': singlelinkedlist=SingleLinkedList() singlelinkedlist.insert_values(["red","blue","green","yellow","orange"]) singlelinkedlist.insert_after_value("red","white") print(singlelinkedlist.print_elements()) singlelinkedlist.remove_by_value("red") print(singlelinkedlist.print_elements()) singlelinkedlist.remove_by_value("orange") print(singlelinkedlist.print_elements()) singlelinkedlist.remove_by_value("black") print(singlelinkedlist.print_elements()) singlelinkedlist.remove_by_value("blue") print(singlelinkedlist.print_elements()) singlelinkedlist.remove_by_value("green") print(singlelinkedlist.print_elements()) singlelinkedlist.remove_by_value("yellow") singlelinkedlist.remove_by_value("white") print(singlelinkedlist.print_elements())
names = ["Alex", "John", "Mary", "Steve", "John", "Steve"] duplicated_names = [] def locate_duplicates(names): for name in names: if names.count(name) > 1: if name in duplicated_names: pass else: duplicated_names.append(name) duplicatesFound = True return duplicatesFound # delete Duplicated names def delete_duplicates(names,duplicated_names): for name in duplicated_names: names.remove(name)
print("--------WELL COME TO UBER APP-----") import random l1=[1,1.5,2,2.5,3] def rider(destination,kilometers,vechile): rounds=int(input("enter how many times do you want take rounds::")) amount=0 index=1 dict={} l2=random.choice(l1) contact_information={"Bujji":9063430003,"RANI":7893592978,"chinna":888519989,"mosha":9989454089} while index<=rounds: dict[destination]=kilometers amount=dict1[vechile]*kilometers time=dict[destination]*l2 index=index+1 print(contact_information) call=input("do you want to call yes/no:") if call=="yes": name=input("enter driver name here::") print(contact_information[name]) elif call=="no": print("no nedd to call") print(dict) print("time taking for ",rounds,"rounds",time,"min") print("total amount",amount) destination=input("enter the destination point::") kilometers=int(input(" the distance b/w current location to destionation point::")) dict1={"mini":7,"auto":5,"prime_sedan":8,"prime_play":9,"prime_suv":10} print(dict1) vechile=input("slect your vechile::") confarmation=input("enter do you want to ride:") if confarmation=="yes": rider(destination,kilometers,vechile) elif confarmation=="no": print("canclled the vechile")
# TP of Julien Khlaut and Pierre Glandon import copy from MutableString import MutableString class Domino: """Insert Docstring Dominos size must uneven be and squared.""" DEFAULT_SIZE = 3 DISPLAY_SYMBOL = '*' def generate_pattern(self, value, size): """ Generate the pattern of the domino for a given value. Returns a list of location (i, j) where something should be drawn to display the domino. """ assert size % 2 == 1 if size <= 1 or value <= 0: return [] # if size in Domino.DISPLAY_PATTERN.keys() and value in Domino.DISPLAY_PATTERN[size]: # return copy.copy(Domino.DISPLAY_PATTERN[size][value]) if value % 2 == 1: return [(0, 0)] + self.generate_pattern(value - 1, size) pattern = [] # We build a pattern for 3x3 domino pattern_normalized = self.generate_normalized_pattern(value) # We expand it for the correct size pattern += self.expand_pattern(pattern_normalized, size) # We generate the interior of the pattern recursively full_pattern = pattern + self.generate_pattern(value - 8, size - 2) # if size not in Domino.DISPLAY_PATTERN.keys(): # Domino.DISPLAY_PATTERN[size] = {} # Domino.DISPLAY_PATTERN[size][value] = copy.copy(full_pattern) return full_pattern def generate_string_for_value(self, value): """ Generate a string representation of half a Domino (whithout canvas). """ display_list = MutableString() pattern = self.generate_pattern(value, self._size) for (i, j) in pattern: list_position_i, list_position_j = self.transform_pattern_coord_to_list_coord(i, j) display_list[list_position_i, 2 * list_position_j] = Domino.DISPLAY_SYMBOL return display_list def transform_pattern_coord_to_list_coord(self, position_i, position_j): """Transform the coordinate for patterns into list coordinate for string representation""" position_i += self._size // 2 position_j += self._size // 2 return position_i, position_j def __str__(self): display_rvalue = self.generate_string_for_value(self._rvalue) display_lvalue = self.generate_string_for_value(self._lvalue) canvas = self.generate_canvas() canvas.insert(1, 1, display_lvalue) canvas.insert(1, 2 * self._size + 1, display_rvalue) return str(canvas) def generate_canvas(self): """ Generate the canvas to display the domino. Returns a MutableString """ # if self._size in Domino.DISPLAY_CANVAS_LIST.keys(): # return copy.copy(Domino.DISPLAY_CANVAS_LIST[self._size]) canvas = MutableString() for i in [0, self._size + 1]: # We generate top/bottom border canvas[i, 0] = '+' for j in range(1, 2 * self._size): canvas[i, j] = '-' canvas[i, 2 * self._size] = '|' for j in range(2 * self._size + 1, 4 * self._size + 1): canvas[i, j] = '-' canvas[i, -1] = '+' for j in [0, 2 * self._size, 4 * self._size]: for i in range(1, self._size + 1): canvas[i, j] = '|' # Domino.DISPLAY_CANVAS_LIST[self._size] = copy.copy(canvas) return canvas def __init__(self, l_value, r_value, size=DEFAULT_SIZE): # Once set those values shouldn't be modified. check_half_domino(l_value) check_half_domino(r_value) self._lvalue = l_value self._rvalue = r_value self._size = int(size) @property def lvalue(self): return self._lvalue @property def rvalue(self): return self._rvalue @property def get_value(self): return self._rvalue + self._lvalue @staticmethod def generate_normalized_pattern(value): """Generate a 3x3 pattern for the given value, useful to generate higher value pattern by expanding it.""" pattern = [] if value >= 2: pattern += [(-1, -1), (1, 1)] if value >= 4: pattern += [(1, -1), (-1, 1)] if value >= 6: pattern += [(0, -1), (0, 1)] if value >= 8: pattern += [(-1, 0), (1, 0)] return pattern @staticmethod def expand_pattern(pattern_normalized, size): """Takes a normalized 3x3 patterns and turns it into an equivalent value size x size pattern""" pattern = [] for (i, j) in pattern_normalized: pattern.append(((size // 2) * i, (size // 2) * j)) return pattern def __repr__(self): return f"Domino({self._lvalue}, {self._rvalue})" def __eq__(self, other): return self.lvalue == other.lvalue and self.rvalue == other.rvalue def __ne__(self, other): return self.lvalue != other.lvalue or self.rvalue != other.rvalue def __lt__(self, other): return self.lvalue < other.lvalue or self.rvalue < other.lvalue class Correct_Half_Domino(Exception): def __init__(self, n): super().__init__() self._value = n @property def value(self): return self._value def __str__(self): return f"Half domino's value is not correct : '{self._value}'. It has to be an integer between 0 and 6" def check_half_domino(value): if type(value) != int or value > 6 or value < 0: raise Correct_Half_Domino(value)
""" Question 79 Question Please write a program to generate all sentences where subject is in ["I", "You"] and verb is in ["Play", "Love"] and the object is in ["Hockey","Football"]. Hints Use list[index] notation to get a element from a list. """ '''Solution by: popomaticbubble ''' import itertools subject = ["I", "You"] verb = ["Play", "Love"] objects = ["Hockey","Football"] sentence = [subject, verb, objects] n = list(itertools.product(*sentence)) for i in n: print(i)
#!/usr/bin/env python # coding: utf-8 # # Question 18 # # ### **Question:** # # > **_A website requires the users to input username and password to register. Write a program to check the validity of password input by users._** # # > **_Following are the criteria for checking the password:_** # # - **_At least 1 letter between [a-z]_** # - **_At least 1 number between [0-9]_** # - **_At least 1 letter between [A-Z]_** # - **_At least 1 character from [$#@]_** # - **_Minimum length of transaction password: 6_** # - **_Maximum length of transaction password: 12_** # # > **_Your program should accept a sequence of comma separated passwords and will check them according to the above criteria. Passwords that match the criteria are to be printed, each separated by a comma._** # # > **_Example_** # # > **_If the following passwords are given as input to the program:_** # # # ABd1234@1,a F1#,2w3E*,2We3345 # # # > **_Then, the output of the program should be:_** # # # ABd1234@1 # # # --- # # ### Hints: # # > **_In case of input data being supplied to the question, it should be assumed to be a console input._** # # --- # # # # **Solutions:** # In[1]: def is_low(x): # Returns True if the string has a lowercase for i in x: if "a" <= i and i <= "z": return True return False def is_up(x): # Returns True if the string has a uppercase for i in x: if "A" <= i and i <= "Z": return True return False def is_num(x): # Returns True if the string has a numeric digit for i in x: if "0" <= i and i <= "9": return True return False def is_other(x): # Returns True if the string has any "$#@" for i in x: if i == "$" or i == "#" or i == "@": return True return False s = input().split(",") lst = [] for i in s: length = len(i) if ( 6 <= length and length <= 12 and is_low(i) and is_up(i) and is_num(i) and is_other(i) ): # Checks if all the requirments are fulfilled lst.append(i) print(",".join(lst)) # **OR** # In[2]: def check(x): cnt = 6 <= len(x) and len(x) <= 12 for i in x: if i.isupper(): cnt += 1 break for i in x: if i.islower(): cnt += 1 break for i in x: if i.isnumeric(): cnt += 1 break for i in x: if i == "@" or i == "#" or i == "$": cnt += 1 break return ( cnt == 5 ) # counting if total 5 all conditions are fulfilled then returns True s = input().split(",") lst = filter( check, s ) # Filter function pick the words from s, those returns True by check() function print(",".join(lst)) # **OR** # In[3]: import re s = input().split(",") lst = [] for i in s: cnt = 0 cnt += 6 <= len(i) and len(i) <= 12 cnt += bool( re.search("[a-z]", i) ) # here re module includes a function re.search() which returns the object information cnt += bool( re.search("[A-Z]", i) ) # of where the pattern string i is matched with any of the [a-z]/[A-z]/[0=9]/[@#$] characters cnt += bool( re.search("[0-9]", i) ) # if not a single match found then returns NONE which converts to False in boolean cnt += bool(re.search("[@#$]", i)) # expression otherwise True if found any. if cnt == 5: lst.append(i) print(",".join(lst)) # --- # # # Question 19 # # ### **Question:** # # > **_You are required to write a program to sort the (name, age, score) tuples by ascending order where name is string, age and score are numbers. The tuples are input by console. The sort criteria is:_** # # - **_1: Sort based on name_** # - **_2: Then sort based on age_** # - **_3: Then sort by score_** # # > **_The priority is that name > age > score._** # # > **_If the following tuples are given as input to the program:_** # # # Tom,19,80 # # John,20,90 # # Jony,17,91 # # Jony,17,93 # # Json,21,85 # # # > **_Then, the output of the program should be:_** # # # [('John', '20', '90'), ('Jony', '17', '91'), ('Jony', '17', '93'), ('Json', '21', '85'), ('Tom', '19', '80')] # # # --- # # ### Hints: # # > **_In case of input data being supplied to the question, it should be assumed to be a console input.We use itemgetter to enable multiple sort keys._** # # --- # # # # **Solutions:** # In[ ]: lst = [] while True: s = input().split(",") if not s[0]: # breaks for blank input break lst.append(tuple(s)) lst.sort( key=lambda x: (x[0], x[1], x[2]) ) # here key is defined by lambda and the data is sorted by element priority 0>1>2 in accending order print(lst) # In[ ]:
""" Question 101 Question You are given a string. Your task is to count the frequency of letters of the string and print the letters in descending order of frequency. If the following string is given as input to the program: aabbbccde Then, the output of the program should be: b 3 a 2 c 2 d 1 e 1 Hints Count frequency with dictionary and sort by Value from dictionary Items """ '''Solution by: yuan1z''' X = input() my_set = set(X) arr = [] for item in my_set: arr.append([item, X.count(item)]) tmp = sorted(arr, key = lambda x: (-x[1], x[0])) for i in tmp: print(i[0] + ' ' + str(i[1]))
""" Question 54 Question Assuming that we have some email addresses in the "username@companyname.com" format, please write program to print the company name of a given email address. Both user names and company names are composed of letters only. Example: If the following email address is given as input to the program: john@google.com Then, the output of the program should be: google In case of input data being supplied to the question, it should be assumed to be a console input. Hints Use \w to match letters. """ import re emailAddress = input() pat2 = "(\w+)@(\w+)\.(com)" r2 = re.match(pat2, emailAddress) print(r2.group(2))
""" Question 34 Question: Define a function which can generate a list where the values are square of numbers between 1 and 20 (both included). Then the function needs to print the first 5 elements in the list. Hints: Use ** operator to get power of a number. Use range() for loops. Use list.append() to add values into a list. Use [n1:n2] to slice a list """ '''Solution by: popomaticbubble ''' def squares(n): squares_list = [i ** 2 for i in range(1, n+1)] print(squares_list[0:5]) squares(20)
""" Question 22 Question: Write a program to compute the frequency of the words from the input. The output should output after sorting the key alphanumerically. Suppose the following input is supplied to the program: New to Python or choosing between Python 2 and Python 3? Read Python 2 or Python 3. Then, the output should be: 2:2 3.:1 3?:1 New:1 Python:5 Read:1 and:1 between:1 choosing:1 or:2 to:1 Hints In case of input data being supplied to the question, it should be assumed to be a console input. """ ss = input().split() dict = {} # setdefault() function takes key & value to set it as dictionary. for i in ss: i = dict.setdefault(i, ss.count(i)) # items() function returns both key & value of dictionary as a list # and then sorted. The sort by default occurs in order of 1st -> 2nd key dict = sorted(dict.items()) for i in dict: print("%s:%d"%(i[0], i[1]))
""" Question 9 Question: Write a program that accepts sequence of lines as input and prints the lines after making all characters in the sentence capitalized. Suppose the following input is supplied to the program: Hello world Practice makes perfect Then, the output should be: HELLO WORLD PRACTICE MAKES PERFECT Hints: In case of input data being supplied to the question, it should be assumed to be a console input. """ def user_input(): while True: s = input() if not s: return yield s for line in map(str.upper, user_input()): print(line)
""" Question 39 Question: Write a program to generate and print another tuple whose values are even numbers in the given tuple (1,2,3,4,5,6,7,8,9,10). Hints: Use "for" to iterate the tuple. Use tuple() to generate a tuple from a list. """ tpl = (1,2,3,4,5,6,7,8,9,10) tpl1 = tuple(i for i in tpl if i % 2 == 0) print(tpl1)
""" Question 81 Question By using list comprehension, please write a program to print the list after removing numbers which are divisible by 5 and 7 in [12,24,35,70,88,120,155]. Hints Use list comprehension to delete a bunch of element from a list. """ li = [12,24,35,70,88,120,155] li = [x for x in li if x % 5 != 0 and x % 7 != 0] print(li)
""" Question 10 Question Write a program that accepts a sequence of whitespace separated words as input and prints the words after removing all duplicate words and sorting them alphanumerically. Suppose the following input is supplied to the program: hello world and practice makes perfect and hello world again Then, the output should be: again and hello makes perfect practice world Hints: In case of input data being supplied to the question, it should be assumed to be a console input. We use set container to remove duplicated data automatically and then use sorted() to sort the data. """ '''Solution by: Sukanya-Mahapatra ''' inp_string = input("Enter string: ").split() out_string = [] for words in inp_string: if words not in out_string: out_string.append(words) print(" ".join(sorted(out_string)))
""" Question 59 Question Write a program to compute 1/2+2/3+3/4+...+n/n+1 with a given n input by console (n>0). Example: If the following n is given as input to the program: 5 Then, the output of the program should be: 3.55 In case of input data being supplied to the question, it should be assumed to be a console input. Hints Use float() to convert an integer to a float. Even if not converted it wont cause a problem because python by default understands the data type of a value. """ '''Solution by: lcastrooliveira ''' def question_59(n): print(round(sum(map(lambda x: x/(x+1), range(1, n+1))), 2)) question_59(5)
""" Question 78 Question Please write a program to shuffle and print the list [3,6,7,8]. Hints Use shuffle() function to shuffle a list. """ import random # shuffle with a chosen seed lst = [3,6,7,8] seed = 7 random.Random(seed).shuffle(lst) print(lst)
""" Question 43 Question: Write a program which can filter() to make a list whose elements are even number between 1 and 20 (both included). Hints: Use filter() to filter elements of a list. Use lambda to define anonymous functions. """ def even(x): return x % 2 == 0 evenNumbers = filter(even, range(1, 21)) print(list(evenNumbers))
""" Question 90 Question Please write a program which count and print the numbers of each character in a string input by console. Example: If the following string is given as input to the program: abcdefgabc Then, the output of the program should be: a,2 c,2 b,2 e,1 d,1 g,1 f,1 Hints Use dict to store key/value pairs. Use dict.get() method to lookup a key with default value. """ '''Solution by: popomaticbubble ''' def character_counter(text): characters_list = list(text) char_count = {} for x in characters_list: if x in char_count.keys(): char_count[x] += 1 else: char_count[x] = 1 return char_count def dict_viewer(dictionary): for x, y in dictionary.items(): print(f"{x}, {y}") text = input("> ") dict_viewer(character_counter(text))
""" Question 13 Question: Write a program that accepts a sentence and calculate the number of letters and digits. Suppose the following input is supplied to the program: hello world! 123 Then, the output should be: LETTERS 10 DIGITS 3 Hints: In case of input data being supplied to the question, it should be assumed to be a console input. """ '''Solution by: hajimalung ''' #using reduce for to count from functools import reduce def count_letters_digits(counters, char_to_check): counters[0] += char_to_check.isalpha() counters[1] += char_to_check.isnumeric() return counters print('LETTERS {0}\nDIGITS {1}'.format(*reduce(count_letters_digits, input(), [0,0])))
""" Question 86 Question By using list comprehension, please write a program to print the list after removing the value 24 in [12,24,35,24,88,120,155]. Hints Use list's remove method to delete a value. """ li = [12, 24, 35, 24, 88, 120, 155] # this will remove only the first occurrence of 24 li.remove(24) print(li)
""" Question 17 Question: Write a program that computes the net amount of a bank account based a transaction log from console input. The transaction log format is shown as following: D 100 W 200 D means deposit while W means withdrawal. Suppose the following input is supplied to the program: D 300 D 300 W 200 D 100 Then, the output should be: 500 Hints: In case of input data being supplied to the question, it should be assumed to be a console input. """ total = 0 while True: s = input().split() # break if the string is empty if not s: break # two inputs are distributed in cm and num in string data type cm, num = map(str, s) if cm == 'D': total += int(num) if cm == 'W': total -= int(num) print(total)
""" Question 11 Question Write a program which accepts a sequence of comma separated 4 digit binary numbers as its input and then check whether they are divisible by 5 or not. The numbers that are divisible by 5 are to be printed in a comma separated sequence. Example: 0100,0011,1010,1001 Then the output should be: 1010 Notes: Assume the data is input by console. Hints: In case of input data being supplied to the question, it should be assumed to be a console input. """ # converts binary to integer & returns zero if divisible by 5 def check(x): total, pw = 0, 1 reversed(x) # ord() function returns ASCII value for i in x: total += pw * (ord(i) - 48) pw *= 2 return total % 5 # inputs taken here and splitted in ',' position data = input().split(",") lst = [] # if zero found it means divisible by zero and added to the list for i in data: if check(i) == 0: lst.append(i) print(",".join(lst))
#!/usr/bin/env python # coding: utf-8 # # Question 54 # # ### **Question** # # > **_Assuming that we have some email addresses in the "username@companyname.com" format, please write program to print the company name of a given email address. Both user names and company names are composed of letters only._** # # > **_Example: # > If the following email address is given as input to the program:_** # # # > john@google.com # # # > **_Then, the output of the program should be:_** # # # > google # # # > **_In case of input data being supplied to the question, it should be assumed to be a console input._** # # --- # # ### Hints # # > **_Use \w to match letters._** # # --- # # # # **Solutions:** # In[1]: import re email = "john@google.com elise@python.com" pattern = "\w+@(\w+).com" ans = re.findall(pattern, email) print(ans) # --- # # # Question 55 # # ### **Question** # # > **_Write a program which accepts a sequence of words separated by whitespace as input to print the words composed of digits only._** # # > **_Example: # > If the following words is given as input to the program:_** # # # > 2 cats and 3 dogs. # # # > **_Then, the output of the program should be:_** # # # > ['2', '3'] # # # > **_In case of input data being supplied to the question, it should be assumed to be a console input._** # # --- # # ### Hints # # > **_Use re.findall() to find all substring using regex._** # # --- # # # # **Solutions:** # In[2]: import re email = input() pattern = "\d+" ans = re.findall(pattern, email) print(ans) # **OR** # In[3]: email = input().split() ans = [] for word in email: if word.isdigit(): # can also use isnumeric() / isdecimal() function instead ans.append(word) print(ans) # **OR** # In[ ]: email = input().split() ans = [word for word in email if word.isdigit()] # using list comprehension method print(ans) # --- # # # Question 56 # # ### **Question** # # > **_Print a unicode string "hello world"._** # # --- # # ### Hints # # > **_Use u'strings' format to define unicode string._** # # --- # # # # # Question 57 # # ### **Question** # # > **_Write a program to read an ASCII string and to convert it to a unicode string encoded by utf-8._** # # --- # # ### Hints # # > **_Use unicode()/encode() function to convert._** # # --- # # # # **Solutions:** # In[ ]: s = input() u = s.encode("utf-8") print(u) # --- # # # Question 58 # # ### **Question** # # > **_Write a special comment to indicate a Python source code file is in unicode._** # # --- # # ### Hints # # > **_Use unicode() function to convert._** # # --- # # **Solution:** # In[ ]: # -*- coding: utf-8 -*- # --- # # # Question 59 # # ### **Question** # # > **_Write a program to compute 1/2+2/3+3/4+...+n/n+1 with a given n input by console (n>0)._** # # > **_Example: # > If the following n is given as input to the program:_** # # # > 5 # # # > **_Then, the output of the program should be:_** # # # > 3.55 # # # > **_In case of input data being supplied to the question, it should be assumed to be a console input._** # # --- # # ### Hints # # > **_Use float() to convert an integer to a float.Even if not converted it wont cause a problem because python by default understands the data type of a value_** # # --- # # # # **Solutions:** # In[ ]: n = int(input()) sum = 0 for i in range(1, n + 1): sum += i / (i + 1) print(round(sum, 2)) # rounded to 2 decimal point # ---
#!/usr/bin/env python # coding: utf-8 # # Question 22 # # ### **Question:** # # > **_Write a program to compute the frequency of the words from the input. The output should output after sorting the key alphanumerically._** # # > **_Suppose the following input is supplied to the program:_** # # # New to Python or choosing between Python 2 and Python 3? Read Python 2 or Python 3. # # # > **_Then, the output should be:_** # # ``` # 2:2 # 3.:1 # 3?:1 # New:1 # Python:5 # Read:1 # and:1 # between:1 # choosing:1 # or:2 # to:1 # ``` # # --- # # ### Hints # # > **_In case of input data being supplied to the question, it should be assumed to be a console input._** # # --- # # # # **Solutions:** # In[1]: ss = input().split() word = sorted(set(ss)) # split words are stored and sorted as a set for i in word: print("{0}:{1}".format(i, ss.count(i))) # **OR** # In[2]: ss = input().split() dict = {} for i in ss: i = dict.setdefault( i, ss.count(i) ) # setdefault() function takes key & value to set it as dictionary. dict = sorted( dict.items() ) # items() function returns both key & value of dictionary as a list # and then sorted. The sort by default occurs in order of 1st -> 2nd key for i in dict: print("%s:%d" % (i[0], i[1])) # **OR** # In[3]: ss = input().split() dict = { i: ss.count(i) for i in ss } # sets dictionary as i-> split word & ss.count(i) -> total occurrence of i in ss dict = sorted( dict.items() ) # items() function returns both key & value of dictionary as a list # and then sorted. The sort by default occurs in order of 1st -> 2nd key for i in dict: print("%s:%d" % (i[0], i[1])) # **OR** # In[4]: from collections import Counter ss = input().split() ss = Counter(ss) # returns key & frequency as a dictionary ss = sorted(ss.items()) # returns as a tuple list for i in ss: print("%s:%d" % (i[0], i[1])) # **Solution by: AnjanKumarG** # In[5]: from pprint import pprint p = input().split() pprint({i: p.count(i) for i in p}) # --- # # # Question 23 # # ### **Question:** # # > **_Write a method which can calculate square value of number_** # # --- # # ### Hints: # # # Using the ** operator which can be written as n**p where means n^p # # # --- # # # # **Solutions:** # In[6]: n = int(input()) print(n ** 2) # --- # # # Question 24 # # ### **Question:** # # > **_Python has many built-in functions, and if you do not know how to use it, you can read document online or find some books. But Python has a built-in document function for every built-in functions._** # # > **_Please write a program to print some Python built-in functions documents, such as abs(), int(), raw_input()_** # # > **_And add document for your own function_** # # ### Hints: # # # The built-in document method is __doc__ # # # --- # # # # **Solutions:** # In[7]: print(str.__doc__) print(sorted.__doc__) def pow(n, p): """ param n: This is any integer number param p: This is power over n return: n to the power p = n^p """ return n ** p print(pow(3, 4)) print(pow.__doc__) # --- # # # Question 25 # # ### **Question:** # # > **_Define a class, which have a class parameter and have a same instance parameter._** # # --- # # ### Hints: # # # Define an instance parameter, need add it in __init__ method.You can init an object with construct parameter or set the value later # # # --- # # # # **Solutions:** # In[8]: class Car: name = "Car" def __init__(self, name=None): self.name = name honda = Car("Honda") print(f"{Car.name} name is {honda.name}") toyota = Car() toyota.name = "Toyota" print(f"{Car.name} name is {toyota.name}") # ---
""" Question 48 Question Define a class named Rectangle which can be constructed by a length and width. The Rectangle class has a method which can compute the area. Hints Use def methodName(self) to define a method. """ class Rectangle(): def __init__(self, init_l, init_w): self.length = init_l self.width = init_w def area(self): return self.length * self.width rect = Rectangle(2,4) print(rect.area())
""" Question 6 Question: Write a program that calculates and prints the value according to the given formula: Q = Square root of [(2 _ C _ D)/H] Following are the fixed values of C and H: C is 50. H is 30. D is the variable whose values should be input to your program in a comma-separated sequence. For example Let us assume the following comma separated input sequence is given to the program: 100,150,180 The output of the program should be: 18,22,24 Hints: If the output received is in decimal form, it should be rounded off to its nearest value (for example, if the output received is 26.0, it should be printed as 26). In case of input data being supplied to the question, it should be assumed to be a console input. """ '''Solution by: saxenaharsh24 ''' my_list = [ int(x) for x in input('').split(',')] C, H, x = 50, 30, [] for D in my_list: Q = ((2*C*D) /H) ** (1/2) x.append(round(Q)) print(','.join(map(str, x)))
""" Question 96 Question You are given a string S and width W. Your task is to wrap the string into a paragraph of width. If the following string is given as input to the program: ABCDEFGHIJKLIMNOQRSTUVWXYZ 4 Then, the output of the program should be: ABCD EFGH IJKL IMNO QRST UVWX YZ Hints Use wrap function of textwrap module """ """Solution by: mishrasunny-coder """ import textwrap string = input() width = int(input()) print(textwrap.fill(string, width))
""" Question 42 Question: Write a program which can map() and filter() to make a list whose elements are square of even number in [1,2,3,4,5,6,7,8,9,10]. Hints: Use map() to generate a list. Use filter() to filter elements of a list. Use lambda to define anonymous functions. """ """ Solution by: saxenaharsh24 """ def even(item): if item % 2 == 0: return item ** 2 lst = [i for i in range(1, 11)] print( list(filter(lambda j: j is not None, list(map(even, lst)))))
""" Question 88 Question With a given list [12,24,35,24,88,120,155,88,120,155], write a program to print this list after removing all duplicate values with original order reserved. Hints Use set() to store a number of values without duplicate.""" li = [12, 24, 35, 24, 88, 120, 155, 88, 120, 155] for i in li: if li.count(i) > 1: li.remove(i) print(li)
#Fill in the contents of the is_old_enough_to_drink function. This function takes in a number, called age, and returns whether a person of this age old enough to legally drink in the United States. If the person is old enough to drink, the function should return True. If they are not old enough to drink in the united states, the function should return False. Notes: #The legal drinking age in the United States is 21 # output = is_old_enough_to_drink(22) # print(output) # --> True def is_old_enough_to_drink(age): if age>=21: return True else: return False print(is_old_enough_to_drink(20))
import math # Complete the targetRotation function below. def targetRotation(matrix, r): m= len(matrix) n=len(matrix[0]) r_circle=math.min(m,n)/2 for idx in range(r): for idx_circle in range(r_circle): row_end=m-idx_circle col_end=n-idx_circle if __name__ == '__main__': mnr = input().rstrip().split() m = int(mnr[0]) # Number of rows n = int(mnr[1]) # Number of columns r = int(mnr[2]) # Number of rotations matrix = [] for _ in range(m): matrix.append(list(map(int, input().rstrip().split()))) targetRotation(matrix, r) print(matrix[1][1])
#Milan Patel and Faizan Rashid import connectfour import common_functions def want_to_play()-> None: """introduces user and asks them if they want to start a new game""" common_functions.welcome_message() yes_or_no = str(input('Would you like to start a new game? (Enter Y or N) ')) #user has to enter Y or N (lowercase or uppercase) or keep asking while yes_or_no.lower().strip() != 'y' and yes_or_no.lower().strip() != 'n': print('\nPlease enter Y or N') yes_or_no = str(input('\nWould you like to start a new game? (Enter Y or N) ')) #if they say yes, call function that executes game if yes_or_no.lower().strip() == 'y': print() print('Enjoy your game!\n') play_game() elif yes_or_no.lower().strip() == 'n': print('You chose not to play. Have a nice day') def play_game(): """Executes game by using functions from connectfour and common_functions module""" #game_status is the GameState #call new_game function from connectfour module to create new gamestate #then call all functions from the common functions module to play the game game_status = connectfour.new_game() while True: #print current board, get move type, column number, and execute move common_functions.print_board(game_status) print(common_functions.whose_turn(game_status)) drop_or_pop = common_functions.choose_move() what_column = common_functions.column_number() if drop_or_pop == 'DROP': game_status = common_functions.move_DROP(game_status, what_column) elif drop_or_pop == 'POP': game_status = common_functions.move_POP(game_status, what_column) #if there is a winner, print winner and end program if common_functions.game_win(game_status) == False: common_functions.who_wins(game_status) break else: print() if __name__ == '__main__': want_to_play()
numero = int(input('ingrese Numero: ')) #Fibonacci fibonacci = (lambda fun: lambda arg: fun(fun,arg)) (lambda f,a:0 if a==0 else (1 if a==1 else f(f,a-1)+f(f,a-2))) (numero) print(fibonacci) #Factorial factorial = (lambda fun: lambda arg: fun(fun,arg)) (lambda f,a: 1 if a ==0 else a*f(f,a-1))(numero) print(factorial)
# Examle of function to calculate VAT def get_vat(payment, percent=18): print (percent) try: payment = float(payment) vat = payment / 100 * percent vat = round(vat, 2) return 'final VAT is {}'.format(vat) except (TypeError, ValueError): return 'can not count, check your input data' result = get_vat(1000, 18) print(result)
import unittest def can_enter_all_rooms(rooms): ''' Checks whether all rooms can be entered :param rooms: A list of lists. :return: True or False ''' keys = [False] * len(rooms) print(keys) enter = [0] while len(enter) > 0: one = enter.pop(0) if keys[one]: continue keys[one] = True for key in rooms[one]: if key < len(keys): enter.append(key) for key in keys: if not key: return False return True class Test(unittest.TestCase): def test_one(self): rooms = [[1], [0,2], [3]] self.assertTrue(can_enter_all_rooms(rooms)) def test_two(self): rooms = [[1,3], [3,0,1], [2], [0]] self.assertFalse(can_enter_all_rooms(rooms)) # def test_three(self): rooms = [[1,2,3], [0], [0], [0]] self.assertTrue(can_enter_all_rooms(rooms)) def test_four(self): rooms = [[1], [0,2,4], [1,3,4], [2], [1,2]] self.assertTrue(can_enter_all_rooms(rooms)) def test_five(self): rooms = [[1], [2,3], [1,2], [4], [1], [5]] self.assertFalse(can_enter_all_rooms(rooms)) def test_six(self): rooms = [[1], [2], [3], [4], [2]] self.assertTrue(can_enter_all_rooms(rooms)) def test_seven(self): rooms = [[1], [1,3], [2], [2,4,6], [], [1,2,3], [1]] self.assertFalse(can_enter_all_rooms(rooms)) unittest.main(verbosity=2)
import unittest def is_single_riffle(half1, half2, shuffled_deck): # Check if the shuffled deck is a single riffle of the halves i = j = 0 for card in shuffled_deck: if i < len(half1) and j < len(half2): if half1[i] != card and half2[j] != card: return False if half1[i] == card: i += 1 elif half2[j] == card: j += 1 elif i < len(half1): if half1[i] != card: return False i += 1 elif j < len(half2): if half2[j] != card: return False j += 1 else: return False return True # Tests class Test(unittest.TestCase): def test_both_halves_are_the_same_length(self): result = is_single_riffle([1, 4, 5], [2, 3, 6], [1, 2, 3, 4, 5, 6]) self.assertTrue(result) def test_halves_are_different_lengths(self): result = is_single_riffle([1, 5], [2, 3, 6], [1, 2, 6, 3, 5]) self.assertFalse(result) def test_one_half_is_empty(self): result = is_single_riffle([], [2, 3, 6], [2, 3, 6]) self.assertTrue(result) def test_shuffled_deck_is_missing_cards(self): result = is_single_riffle([1, 5], [2, 3, 6], [1, 6, 3, 5]) self.assertFalse(result) def test_shuffled_deck_has_extra_cards(self): result = is_single_riffle([1, 5], [2, 3, 6], [1, 2, 3, 5, 6, 8]) self.assertFalse(result) unittest.main(verbosity=2)
c=int(input("")) temp=c a=0 while(c>0): x=c%10 a=a*10+x c=c//10 if(temp==a): print("yes") else: print("no")
while True: try: x = float(input("x = ")) y = float(input("y = ")) except ValueError: print("Not a number, please try again.") else: break while y == 0: print("Please select a different y (divisor) as to not make your primary school teacher unhappy :D") while True: try: y = float(input("y = ")) except ValueError: print("Not a number, please enter again.") else: break result1 = x - y result2 = x/y print("x - y = ", '{0:.4f}'.format(result1)) print("x/y = ", '{0:.4f}'.format(result2))
from turtle import * # importing whole turtle module from random import randrange # importing random from freegames import square, vector #importing freegames amul=Turtle() target = vector(0, 0) #this is snake = [vector(10, 0)] pointer = vector(0, -10) wn=Screen() # this is for background color wn.bgcolor('blue') # background in blue color def func_1(x, y): #parameters are 2 since its a 2-D game pointer.x = x # represents x axis pointer.y = y # represents y axis def func_2(part): #boundary values. End values are essential for defining square. return -200 < part.x < 190 and -200 < part.y < 190 # when snake crosses boundary values it is a foul. def move(): # movement is given to snake, it only moves in forward direction part= snake[-1].copy() part.move(pointer) if not func_2(part) or part in snake: square(part.x, part.y, 9, 'red') update() return snake.append(part) if part== target: # for counting print('Snake:', len(snake)) target.x = randrange(-15, 15) * 10 target.y = randrange(-15, 15) * 10 else: snake.pop(0) clear() for i in snake: # snake element-combination of squares. square(i.x, i.y, 9, 'black') square(target.x, target.y, 9, 'violet') update() # to update all the steps. ontimer(move, 100) hideturtle()# to hide the turtle(arrow) tracer(False) # brings back elements to initial state listen()# countinously updates game onkey(lambda: func_1(10, 0), 'Right') # controls are given onkey(lambda: func_1(-10, 0), 'Left') onkey(lambda: func_1(0, 10), 'Up') onkey(lambda: func_1(0, -10), 'Down') move() # calling function done() # for holding screen
print("calculate an average of first n natural numbers") n = input("Enter Number ") n = int(n) average = 0 sum = 0 for num in range(0, n+1, 1): sum = sum+num average = sum / n print("Average of first ", n, "number is: ", average)
from card import Card from random import shuffle as randomshuffle #I'm going to treat a list as a deck, with the right side of the list being the bottom of the deck, and the left side of the #list being the top of the deck class Deck(): def __init__(self) -> None: ''' A class that implements basic functionality of a deck of cards. A new instance contains all the cards without the jokers, sorted by suit and then by rank. ''' self.cards = list() for suit in Card.SUITS: for rank in Card.RANKS: self.cards.append(Card(suit, rank)) def shuffle(self) -> None: ''' Shuffles the deck. ''' randomshuffle(self.cards) def deal_one(self) -> Card: ''' Removes and returns the top card from the deck. ''' return self.cards.pop(0) def __len__(self) -> int: ''' Returns the number of cards left in the deck. ''' return len(self.cards)
# Example of using optional parameters in python def func(word, freq=1, add=5): print(word*(freq+add)) call = func('hello', add=3)
import random as rand import numpy.random as rand_2 # Problem : [ [0, 0, 0, 0], # [0, 0, 0, 0], # [0, 0, 0, 0], # [0, 0, 0, 0] ] # Goal: [ [1, 1, 1, 1], # [1, 1, 1, 1], # [1, 1, 1, 1], # [1, 1, 1, 1] ] # Generating population randomly def generate_population(array): temp_array = array.copy() chromosome = [] for i in range(len(array)): # Iterating over 2D array row = array[i] # Taking row or element of 2D array chromosome.extend(row) # As chromosome is 1D array population = [chromosome.copy() for _ in range(4)] # Initializing 4 chromosmes for populaiton for i in range(4): print("---> ",population[i]) individual_chromosome = population[i] for rand_ind in [rand.randrange(0, len(array)) for _ in range(8)]: # Generating random indices to change value of individual_chromosome[rand_ind] = 1 return population # calculating fitness value of any individual def calculate_fitness(individual): num_of_ones = 0 for i in range(len(individual)): num_of_ones = num_of_ones + individual[i] # As each value is simply 0 or 1 so we can know number of 1's by siply adding return num_of_ones # Check if any individual is fit enough to be the goal state or desirable def individual_fit_enough(population, fitness_threshold=16): fittest_individual = max(population, key=calculate_fitness) if calculate_fitness(fittest_individual) == fitness_threshold: # If fitness value of any individual is equal to 16 return True return False # Randomly select any individual from population by its selection_prob def select(population, calculate_fitness): fitness_values = [calculate_fitness(individual) for individual in population] # fitness values of population sum_fitness = sum(fitness_values) # sum of fitness values selection_probs = [fitness_values[index]/sum_fitness for index, individual in enumerate(population)] # Array holding selection prob for each individual selection_prob(of individual) = fitness_value(of individual) / sum_of_all_fitness_values population_indices = [ind for ind in range(len(population))] # Indices of individual in population, necessary for numpy.random.choice as it requires a=1D array selected_individual_index = rand_2.choice(population_indices, p=selection_probs) # p is the selected_probs of corresponding individuals return population[selected_individual_index] # Reproduce a child using x and y chromosme def reproduce(x, y): n = len(x) c = rand.randint(0,n) return x[:c] + y[c:] # x upto random n index extended with y from random n index # mutate a chile using prob 0.1 def mutate(child): new_child = child.copy() rand_index = rand.randint(0, len(child)-1) # len(child)-1 as we need between 0 to 15 index value rand_value = rand.randint(0, 1) new_child[rand_index] = rand_value return new_child # genetic search def genetic_search(population, calculate_fitness): while not individual_fit_enough(population): # repeat until any individual is fit enough or time limit new_population = [] for i in range(len(population)): x = select(population, calculate_fitness) y = select(population, calculate_fitness) child = reproduce(x, y) if (rand.uniform(0,1) <= 0.1): # mutate with prob 0.1 child = mutate(child) new_population.append(child) population = new_population return max(population, key=calculate_fitness) # return most fitted population = generate_population([ [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0] ] ) individual_fit_enough(population) print(population) select(population, calculate_fitness) print('goal', genetic_search(population, calculate_fitness)) max?
number = 5 if number == 5 : print("Number is 5") else: print("Number is not 5") #Truthy and Falsy values: if number: # just checks that the variable is defined: which it is so it is truthy print("Number is defined and 'Truthy'") text = "Python" if text: # just checks that the variable is defined: which it is so it is truthy print("Text is defined and 'Truthy'") python_file = True if python_file: # just checks that the variable is defined: which it is so it is truthy print("This will execute") aliens_found = None if aliens_found:# just checks that the variable is defined: which it is NOT so it is falsy and the statement will not execute print("This will not execute as 'None' is 'falsy'") #check if condition is false avoids having to create a true statment and putting logic in the else section if number != 5: print ("This will not execute") if not python_file: print("This will not execute") # linking multiple if conditions if number == 5 and python_file: print("This will execute as both conditions are true") if number == 17 or python_file: print("This will execute as only one condition needs to be true") #ternary if statements a = 1 b = 2 "bigger" if a > b else "smaller"
# complex polygon as shape, using turtle.Shape import turtle import engine WIDTH = 640 HEIGHT = 480 class House(engine.GameObject): def __init__(self): super().__init__(0, 0, 0, 0, 'house', 'blue') def heading(self): return 90 def makeshape(): house = turtle.Shape("compound") wall = ((0,-5),(100,-5),(100,-60),(0,-60)) house.addcomponent(wall, "white", "black") door = ((80,-60),(80,-20),(55,-20),(55, -60)) house.addcomponent(door, "brown", "black") window = ((15,-22), (40,-22), (40, -45), (15,-45)) house.addcomponent(window, "blue", "black") roof = ((-10,-5), (110,-5), (50, 30)) house.addcomponent(roof, "red", "red") turtle.register_shape('house', house) if __name__ == '__main__': engine.init_screen(WIDTH, HEIGHT) engine.init_engine() makeshape() house = House() engine.add_obj(house) engine.engine()
from utils import database USER_CHOICE = """ Enter : - 'a' to add a new contact - 'l' to list all the contact - 'd' to delete a book - 'q' to quit Your choice ? : """ def menu(): database.create_contact_table() user_input = input(USER_CHOICE) while user_input != 'q': if user_input == 'a': prompt_add_contact() elif user_input == 'l': list_contacts() elif user_input == 'd': prompt_delete_contact() else: print("Unknown input given, please try again. ") user_input = input(USER_CHOICE) def prompt_add_contact(): name = input("Enter the contact name : ") number = input("Enter the contact number: ") database.add_contact(name,number) def list_contacts(): contacts = database.get_all_contacts() for contact in contacts: print(f"{contact['name']}'s number is {contact['number']}") def prompt_delete_contact(): name = input("Enter the name of the contact that u want to delete : ") database.delete_contact(name) menu()
""" 完善你的Calc的用例,增加更多用例(浮点数相乘bug) - 提交你的github测试文件地址 - 把allure的首页截图到回帖中 """ import allure import pytest from core.calc import Calc from tests.base import Base @allure.feature("除法测试用例") class TestCalcDiv(Base): @allure.story("正常整数") @pytest.mark.parametrize("a, b, exp", [ (1, 2, 0.5), (100, 10, 10), (-3, -4, 0.75), (-10, -5, 2), (250, -5, -50), (-60, 3, -20) ]) def test_div_int(self, a, b, exp): assert self.calc.div(a, b) == exp @allure.story("正常小数") @pytest.mark.parametrize("a, b, exp", [ (1.5, 0.3, 5), (0.4, 0.8, 0.5), (-0.9, -0.3, 3), (-0.4, -1.6, 0.25), (2.8, -0.7, -4), (-5.6, 0.8, -7), (0.008, 0.2, 0.04) ]) def test_div_float(self, a, b, exp): assert self.calc.div(a, b) == exp @allure.story("正常小数和整数") @pytest.mark.parametrize("a, b, exp", [ (5, 0.5, 10), (1.8, 6, 0.3), (-0.6, -3, 0.2), (-3, -0.5, 6), (4, -0.2, -20), (-1.5, 3, -0.5) ]) def test_div_mix(self, a, b, exp): assert self.calc.div(a, b) == exp @allure.story("特殊值0处理") @pytest.mark.parametrize("a, b, exp", [ (0, 100, 0), (0, -10, 0), (0, 0.9, 0), (0, -1.784, 0) ]) def test_div_zero(self, a, b, exp): assert self.calc.div(a, b) == exp @allure.story("错误类型") @pytest.mark.parametrize("a, b", [ (2, 0), (-102, 0), (0, 0), (1.85, 0), (-0.09, 0), ('jjj', 'hhh'), ('*', ','), (True, False) ]) def test_div_err(self, a, b): with pytest.raises(Exception): assert self.calc.div(a, b) @allure.feature("乘法测试用例") class TestCalcMul: @allure.story("正常整数和0") @pytest.mark.parametrize("a, b, exp", [ (1, 2, 2), (100, 10, 1000), (-3, -4, 12), (-10, -5, 50), (250, -5, -1250), (-60, 3, -180), (0, 0, 0), (0, 13, 0), (294, 0, 0), (-293, 0, 0), (0, -39, 0) ]) def test_mul(self, a, b, exp): assert self.calc.mul(a, b) == exp @allure.story("正常小数") @pytest.mark.parametrize("a, b, exp", [ (1.5, 0.3, 5), (0.4, 0.8, 0.5), (-0.9, -0.3, 3), (-0.4, -1.6, 0.25), (2.8, -0.7, -4), (-5.6, 0.8, -7), (0.008, 0.2, 0.04) ]) def test_mul_float(self, a, b, exp): assert self.calc.div(a, b) == exp @allure.story("正常小数和整数") @pytest.mark.parametrize("a, b, exp", [ (5, 0.5, 10), (1.8, 6, 0.3), (-0.6, -3, 0.2), (-3, -0.5, 6), (4, -0.2, -20), (-1.5, 3, -0.5), (958.039, 0, 0), (0, 0.001, 0), (-0.394, 0, 0), (0, -9.39244, 0) ]) def test_mul_mix(self, a, b, exp): assert self.calc.div(a, b) == exp @allure.story("错误类型") @pytest.mark.parametrize("a, b", [ ('jjj', 'hhh'), ('*', ','), (True, False) ]) def test_div_err(self, a, b): with pytest.raises(Exception): assert self.calc.div(a, b) @allure.feature("混合场景,流程示例") class TestCalcMix: @allure.story("先除后乘") def test_mix1(self): result1 = self.calc.div(1024, 128) result2 = self.calc.mul(16, 16) assert result1 == 8 assert result2 == 256 @allure.story("先乘后除") def test_mix2(self): result1 = self.calc.mul(1024, 1024) result2 = self.calc.div(32, 8) assert result1 == 1048576 assert result2 == 4
a_list = [1,5,3,4] print([x+1 for x in a_list]) print([x for x in range(1,11) if x%2==0]) print([x for x in range(1,11) if x%2!=0]) s= [ x**2 for x in range(10)] v= [ 2**x for x in range(13)] m = [x for x in s if x%2 == 0] print("S", s) print("V", v) print("M", m) a_set = set(range(10)) print({x**2 for x in a_set}) a_dict = {'a' : 10, 'b': 20, 'c': 30} print({value:key for key, value in list(a_dict.items())})
file_name = 'file.txt' try: f = open(file_name) cnt = 0 while True: cnt += 1 line = f.readline() if line == '': break print("%d : %s" %(cnt, line), end=' ') except IOError: print('Can not open the file')
a = "10" b = "20" print(a, int(a), type(a), type(int(a))) print(b, int(b), type(b), type(int(b))) print(a + b) print(int(a) + int(b)) print(float("3.14")) print(float(123)) print(complex("3+5j")) print(complex(1234)) print(str(10)) print('%s'%10)
print('abc' + 'def') #print '10' + 2 #error #print '10' - 2 print('abc' * 3) #print '10' / 2 print(2 ** 3) print(7 / 4) print(7 % 4) print(divmod(7,4)) print(7 / 4.0) print(7 // 4.0) print((2 + 3j) + (3 + 2j)) num = 10 num+=1 print(num) num-=1 print(num) #num++ #error #num-- print(True and True) print(True and False) print(False and True) print(False and False) print(True or True) print(True or False) print(False or True) print(False or False) print(not True) print(not False) print('a' in 'abcd') print(1 in [1,2,3,4]) print(1 not in [5,6,7,8]) print(~5) # 0000...0101 --> 1111....1010 (-6) print(3 << 2) # 0000 0011 --> 0000 1100 (12) print(4 >> 1) # 0000 0100 --> 0000 0010 (2) print(3 & 2) # 0011 & 0010 --> 0010 (2) print(3 | 8) # 0011 | 1000 --> 1011 (11) print(15 ^ 6) # 1111 ^ 0110 --> 1001 (9)
dict1 = {'name':'Lee','age':'27','height':185} print(type(dict1), dict1, len(dict1)) print(dict1.get('name')) dict1['height'] = 180 dict1['weight'] = 68 print('after editing:', dict1) del dict1['height'] print(dict1) dict1.clear() print(dict1) dict1['new'] =123 print(dict1) dict2 = {'car':'bmw','house':'aprtment','phone':'android'} print(list(dict2.keys())) print(list(dict2.values())) print(list(dict2.items())) print(list(dict2.items())[0][0]) for key in dict2: value=dict2[key] print(key, ':', value) print('--------------------') for key in list(dict2.keys()): value = dict2[key] print(key, ':', value)
d = {'a':1, 'b': 2} print d['c'] ''' Traceback (most recent call last): File "exceptions_KeyError.py", line 13, in <module> print d['c'] KeyError: 'c' '''
## Capture image from a camera , convert it to opencv image format and then display it ## Author: Waqar Rashid ## Email: waqarrashid33@gmail.com # import the necessary packages import cv2 import numpy import io import picamera #Create a memory stream so photos doesn't need to be saved in a file stream = io.BytesIO() #Get the picture (low resolution, so it should be quite fast) #Here you can also specify other parameters (e.g.:rotate the image) with picamera.PiCamera(camera_num=0, stereo_mode= 'none') as camera: camera.resolution = (1280, 720) camera.capture(stream, format='jpeg') #Convert the picture into a numpy array buff = numpy.fromstring(stream.getvalue(), dtype=numpy.uint8) #Now creates an OpenCV image image = cv2.imdecode(buff, 1) # display the image on screen and wait for a keypress cv2.imwrite("cam0.jpg", image) cv2.waitKey(0)
import sys def solution(phone_book): answer = True dic={} for phone_number in phone_book: dic[phone_number]=1 for phone_number in phone_book:# 번호책에서 번호를 가져온다--1 temp="" for number in phone_number:#번호 하나 하나를 이어 붙인다.--2 temp+=number if temp in dic and temp != phone_number:#아직 현재 전화번호를 다 완성하지 못했는데 앞에 접두사 부분과 동일한 번호가 있을때--3 return False return True # def solution(phone_book): # answer = True # phone_book.sort() # for i in range(len(phone_book)-1): # if phone_book[i+1].startswith(phone_book[i]): # return False # return True phone_book=["123","456","789"] print(solution(phone_book))
import turtle import math print("Please enter two legs of a right triangle") a = float(input("Leg #1: ")) b = float(input("Leg #2: ")) c = math.sqrt(a**2 + b**2) alpha_in_radians = math.atan((a / b)) alpha = math.degrees(alpha_in_radians) beta = 90 - alpha turtle.forward(a) turtle.left(90) turtle.forward(b) turtle.left(180 - alpha) turtle.forward(c) turtle.left(180 - beta) turtle.hideturtle() turtle.done
kilos = float(input("Please enter weight in kilograms: ")) meters = float(input("Please enter height in meters: ")) bmi = kilos/meters**2 status = None if bmi < 18.5: status = "Underweight" elif 18.5 <= bmi <= 24.9: status = "Normal" elif 25 <= bmi <= 29.9: status = "Overweight" elif bmi >= 30: status = "Obese" else: status = "Invalid input!" print(f'BMI is: {round(bmi, 2)}, Status is {status}')
#!/usr/bin/python '''A Python program generating a list of prime numbers and output them into a csv file ''' from primepackage import* def main(): '''Generate 100 prime numbers and output it into output.csv file ''' try: primes = get_n_prime(100) write_primes(primes, 'output.csv') nums = read_primes('output.csv') except IOError as err: print(err) except ValueError as num_err: print(num_err) except TypeError as type_err: print(type_err) print(nums) if __name__ == '__main__': main()
''' You are given a positive integer k. You are also given: a 2D integer array rowConditions of size n where rowConditions[i] = [abovei, belowi], and a 2D integer array colConditions of size m where colConditions[i] = [lefti, righti]. The two arrays contain integers from 1 to k. You have to build a k x k matrix that contains each of the numbers from 1 to k exactly once. The remaining cells should have the value 0. The matrix should also satisfy the following conditions: The number abovei should appear in a row that is strictly above the row at which the number belowi appears for all i from 0 to n - 1. The number lefti should appear in a column that is strictly left of the column at which the number righti appears for all i from 0 to m - 1. Return any matrix that satisfies the conditions. If no answer exists, return an empty matrix. ''' class Solution: def buildMatrix(self, k: int, rc: List[List[int]], cc: List[List[int]]) -> List[List[int]]: def toposortBFS(cond): adj=[[] for i in range(k+1)] for u,v in cond: adj[u].append(v) inDegree=[0 for i in range(k+1)] topoArray=[] q=[] for i in range(1,k+1): for j in adj[i]: inDegree[j]+=1 for i in range(1,k+1): if inDegree[i]==0: q.append(i) while q: ele=q.pop(0) topoArray.append(ele) for it in adj[ele]: inDegree[it]-=1 if inDegree[it]==0: q.append(it) return topoArray t1=toposortBFS(rc) t2=toposortBFS(cc) if len(t1)<k or len(t2)<k: return [] ans=[[0 for i in range(k)] for i in range(k)] hmap=defaultdict(list) for ind,x in enumerate(t1): hmap[x].append(ind) for ind,x in enumerate(t2): hmap[x].append(ind) for key in hmap.keys(): x,y=hmap[key] ans[x][y]=key return ans ------------------------------------------------------------------------------------------------------------------ class Solution: def buildMatrix(self, n: int, rowC: List[List[int]], colC: List[List[int]]) -> List[List[int]]: # create two graphs, one for row and one for columns row_adj = {i: [] for i in range(1, n + 1)} col_adj = {i: [] for i in range(1, n + 1)} for u, v in rowC: row_adj[u].append(v) for u, v in colC: col_adj[u].append(v) # inorder to do topological sort, we need to maintain two visit lists: one marks which node # we have already processed (because not all nodes are connected to each other and we do not # want to end up in a infinite loop), the other one marks nodes we are currently visiting(or in # our recursion stack). If we visit a node that we are currently visiting, that means there is # a loop, so we return False; if it is not in our current visit but has already been visited, we # can safely travel to the next node and return True. row_stack = [] row_visit = set() row_visiting = set() col_stack = [] col_visit = set() col_visiting = set() def dfs(node, stack, visit, visiting, adj): if node in visiting: return False if node in visit: return True visit.add(node) visiting.add(node) for child in adj[node]: if not dfs(child, stack, visit, visiting, adj): return False visiting.remove(node) stack.append(node) return True # do dfs on each row/col graph for i in range(1, n + 1): if i not in row_visit: if not dfs(i, row_stack, row_visit, row_visiting, row_adj): return [] if i not in col_visit: if not dfs(i, col_stack, col_visit, col_visiting, col_adj): return [] # After the dfs, we also need a stack to store which node has been entirely explored. That's why we # append the current node to our stack after exploring all its neighbors. Remember we have to reverse # the stack after all DFS's, because the first-explored node gets appended first. row_stack, col_stack = row_stack[::-1], col_stack[::-1] # mark position for each element row_memo, col_memo = {}, {} for idx, num in enumerate(row_stack): row_memo[num] = idx for idx, num in enumerate(col_stack): col_memo[num] = idx # create an empty matrix as our ans ans = [[0]*n for _ in range(n)] # plug in values from what we have discovered for i in range(1, n + 1): ans[row_memo[i]][col_memo[i]] = i return ans ------------------------------------------------------------------------------------------------------------------------
''' You are given a 0-indexed integer array nums and an integer pivot. Rearrange nums such that the following conditions are satisfied: Every element less than pivot appears before every element greater than pivot. Every element equal to pivot appears in between the elements less than and greater than pivot. The relative order of the elements less than pivot and the elements greater than pivot is maintained. More formally, consider every pi, pj where pi is the new position of the ith element and pj is the new position of the jth element. For elements less than pivot, if i < j and nums[i] < pivot and nums[j] < pivot, then pi < pj. Similarly for elements greater than pivot, if i < j and nums[i] > pivot and nums[j] > pivot, then pi < pj. Return nums after the rearrangement. ''' class Solution: def pivotArray(self, nums: List[int], pivot: int) -> List[int]: before = list(filter(lambda x: x < pivot, nums)) equal = list(filter(lambda x: x == pivot, nums)) after = list(filter(lambda x: x > pivot, nums)) nums = before + equal + after print(nums) return nums -------------------------------------------------------------------------------------------------- class Solution: def pivotArray(self, nums: List[int], pivot: int) -> List[int]: ans=[] nums.remove(pivot) i=0 ans.append(pivot) for j in nums: if j<pivot: ans.insert(i,j) i=i+1 elif j==pivot: ans.insert(i+1,j) else: ans.append(j) return ans
''' We have n cities labeled from 1 to n. Two different cities with labels x and y are directly connected by a bidirectional road if and only if x and y share a common divisor strictly greater than some threshold. More formally, cities with labels x and y have a road between them if there exists an integer z such that all of the following are true: x % z == 0, y % z == 0, and z > threshold. Given the two integers, n and threshold, and an array of queries, you must determine for each queries[i] = [ai, bi] if cities ai and bi are connected directly or indirectly. (i.e. there is some path between them). Return an array answer, where answer.length == queries.length and answer[i] is true if for the ith query, there is a path between ai and bi, or answer[i] is false if there is no path. ''' class UnionFind: def __init__(self, size): self.root = [i for i in range(size)] self.rank = [1] * size def find(self, x): if x == self.root[x]: return x self.root[x] = self.find(self.root[x]) return self.root[x] def union(self, x, y): rootX = self.find(x) rootY = self.find(y) if rootX != rootY: if self.rank[rootX] > self.rank[rootY]: self.root[rootY] = rootX elif self.rank[rootX] < self.rank[rootY]: self.root[rootX] = rootY else: self.root[rootY] = rootX self.rank[rootX] += 1 def connected(self, x, y): return self.find(x) == self.find(y) class Solution: def areConnected(self, n: int, threshold: int, queries: List[List[int]]) -> List[bool]: import math @lru_cache def gcd(x, y): return math.gcd(x, y) uf = UnionFind(n+1) for k in range(threshold+1, n+1): std = k for num in range(std, n+1, k): uf.union(std, num) for i in range(len(queries)): queries[i] = uf.connected(queries[i][0], queries[i][1]) return queries ---------------------------------------------------------------------------------------------------------------- class Solution: def areConnected(self, n: int, threshold: int, queries: List[List[int]]) -> List[bool]: G = defaultdict(set) for i in range(max(1,threshold+1),n+1): for j in range(i,n+1,i): G[i+n].add(j) G[j].add(i+n) color = {} seed = 0 def dfs(i,col): color[i]=col for j in G[i]: if j not in color: dfs(j,col) for i in range(1,n+1): if i not in color: seed+=1 dfs(i,seed) return [color[i]==color[j] for i,j in queries]
''' Given an integer n, return the number of ways you can write n as the sum of consecutive positive integers. ''' ----------------------------------------------------------------------------------------------------- class Solution: def consecutiveNumbersSum(self, n: int) -> int: ans, sumNum, cnt = 1, 1, 2 while sumNum < n: if sumNum % cnt == n % cnt: ans += 1 sumNum += cnt cnt += 1 return ans The point of this problem is, it should be divided into consecutive numbers. Let's think about dividing the number 15. If we want to break 15 down to three consecutive numbers, it should be like m / m + 1 / m + 2(or m - 1 / m / m + 1, or m - 2 / m - 1 / m), which is 4 / 5 / 6 and m is 4 in this case. If it's divided into five chunks, it should be like m / m + 1 /m + 2 / m + 3 / m + 4, which will be 1 / 2 / 3 / 4 / 5 and m is 1. So we can say the number n can be expressed as k*m + Sum{0~(k-1)} if the number n is split into k pieces. Now, all we have to do is to see if the result of Sum{0~(k-1)} % k is equal to n % k because if they have the same remainders, it means we can successfully split n into k consecutive numbers. In my code, sumNum is the result of Sum{0~(k-1)} and cnt is the k number and also the next number to be added to sumNum at the same time. Running though the loop, the code checks the value of remainders and keeps adding numbers to sumNum and cnt. The loop ends when sumNum is equal or bigger than the number n because the sum of remainders shouldn't be bigger than n.
''' Given an array of strings words, return the first palindromic string in the array. If there is no such string, return an empty string "". A string is palindromic if it reads the same forward and backward. ''' class Solution: def firstPalindrome(self, words: List[str]) -> str: def check_palindrome(s): if len(s) % 2 == 0: mid = len(s)//2 first = s[:mid] second = s[mid:] second = second[::-1] return first == second else: mid = len(s)//2 first = s[:mid] second = s[(mid+1):] second = second[::-1] return first == second for word in words: if check_palindrome(word): return word return ''
''' You are given a 0-indexed string s and a 0-indexed integer array spaces that describes the indices in the original string where spaces will be added. Each space should be inserted before the character at the given index. For example, given s = "EnjoyYourCoffee" and spaces = [5, 9], we place spaces before 'Y' and 'C', which are at indices 5 and 9 respectively. Thus, we obtain "Enjoy Your Coffee". Return the modified string after the spaces have been added. ''' class Solution: def addSpaces(self, s: str, spaces: List[int]) -> str: arr = [] prev = 0 for space in spaces: arr.append(s[prev:space]) prev = space arr.append(s[space:]) return " ".join(arr)
''' Implement a SnapshotArray that supports the following interface: SnapshotArray(int length) initializes an array-like data structure with the given length. Initially, each element equals 0. void set(index, val) sets the element at the given index to be equal to val. int snap() takes a snapshot of the array and returns the snap_id: the total number of times we called snap() minus 1. int get(index, snap_id) returns the value at the given index, at the time we took the snapshot with the given snap_id ''' #this takes lots of space though class SnapshotArray: def __init__(self, length: int): self.cache = [] self.d = dict() self.i = 0 def set(self, index: int, val: int) -> None: self.d[index] = val def snap(self) -> int: self.cache.append(dict(self.d)) self.i += 1 return self.i-1 def get(self, index: int, snap_id: int) -> int: snap = self.cache[snap_id] return snap[index] if index in snap else 0 ---------------------------------------------------------------------------------------------------------- class SnapshotArray(object): def __init__(self, length): """ :type length: int """ self.snap_id = 0 self.list = [[[-1, 0]] for _ in range(length)] def set(self, index, val): """ :type index: int :type val: int :rtype: None """ self.list[index].append([self.snap_id, val]) def snap(self): """ :rtype: int """ ans = self.snap_id self.snap_id += 1 return ans def get(self, index, snap_id): """ :type index: int :type snap_id: int :rtype: int """ #print(self.list) li = self.list[index] left, right = 0, len(li) - 1 while left + 1 < right: mid = (left + right) // 2 if li[mid][0] <= snap_id: left = mid else: right = mid if li[right][0] <= snap_id: return li[right][1] return li[left][1]
''' A sentence is a list of words that are separated by a single space with no leading or trailing spaces. For example, "Hello World", "HELLO", "hello world hello world" are all sentences. Words consist of only uppercase and lowercase English letters. Two sentences sentence1 and sentence2 are similar if it is possible to insert an arbitrary sentence (possibly empty) inside one of these sentences such that the two sentences become equal. For example, sentence1 = "Hello my name is Jane" and sentence2 = "Hello Jane" can be made equal by inserting "my name is" between "Hello" and "Jane" in sentence2. Given two sentences sentence1 and sentence2, return true if sentence1 and sentence2 are similar. Otherwise, return false. ''' class Solution: def areSentencesSimilar(self, sentence1: str, sentence2: str) -> bool: s1 = sentence1.split() s2 = sentence2.split() # let s1 be the shorter sequence if len(s1) > len(s2): s1,s2 = s2,s1 # find the first index where they differ i = 0 while i < len(s1): if s1[i] != s2[i]: break i += 1 # check if the trailing part of s1 matches the end of s2 return s1[i:] == s2[len(s2) - (len(s1) - i):] ------------------------------------------------------------------- If the first words match, pop them out If the last words match,pop them out If neither matches, return False class Solution: def areSentencesSimilar(self, sentence1: str, sentence2: str) -> bool: s1 = sentence1.split() s2 = sentence2.split() if(len(s1)>len(s2)): #let s1 be the smaller and s2 be the greater s1,s2 = s2,s1 while(s1): if(s2[0]==s1[0]): s2.pop(0) s1.pop(0) elif(s2[-1]==s1[-1]): s2.pop() s1.pop() else: return(False) return(True) ----------------------------------------------------------------------------------------------------------------- Let's break it down: If sentences are the same - they are similar If sentences don't have a common prefix or don't have a common suffix - they are not similar If either common prefix or common suffix equals one of the lengths of the sentences - then they are similar! If they have common prefix and common suffix, and one of the sentances can be build by the common_prefix+common_suffix - then they are similiar! Please upvote if you find the explanation helful! :) Code: class Solution: def areSentencesSimilar(self, sentence1: str, sentence2: str) -> bool: if sentence1 == sentence2: return True def longst_common_prefix(s1, s2): prefix = [] for x1, x2 in zip(s1, s2): if x1 == x2: prefix.append(x1) else: break return prefix def longst_common_suffix(s1, s2): s1 = s1[::-1] s2 = s2[::-1] return longst_common_prefix(s1, s2)[::-1] words1 = sentence1.split(' ') words2 = sentence2.split(' ') common_prefix = longst_common_prefix(words1, words2) common_suffix = longst_common_suffix(words1, words2) def can_match(common_prefix, common_suffix, words1, words2): if not common_prefix and not common_suffix: return False sentances_lengts = { len(words1), len(words2) } if len(common_prefix) in sentances_lengts: return True if len(common_suffix) in sentances_lengts: return True total_common_legnth = len(common_prefix) + len(common_suffix) return total_common_legnth in sentances_lengts return can_match(common_prefix, common_suffix, words1, words2)
''' A set of real numbers can be represented as the union of several disjoint intervals, where each interval is in the form [a, b). A real number x is in the set if one of its intervals [a, b) contains x (i.e. a <= x < b). You are given a sorted list of disjoint intervals intervals representing a set of real numbers as described above, where intervals[i] = [ai, bi] represents the interval [ai, bi). You are also given another interval toBeRemoved. Return the set of real numbers with the interval toBeRemoved removed from intervals. In other words, return the set of real numbers such that every x in the set is in intervals but not in toBeRemoved. Your answer should be a sorted list of disjoint intervals as described above. ''' my simple yet maybe naive solution. for each interval in the invervals list, there are just 4 senarios: interval is outside of the toBeRemoved range, append to res interval intersects with the toBeRemoved on the frond end, only append the [a, toBeRemoved[0]] portion interval intersects with the toBeRemoved on the back end, only append the [toBeRemoved[1], b] portion inverval could be bigger than toBeRemoved, in that case, add both front end and the back end portion of the inverval inverval is in completely in toBeRemoved, do nothing! it is to be removed then just turn them into 4 if statements. class Solution: def removeInterval(self, intervals: List[List[int]], toBeRemoved: List[int]) -> List[List[int]]: res = [] for a, b in intervals: if b <= toBeRemoved[0] or a >= toBeRemoved[1]: # out of range res.append([a, b]) elif a < toBeRemoved[0] < b <= toBeRemoved[1]: # intersect in the front res.append([a, toBeRemoved[0]]) elif toBeRemoved[0] <= a < toBeRemoved[1] < b: # intersect on the back res.append([toBeRemoved[1], b]) elif a < toBeRemoved[0] and b > toBeRemoved[1]: # interval is bigger than toBeRemoved res.append([a, toBeRemoved[0]]) res.append([toBeRemoved[1], b]) return res -------------------------------------------------------- def removeInterval(self, intervals: List[List[int]], toBeRemoved: List[int]) -> List[List[int]]: x, y = toBeRemoved res = [] for a, b in intervals: left, right = max(x, a), min(y, b) if right <= left: # no intersection res.append([a, b]) continue if a < left: res.append([a, left]) if b > right: res.append([right, b]) return res ------------------------------------------------------------- class Solution: def removeInterval(self, intervals: List[List[int]], toBeRemoved: List[int]) -> List[List[int]]: res = [] for s, e in sorted(intervals): # Situation 1: no overlaps if e < toBeRemoved[0] or s > toBeRemoved[1]: res.append([s,e]) # Situation 2: s-e in toBeRemoved # Situation 3: e in [toBeRemoved] # Situation 4: s in [toBeRemoved] else: if s < toBeRemoved[0]: res.append([s, toBeRemoved[0]]) if e > toBeRemoved[1]: res.append([toBeRemoved[1], e]) return res ------------------------------------------------------------------------ class Solution: def removeInterval(self, intervals: List[List[int]], toBeRemoved: List[int]) -> List[List[int]]: start = self.bsearchLeft(intervals,toBeRemoved[0]) last = self.bsearchRight(intervals,toBeRemoved[1]) if start > last: return intervals if start == last: intv = [] low, high = toBeRemoved curL, curH = intervals[start] if curL < low: intv.append([curL,low]) if high < curH: intv.append([high,curH]) return intervals[:start] + intv + intervals[start+1:] intervals[start][1] = toBeRemoved[0] intervals[last][0] = toBeRemoved[1] if intervals[start][0] >= intervals[start][1]: start -= 1 if intervals[last][0] >= intervals[last][1]: last += 1 return intervals[:start+1] + intervals[last:] def bsearchLeft(self, intervals, beg): l, r = 0, len(intervals)-1 while l <= r: m = int((l+r)/2) if intervals[m][1] > beg: r = m - 1 else: l = m + 1 return l def bsearchRight(self, intervals, last): l, r = 0, len(intervals)-1 while l <= r: m = int((l+r)/2) if intervals[m][0] > last: r = m - 1 else: l = m + 1 return r ---------------------------------------------- class Solution: def removeInterval(self, intervals: List[List[int]], toBeRemoved: List[int]) -> List[List[int]]: output = [] for interval in intervals: if interval[1] <= toBeRemoved[0] or interval[0] >= toBeRemoved[1]: output.append(interval) elif interval[1] > toBeRemoved[1] and interval[0] < toBeRemoved[0]: output.append([interval[0],toBeRemoved[0]]) output.append([toBeRemoved[1],interval[1]]) elif interval[1] > toBeRemoved[0] and interval[0] < toBeRemoved[0] : output.append([interval[0],toBeRemoved[0]]) elif interval[0] < toBeRemoved[1] and interval[1] > toBeRemoved[1] : output.append([toBeRemoved[1],interval[1]]) return output
''' You have a cubic storeroom where the width, length, and height of the room are all equal to n units. You are asked to place n boxes in this room where each box is a cube of unit side length. There are however some rules to placing the boxes: You can place the boxes anywhere on the floor. If box x is placed on top of the box y, then each side of the four vertical sides of the box y must either be adjacent to another box or to a wall. Given an integer n, return the minimum possible number of boxes touching the floor. ''' class Solution: def minimumBoxes(self, n: int) -> int: boxesPlaced = 0 maxFloor = 1 boxesOnFloor = 0 while boxesPlaced < n: for i in range(1, maxFloor + 1): boxesPlaced += i boxesOnFloor += 1 if boxesPlaced >= n: break maxFloor += 1 return boxesOnFloor
''' Given two integers a and b, return the sum of the two integers without using the operators + and -. ''' class Solution: def getSum(self, a: int, b: int) -> int: # 32 bit mask in hexadecimal mask = 0xffffffff # works both as while loop and single value check while (b & mask) > 0: carry = ( a & b ) << 1 a = (a ^ b) b = carry # handles overflow return (a & mask) if b > 0 else a -------------------------- def getSum(a, b): if b == 0: return a return getSum(a ^ b, (a & b) << 1) --------------------------------------------------- class Solution: def getSum(self, a: int, b: int) -> int: ## RC ## ## APPROACH : BITWISE OPERATIONS ## ## LOGIC ## # 1. For any two numbers, if their binary representations are completely opposite, then XOR operation will directly produce sum of numbers ( in this case carry is 0 ) # 2. what if the numbers binary representation is not completely opposite, XOR will only have part of the sum and remaining will be carry, which can be produced by and operation followed by left shift operation. # 3. For Example 18, 13 => 10010, 01101 => XOR => 11101 => 31 (ans found), and operation => carry => 0 # 4. For Example 7, 5 # 1 1 1 1 1 1 # 1 0 1 1 0 1 # ----- ----- # 0 1 0 => XOR => 2 1 0 1 => carry => after left shift => 1 0 1 0 # 2 10 # now we have to find sum of 2, 10 i.e a is replace with XOR result and b is replaced wth carry result # similarly repeating this process till carry is 0 # steps will be 7|5 => 2|10 => 8|4 => 12|0 ## TIME COMPLEXITY : O(1) ## ## SPACE COMPLEXITY : O(1) ## # 32 bit mask in hexadecimal mask = 0xffffffff # (python default int size is not 32bit, it is very large number, so to prevent overflow and stop running into infinite loop, we use 32bit mask to limit int size to 32bit ) while(b & mask > 0): carry = (a & b) << 1 a = a ^ b b = carry return (a & mask) if b > 0 else a --------------------------------------------------------------------- There's lot of answers here, but none of them shows how they arrived at the answer, here's my simple try to explain. Eg: Let's try this with our hand 3 + 2 = 5 , the carry will be with in the brackets i.e "()" 3 => 011 2=> 010 ____ 1(1)01 Here we will forward the carry at the second bit to get the result. So which bitwise operator can do this ? A simple observation says that XOR can do that,but it just falls short in dealing with the carry properly, but correctly adds when there is no need to deal with carry. For Eg: 1 => 001 2 => 010 1^2 => 011 (2+1 = 3) So now when we have carry, to deal with, we can see the result as : 3 => 011 2 => 010 3^2=> 001 Here we can see XOR just fell short with the carry generated at the second bit. So how can we find the carry ? The carry is generated when both the bits are set, i.e (1,1) will generate carry but (0,1 or 1,0 or 0,0) won't generate a carry, so which bitwise operator can do that ? AND gate ofcourse. To find the carry we can do 3 => 011 2 => 010 3&2 => 010 now we need to add it to the previous value we generated i.e ( 3 ^ 2), but the carry should be added to the left bit of the one which genereated it. so we left shift it by one so that it gets added at the right spot. Hence (3&2)<<1 => 100 so we can now do 3 ^2 => 001 (3&2)<<1 => 100 Now xor them, which will give 101(5) , we can continue this until the carry becomes zero. A Java program which implements the above logic : class Solution { public int getSum(int a, int b) { int c; while(b !=0 ) { c = (a&b); a = a ^ b; b = (c)<<1; } return a; } }
''' You are given the root of a binary search tree and an array queries of size n consisting of positive integers. Find a 2D array answer of size n where answer[i] = [mini, maxi]: mini is the largest value in the tree that is smaller than or equal to queries[i]. If a such value does not exist, add -1 instead. maxi is the smallest value in the tree that is greater than or equal to queries[i]. If a such value does not exist, add -1 instead. Return the array answer. ''' class Solution: def closestNodes(self, root: Optional[TreeNode], queries: List[int]) -> List[List[int]]: # Input: root = [6,2,13,1,4,9,15,null,null,null,null,null,null,14], queries = [2,5,16] # Output: [[2,2],[4,6],[15,-1]] values = [] def dfs(root): if not root: return dfs(root.left) values.append(root.val) dfs(root.right) dfs(root) n = len(values) res = [] for q in queries: tmp = [] l, r = 0 , n-1 while l < r: mid = r - (r-l)//2 if values[mid] > q: r = mid-1 else: l = mid tmp.append(values[l] if values[l] <= q else -1) l, r = 0 , n-1 while l < r: mid = l + (r-l)//2 if values[mid] < q: l = mid+1 else: r = mid tmp.append(values[l] if values[l] >= q else -1) res.append(tmp) return res
''' You are given a 0-indexed integer array nums. The concatenation of two numbers is the number formed by concatenating their numerals. For example, the concatenation of 15, 49 is 1549. The concatenation value of nums is initially equal to 0. Perform this operation until nums becomes empty: If there exists more than one number in nums, pick the first element and last element in nums respectively and add the value of their concatenation to the concatenation value of nums, then delete the first and last element from nums. If one element exists, add its value to the concatenation value of nums, then delete it. Return the concatenation value of the nums. ''' class Solution: def findTheArrayConcVal(self, nums: List[int]) -> int: n = len(nums) ans = 0 for i in range((n+1)//2): if i == n-1-i: ans += nums[i] else: ans += int(str(nums[i]) + str(nums[n-1-i])) return ans ------------------------------------------------------------------ class Solution: def findTheArrayConcVal(self, nums: List[int]) -> int: i=0 j=len(nums)-1 result=0 while(i<=j): if i!=j : result+=int(str(nums[i])+str(nums[j])) else: result+=nums[i] i=i+1 j=j-1 return result
''' You are given a 0-indexed permutation of n integers nums. A permutation is called semi-ordered if the first number equals 1 and the last number equals n. You can perform the below operation as many times as you want until you make nums a semi-ordered permutation: Pick two adjacent elements in nums, then swap them. Return the minimum number of operations to make nums a semi-ordered permutation. A permutation is a sequence of integers from 1 to n of length n containing each number exactly once. ''' class Solution: def semiOrderedPermutation(self, nums: List[int]) -> int: x = nums.index(1) y = nums.index(max(nums)) n = len(nums) if x < y : return x + (n-y-1) else: return x + (n-y-1)-1 -------------------------------------------------------------------------------------------- class Solution: def semiOrderedPermutation(self, nums: List[int]) -> int: if nums[0] == 1 and nums[len(nums) - 1] == len(nums): return 0 op = 0 min_idx = nums.index(min(nums)) max_idx = nums.index(max(nums)) if min_idx < max_idx: op = min_idx + (len(nums) - 1 - max_idx) if min_idx > max_idx: op = min_idx + (len(nums) - 1 - max_idx) - 1 return op
''' Given an integer n, count the total number of digit 1 appearing in all non-negative integers less than or equal to n. ''' def countDigitOne(self, n): if n <= 0: return 0 q, x, ans = n, 1, 0 while q > 0: digit = q % 10 q /= 10 ans += q * x if digit == 1: ans += n % x + 1 elif digit > 1: ans += x x *= 10 return ans ----------------------------------------------------------- class Solution: def countDigitOne(self, n: int) -> int: if n<1: return 0 digits=len(str(n)) dp=[0]*digits for i in range(1, len(dp)): dp[i]=10**(i-1) + 10*dp[i-1] ans=0 for i in range(digits): lead,n=divmod(n,10**(digits-i-1)) if 2>lead>=1: ans+=dp[digits-i-1]+n+1 elif lead>=2: ans+=lead*dp[digits-i-1]+10**(digits-i-1) return ans
''' A password is considered strong if the below conditions are all met: It has at least 6 characters and at most 20 characters. It contains at least one lowercase letter, at least one uppercase letter, and at least one digit. It does not contain three repeating characters in a row (i.e., "...aaa..." is weak, but "...aa...a..." is strong, assuming other conditions are met). Given a string password, return the minimum number of steps required to make password strong. if password is already strong, return 0. In one step, you can: Insert one character to password, Delete one character from password, or Replace one character of password with another character. ''' import itertools class Solution: lowercase = set('abcdefghijklmnopqrstuvwxyz') uppercase = set('ABCDEFGHIJKLMNOPQRSTUFVWXYZ') digit = set('0123456789') def strongPasswordChecker(self, s: str) -> int: characters = set(s) # Check rule (2) needs_lowercase = not (characters & self.lowercase) needs_uppercase = not (characters & self.uppercase) needs_digit = not (characters & self.digit) num_required_type_replaces = int(needs_lowercase + needs_uppercase + needs_digit) # Check rule (1) num_required_inserts = max(0, 6 - len(s)) num_required_deletes = max(0, len(s) - 20) # Check rule (3) # Convert s to a list of repetitions for us to manipulate # For s = '11aaabB' we have groups = [2, 3, 1, 1] groups = [len(list(grp)) for _, grp in itertools.groupby(s)] # We apply deletions iteratively and always choose the best one. # This should be fine for short passwords :) # A delete is better the closer it gets us to removing a group of three. # Thus, a group needs to be (a) larger than 3 and (b) minimal wrt modulo 3. def apply_best_delete(): argmin, _ = min( enumerate(groups), # Ignore groups of length < 3 as long as others are available. key=lambda it: it[1] % 3 if it[1] >= 3 else 10 - it[1], ) groups[argmin] -= 1 for _ in range(num_required_deletes): apply_best_delete() # On the finished groups, we need one repace per 3 consecutive letters. num_required_group_replaces = sum( group // 3 for group in groups ) return ( # Deletes need to be done anyway num_required_deletes # Type replaces can be eaten up by inserts or group replaces. # Note that because of the interplay of rules (1) and (2), the required number of group replaces # can never be greater than the number of type replaces and inserts for candidates of length < 6. + max( num_required_type_replaces, num_required_group_replaces, num_required_inserts, ) ) ------------------------------------------------------------------------------------------------------------------------------- class Solution(object): def strongPasswordChecker(self, s): """ :type s: str :rtype: int """ missing_type = 3 if any('a' <= c <= 'z' for c in s): missing_type -= 1 if any('A' <= c <= 'Z' for c in s): missing_type -= 1 if any(c.isdigit() for c in s): missing_type -= 1 change = 0 one = two = 0 p = 2 while p < len(s): if s[p] == s[p-1] == s[p-2]: length = 2 while p < len(s) and s[p] == s[p-1]: length += 1 p += 1 change += length / 3 if length % 3 == 0: one += 1 elif length % 3 == 1: two += 1 else: p += 1 if len(s) < 6: return max(missing_type, 6 - len(s)) elif len(s) <= 20: return max(missing_type, change) else: delete = len(s) - 20 change -= min(delete, one) change -= min(max(delete - one, 0), two * 2) / 2 change -= max(delete - one - 2 * two, 0) / 3 return delete + max(missing_type, change)
''' Convert a Binary Search Tree to a sorted Circular Doubly-Linked List in place. You can think of the left and right pointers as synonymous to the predecessor and successor pointers in a doubly-linked list. For a circular doubly linked list, the predecessor of the first element is the last element, and the successor of the last element is the first element. We want to do the transformation in place. After the transformation, the left pointer of the tree node should point to its predecessor, and the right pointer should point to its successor. You should return the pointer to the smallest element of the linked list. ''' Just use inorder traversal, which finds the nodes in ascending order, and store the head and previous node in global variables. After the traversal is finished, prev is the "tail" of the double linked list so just connect it to the head. class Solution(object): head = None prev = None def treeToDoublyList(self, root): if not root: return None self.treeToDoublyListHelper(root) self.prev.right = self.head self.head.left = self.prev return self.head def treeToDoublyListHelper(self, node): if not node: return self.treeToDoublyListHelper(node.left) if self.prev: node.left = self.prev self.prev.right = node else: # We are at the head. self.head = node self.prev = node self.treeToDoublyListHelper(node.right) ------------------------------------------------------- Intuition For a binary tree problem, one can often solve it by divide and conquer. That is to say. Try to formulate your solution by focusing on the root node. Assume left subtree is solved, what info do you still need to be returned to you to solve the rest of the problem Assume right subtree is solved, what info do you still need to be returned to to solve the rest of the problem Given the info above, what actions we want to perform to solve the rest of the problem For this problem Assume left subtree is already flattened to a doubly linkedlist, I want the left_head and left_tail. I need the head because root.left is not neccesraily the head anymore after the flattening Assume right subtree is already flattened I want right_head and right_tail for the same reason. Now I have left_head, left_tail, right_head and right_tail, all we need to do is to wire them up. if left_tail: left_tail.right = root root.left = left_tail if right_head: root.right = right_head right_head.left = root Then We return the head and tail of the current tree to continue the recurion. if left_head: result_head = left_head else: result_head = root if right_tail: result_tail = right_tail else: result_tail = root return result_head, result_tail Remember, as human beings. We think about this problem top down but the recursion actually happens bottom up. Solution class Solution(object): def treeToDoublyList(self, root): """ :type root: Node :rtype: Node """ if not root: return head, tail = self.helper(root) head.left = tail tail.right = head return head def helper(self, root): if not root: return None, None left_head, left_tail = self.helper(root.left) right_head, right_tail = self.helper(root.right) if left_tail: left_tail.right = root root.left = left_tail if right_head: root.right = right_head right_head.left = root if left_head: result_head = left_head else: result_head = root if right_tail: result_tail = right_tail else: result_tail = root return result_head, result_tail ------------------------------------------------------ class Solution: def treeToDoublyList(self, root: 'Node') -> 'Node': ## RC ## ## APPROACH : ITERATIVE + STACK ## ## Similar to Leetcode: 94 Binary tree inorder traversal ## ## LOGIC ## ## 1. using pre order traversal, store the prev node and for current node point that prev node and for that prev node point this current node ## ## 2. first when currNode is Node, top of stack is the FirstNode, and as iterating change every next node to LastNode ## ## 3. At last link first and last nodes ## ## TIME COMPLEXITY : O(N) ## ## SPACE COMPLEXITY : O(N) ## if not root: return root if not root.left and not root.right: root.left = root root.right = root return root stack = [] currNode = root prevNode = None firstNode = None lastNode = None while( stack or currNode ): while( currNode ): stack.append( currNode ) currNode = currNode.left node = stack.pop() node.left = prevNode if( prevNode ): prevNode.right = node prevNode = node if( not firstNode ): firstNode = node lastNode = node currNode = node.right # joining first and last numbers firstNode.left = lastNode lastNode.right = firstNode return firstNode ---------------------------------------------- For every node in a BST, the objective is to create 2-way links as follows: predecessor <--> node node <--> successor In a BST: predecessor is max of left subtree (if there is a left subtree) successor is min of right subtree (if there is a right subtree) Algorithm breakdown: recursively return (min, max) found so far at each node, we have l_max (predecessor) and r_min (successor), create the 2-way links with the node itself at the end, we will have the global min and max nodes, connect them separately return global min node The idea of returning (min, max) is useful for other problems. For example, 98. Validate Binary Search Tree. class Solution: def treeToDoublyList(self, root: 'Optional[Node]') -> 'Optional[Node]': def link_in_place(root): if not root: return None, None l_min, l_max = link_in_place(root.left) r_min, r_max = link_in_place(root.right) root.left, root.right = l_max, r_min # predecessor <- node, node -> successor if l_max: l_max.right = root # predecessor -> node if r_min: r_min.left = root # node <- successor return l_min if l_min else root, r_max if r_max else root if not root: return root min_node, max_node = link_in_place(root) min_node.left, max_node.right = max_node, min_node return min_node ------------------------------------------------------- Of course, excluding implicit stack space for recursive approach and explicit stack space for iterative approach. Iterative Approach / In Place : def ite_trav(root): if not root: return root stack = [] prev = cur = head = None while stack or root: while root: stack.append(root) root = root.left root = stack.pop() prev = cur cur = root if not head: head = cur else: prev.right = cur cur.left = prev root = root.right cur.right = head head.left = cur return head return ite_trav(root) Recursive Approach : arr = [] def trav(root): if root: trav(root.left) arr.append(root) trav(root.right) def connect(arr): if len(arr) <= 1: if not arr: return root arr[0].left = arr[0].right = arr[0] return arr[0] for i in range(len(arr)-1): arr[i].right = arr[i+1] arr[i].left = arr[i-1] j = i+1 arr[j].right = arr[-j-1] arr[j].left = arr[j-1] return arr[0] trav(root) return connect(arr)
''' Given a string s consisting of lowercase English letters, return the first letter to appear twice. ''' #my own solution from collections import Counter class Solution: def repeatedCharacter(self, s: str) -> str: d = dict(Counter(s)) n = [] for k, v in d.items(): if v >= 2: n.append([k, v]) mini = float('inf') letter = '' for k, v in n: check = k counter = 0 for i in range(len(s)): if s[i] == check: counter += 1 if counter == 2: if i < mini: mini = i letter = check #mini.append([check, i]) #print(mini, letter) return letter ----------------------------------------------------- class Solution: def repeatedCharacter(self, s: str) -> str: occurences = defaultdict(int) for char in s: occurences[char] += 1 if occurences[char] == 2: return char
''' You are given a license key represented as a string s that consists of only alphanumeric characters and dashes. The string is separated into n + 1 groups by n dashes. You are also given an integer k. We want to reformat the string s such that each group contains exactly k characters, except for the first group, which could be shorter than k but still must contain at least one character. Furthermore, there must be a dash inserted between two groups, and you should convert all lowercase letters to uppercase. Return the reformatted license key. ''' class Solution: def licenseKeyFormatting(self, s: str, k: int) -> str: s = s.replace('-','') s = list(s) for i in range(1,len(s)): if i % k == 0: s[-i] = '-' + s[-i] return (''.join(s)).upper()
''' Given a list of integers nums, find the largest product of two distinct elements. ''' class Solution: def solve(self, nums): nums.sort() case1 = nums[-1] * nums[-2] case2 = nums[0] * nums[1] return max(case1,case2)
''' You are given three integers n, m and k. Consider the following algorithm to find the maximum element of an array of positive integers: You should build the array arr which has the following properties: arr has exactly n integers. 1 <= arr[i] <= m where (0 <= i < n). After applying the mentioned algorithm to arr, the value search_cost is equal to k. Return the number of ways to build the array arr under the mentioned conditions. As the answer may grow large, the answer must be computed modulo 109 + 7. ''' i=index h=max element till index i k=number of searches left class Solution: def numOfArrays(self, n: int, m: int, k: int) -> int: @lru_cache(None) def dp(i,h,k): if i==n and k==0: return 1 if i==n or k<0: return 0 return sum(dp(i+1,max(h,j),k-(j>h)) for j in range(1,m+1))%1000000007 return dp(0,-1,k)
''' You have the task of delivering some boxes from storage to their ports using only one ship. However, this ship has a limit on the number of boxes and the total weight that it can carry. You are given an array boxes, where boxes[i] = [ports​​i​, weighti], and three integers portsCount, maxBoxes, and maxWeight. ports​​i is the port where you need to deliver the ith box and weightsi is the weight of the ith box. portsCount is the number of ports. maxBoxes and maxWeight are the respective box and weight limits of the ship. The boxes need to be delivered in the order they are given. The ship will follow these steps: The ship will take some number of boxes from the boxes queue, not violating the maxBoxes and maxWeight constraints. For each loaded box in order, the ship will make a trip to the port the box needs to be delivered to and deliver it. If the ship is already at the correct port, no trip is needed, and the box can immediately be delivered. The ship then makes a return trip to storage to take more boxes from the queue. The ship must end at storage after all the boxes have been delivered. Return the minimum number of trips the ship needs to make to deliver all boxes to their respective ports. ''' class Solution: def boxDelivering(self, boxes: List[List[int]], portsCount: int, maxBoxes: int, maxWeight: int) -> int: dp = [0] + [inf]*len(boxes) trips = 2 ii = 0 for i in range(len(boxes)): maxWeight -= boxes[i][1] if i and boxes[i-1][0] != boxes[i][0]: trips += 1 while maxBoxes < i - ii + 1 or maxWeight < 0 or ii < i and dp[ii] == dp[ii+1]: maxWeight += boxes[ii][1] if boxes[ii][0] != boxes[ii+1][0]: trips-=1 ii += 1 dp[i+1] = dp[ii] + trips return dp[-1] ----------------------------------------------------------------------------------------------------------------- class Solution: def boxDelivering(self, boxes: List[List[int]], portsCount: int, maxBoxes: int, maxWeight: int) -> int: left = 0 # idx of the box to be delivered first during the next run -> left idx in sliding window ports_on_route = 0 weight_on_ship = 0 dp = [0] for right in range(len(boxes)): while weight_on_ship + boxes[right][1] > maxWeight or right - left == maxBoxes: # ship is full --> deliver boxes until there is enough space for the new box weight_on_ship -= boxes[left][1] ports_on_route -= boxes[left][0] != boxes[left + 1][0] left += 1 while left < right and dp[left] == dp[left + 1]: # if some additional boxes can be delivered for free, deliver them as well # (there can't be a cheaper than free deliveray, plus we clear additional space on the boat) weight_on_ship -= boxes[left][1] ports_on_route -= boxes[left][0] != boxes[left + 1][0] left += 1 # load next box weight_on_ship += boxes[right][1] if right == 0 or boxes[right - 1][0] != boxes[right][0]: ports_on_route += 1 dp.append(dp[left] + ports_on_route + 1) return dp[-1]
''' You are given a binary string s and a positive integer k. Return the length of the longest subsequence of s that makes up a binary number less than or equal to k. Note: The subsequence can contain leading zeroes. The empty string is considered to be equal to 0. A subsequence is a string that can be derived from another string by deleting some or no characters without changing the order of the remaining characters. ''' class Solution: def longestSubsequence(self, s: str, k: int) -> int: nums = '' for i in range(len(s) - 1, -1, -1): # read from right nums = s[i] + nums if int(nums, base = 2) > k: # until it makes larger k # Add all zeros as leading zeros and add the size of the current valid nums return s[:i].count('0') + len(nums) - 1 # we added the digit that makes it > k, - 1 to remove such digit. return len(s)
''' You have n processes forming a rooted tree structure. You are given two integer arrays pid and ppid, where pid[i] is the ID of the ith process and ppid[i] is the ID of the ith process's parent process. Each process has only one parent process but may have multiple children processes. Only one process has ppid[i] = 0, which means this process has no parent process (the root of the tree). When a process is killed, all of its children processes will also be killed. Given an integer kill representing the ID of a process you want to kill, return a list of the IDs of the processes that will be killed. You may return the answer in any order. ''' Suggestions to make it better are always welcomed. Think of it as a tree and now create a dictionary of ppid. Key is ppid and values are the list of its immediate children. Now search through the dictionary in BFS fashion to get all the processes that will be killed. def killProcess(self, pid: List[int], ppid: List[int], kill: int) -> List[int]: mapping = collections.defaultdict(list) for i in range(len(ppid)): mapping[ppid[i]].append(pid[i]) queue = [kill] result = [] while queue: kill = queue.pop(0) result.append(kill) if kill in mapping: queue += mapping[kill] return result ---------------------------------------------- First, create a map from parent process to all of its children. Then either do DFS as below, or BFS and find all the killed processes. def killProcess(self, pid: List[int], ppid: List[int], kill: int) -> List[int]: child_processes = defaultdict(list) for p, pp in zip(pid, ppid): child_processes[pp].append(p) def killp(p): procs = [p] for cp in child_processes[p]: procs += killp(cp) return procs return killp(kill) ---------------------------------------------------- class Solution: def killProcess(self, pid: List[int], ppid: List[int], kill: int) -> List[int]: childrenOf = {} for pos in range(len(pid)): # parent is key childrenOf.setdefault(ppid[pos], []) childrenOf[ppid[pos]].append(pid[pos]) killList = [kill] # root is kill if childrenOf[0] == killList: return pid res = [] while killList: parent = killList.pop() res.append(parent) if parent in childrenOf: for child in childrenOf[parent]: killList.append(child) return res ------------------------------------------------------ class Solution: def killProcess(self, pids: List[int], ppids: List[int], kill: int) -> List[int]: """ find all the children of pid recursively kill them kill pid """ # tree[pid] stores all the children of process pid tree = defaultdict(list) for i, ppid in enumerate(ppids): tree[ppid].append(pids[i]) def killrec(pid): for child in tree[pid]: yield from killrec(child) yield pid return list(killrec(kill)) ---------------------------------------------- def killProcess(self, pid: List[int], ppid: List[int], kill: int) -> List[int]: from collections import defaultdict as dd graph=dd(list) for i in range(len(pid)): graph[ppid[i]].append(pid[i]) res=[kill] def dfs(node): if node not in graph: return res.extend(graph[node]) for child in graph[node]: dfs(child) dfs(kill) return res 1)Create a directional graph with given pid and ppid. 2)Then perform DFS on that graph with starting node as kill node. 3)Keep appending child of graph to resultant list. 4)Return list optained as result. ------------------------------------------------------- class Solution: def killProcess(self, pid: List[int], ppid: List[int], kill: int) -> List[int]: dic=defaultdict(list) for i in range(len(ppid)): dic[ppid[i]].append(pid[i]) ans=[] def dfs(node,flag): if flag: ans.append(node) if node==kill: ans.append(node) for n in dic[node]: dfs(n,True) else: for n in dic[node]: dfs(n,flag) dfs(0,False) return ans
''' Given the root of a binary search tree, return a balanced binary search tree with the same node values. If there is more than one answer, return any of them. A binary search tree is balanced if the depth of the two subtrees of every node never differs by more than 1. ''' # Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def constr(self, left, right, nums): if left > right: return None else: mid = left + (right-left)//2 root = TreeNode(nums[mid]) root.left = self.constr(left, mid-1, nums) root.right = self.constr(mid+1, right, nums) return root def INR(self, root, nums): if root: self.INR(root.left, nums) nums.append(root.val) self.INR(root.right, nums) def balanceBST(self, root: TreeNode) -> TreeNode: nums = [] self.INR(root, nums) nums.sort() a = nums x = self.constr(0, len(a)-1, nums) return x