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....
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(colum...
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 lo...
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...
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) ...
""" 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 ...
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= ...
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_pay...
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 ' ...
# 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...
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") ...
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 ...
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''' ...
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) duplic...
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,"ch...
# 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 ...
""" 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",...
#!/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 le...
""" 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 frequ...
""" 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...
""" 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 ...
""" 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...
""" 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 Hi...
""" 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...
""" 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...
""" 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,...
""" 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...
""" 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)) pri...
""" 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 pa...
""" 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 assume...
""" 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...
""" 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: ...
#!/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._** # # > *...
#!/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 ...
""" 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 ...
""" 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 ...
""" 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 tex...
""" 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...
""" 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...
#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 s...
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__': ...
#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) ')) #u...
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 yo...
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]: ...
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 ...
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...
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('...
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...
# 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 popu...
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...
# 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),...
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': ...
""" 完善你的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...
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}) ...
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 Fa...
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'...
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(...
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...
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.l...
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 =...
#!/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') ...
''' 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 ...
''' 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 relat...
''' 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 ...
''' 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 ...
''' 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): ...
''' 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 '...
''' 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 retu...
''' 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 possibl...
''' 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 a...
''' 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 ...
''' 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 w...
''' 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...
''' 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 tha...
''' 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...
''' 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: ...
''' 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 "......
''' 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...
''' 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(): i...
''' 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, wh...
''' 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,...
''' 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. por...
''' 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 ...
''' 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] =...
''' 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. # cl...