text stringlengths 37 1.41M |
|---|
numberstring = input("please enter comma separated numbers = ")
list1 = list(numberstring.replace(',',''))
tuple1 = tuple(numberstring.replace(',',''))
print(list1)
print(tuple1) |
import matplotlib.pyplot as plt
x = range(1,50)
y = [value * 3 for value in x]
print("Values of X:")
print(*range(1,50))
print("Values of Y (thrice of X):")
print(y)
plt.plot(x,y)
plt.title('X and Y line')
plt.show()
|
# Родительский класс
class Car:
def __init__(self, speed, color, name, is_police=False):
self.speed = int(speed)
self.color = color
self. name = name
self.is_police = is_police
def go(self):
print('Машина поехала.')
def stop(self):
print ('Машина остановилас... |
import linked_list2 as ll2
import timeit
# start time
start = timeit.default_timer()
linkedList = ll2.LinkedList()
for x in range(1,1000):
linkedList.insertLast2("Agam")
#print("inserting at", x)
# stop time
stop = timeit.default_timer()
print('insertLast2 Time: ', stop - start)
# start time
start = timeit.... |
# set -> it contains unique elements only i.e. no duplicacy allowed
jwel_set = {"bangles","earing","sandles"}
print(jwel_set)
jwel_set.add("watch")
# set can have all items of same datatype or may be different - different datatype items
basket = {"Apple","Banana",20, 10.5}
print(basket)
for item in jwel_set:
print... |
class Node:
def __init__(self,data):
self.data = data
self.link = None
class LinkedList:
def __init__(self):
self.head = None
self.tail = None
# high time complexity O(n)
def insertLast(self, data):
# for first element
if (self.head == None):
self.head = Node(data)
return
node = self.head
... |
# polymorphism
# Poly -> many , morphism -> forms
# means many forms
"""
What is Polymorphism : The word polymorphism means having many forms.
In programming, polymorphism means same function name (but different signatures) being uses for different types.
"""
# Python program to demonstrate in-built poly-
# morphi... |
import linked_list_practice2 as ll3
linkedList = ll3.LinkedList()
linkedList.insertLast2("Agam")
linkedList.insertLast2("preet")
linkedList.insertLast2("singh")
linkedList.insertLast2("go")
linkedList.insertLast2("for")
linkedList.insertLast2("it")
linkedList.read()
print(linkedList.delete("Agam"))
linkedList.rea... |
# boolean -> True or False
flag = True
print(flag)
flag = False
print(flag)
c = 10 + 50 # return int
flag = 10 < 50 # return boolean
print(flag)
print(10>50)
print(10==50)
print(10<50)
print(10<=50)
print(10>=50)
print(10<10)
print(10>10)
print(10<=10)
print(10>=10)
print(10==10) # == is equality operator
print(... |
# file handling deals with files e.g.: Image file, text file, video file, pdf file etc i.e any type of file
# so how it works?
# to Access a file you need to open it first
# to do so we have a function 'open(param1, param2)' with 2 param
# param 1 -> name of file / file name with relative/absolute location
# param 2 -... |
list = input().split('-')
for element in list:
print(element[0], end='')
|
cnt = 0
for i in range(int(input())):
word = input()
cnt += list(word) == sorted(word, key=word.find)
print(sorted(word, key=word.find))
print(cnt)
|
n = int(input())
result = n
for i in range(n):
word = input()
for j in range(1, len(word)):
if(word.find(word[j-1]) > word.find(word[j])):
result -= 1
break
print(result)
|
print(len("hello world"))
#finding a particular character in a string
print("hello"[1])
#Dot notation-object.method
print("hello".upper())
print("hello".lower())
print("hello".capitalize())
print("hello".count("l"))
print("hello".find("l"))
print("hello".replace("hello","HELLO"))
print("hello".strip("h"))
|
from collections import deque
# bfs function
def bfs_shortest_path(graph, start, goal):
# keep track of explored nodes
explored = []
# keep track of all the paths to be checked
queue = deque([[start]])
# return path if start is goal
if start == goal:
return [start]
# keeps looping until all poss... |
#
# @lc app=leetcode id=234 lang=python3
#
# [234] Palindrome Linked List
#
# @lc code=start
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def isPalindrome(self, head: ListNode) -> bool:
... |
__author__ = 'Meghan'
import matplotlib.pyplot as plt
import numpy as np
from matplotlib import animation
import copy
f = open('input.txt', 'r')
inp = f.read()
f.close()
def blankgrid(n, m): # n is number of rows, m is number of columns, from day 6
grid = [[0 for j in range(m)] for i in range(n)]
return gri... |
# Given a string of even length, return the first half. So the string "WooHoo"
# yields "Woo".
# first_half('WooHoo') --> 'Woo'
# first_half('HelloThere') --> 'Hello'
# first_half('abcdef') --> 'abc'
def first_half(str):
return str[:len(str) / 2]
print(first_half('WooHoo'))
print(first_half('HelloThere'))
print(f... |
# Given three ints, a b c, return True if one of b or c is "close" (differing
# from a by at most 1), while the other is "far", differing from both other
# values by 2 or more. Note: abs(num) computes the absolute value of a number.
# close_far(1, 2, 10) --> True
# close_far(1, 2, 3) --> False
# close_far(4, 1, 3) --... |
# Given a string, we'll say that the front is the first 3 chars of the string.
# If the string length is less than 3, the front is whatever is there. Return
# a new string which is 3 copies of the front.
front3('Java') --> 'JavJavJav'
front3('Chocolate') --> 'ChoChoCho'
front3('abc') --> 'abcabcabc'
def front3(str):... |
# Given a non-negative number "num", return True if num is within 2 of a
# multiple of 10. Note: (a % b) is the remainder of dividing a by b, so (7 % 5)
# is 2. See also: Introduction to Mod
# near_ten(12) --> True
# near_ten(17) --> False
# near_ten(19) --> True
def near_ten(num):
return (abs(num % 10 - 10) <= 2 ... |
# The number 6 is a truly great number. Given two int values, a and b, return
# True if either one is 6. Or if their sum or difference is 6.
# love6(6, 4) --> True
# love6(4, 5) --> False
# love6(1, 5) --> True
def love6(a, b):
return (a == 6 or b == 6 or (abs(a-b) == 6) or (a+b == 6))
print(love6(6, 4))
print(lo... |
# You and your date are trying to get a table at a restaurant. The parameter
# "you" is the stylishness of your clothes, in the range 0..10, and "date" is
# the stylishness of your date's clothes. The result getting the table is
# encoded as an int value with 0=no, 1=maybe, 2=yes. If either of you is very
# stylish, 8 ... |
# Return True if the string "cat" and "dog" appear the same number of times
# in the given string.
# cat_dog('catdog') --> True
# cat_dog('catcat') --> False
# cat_dog('1cat1cadodog') --> True
def cat_dog(str):
return (str.count("cat") == str.count("dog"))
print(cat_dog('catdog'))
print(cat_dog('catcat'))
print... |
import turtle
num_pts = 5 #number sides to your drawing!
for i in range (num_pts):
turtle.left(360/num_pts)
turtle.forward(100)
print(num_pts)
turtle.mainloop()
|
interest_rate_pa = 279.83
def calculate_interest_per_month():
loan_amount = int(input("Kolik si chces pujcit penez?"))
interest_per_month = loan_amount / 100 * interest_rate_pa / 12
return interest_per_month
def calculate_month_payment(interest_per_month):
month_payment = (loan_amount/12) + in... |
"""
To modify this program, please head to the ConsoleCommmands module for instructions.
Things that you may modify in this module:
- Initial print in start()
- environmentPrompt()
Minimum files needed for the Console API:
- Console.py
- ConsoleCommands.py
- Exceptions.py
- ExitCmd.py
- Help... |
import time
print(time.gmtime(0)) # 0 is default oldest date
# time.struct_time(tm_year=1970,
# tm_mon=1, tm_mday=1, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=3, tm_yday=1, tm_isdst=0)
print(time.localtime()) # no arguments passed thus it takes today's date
# time.struct_time(tm_year=2020,
# tm_mon=10, tm_mday=20, tm_... |
if __name__ == '__main__':
a = int(input())
b = int(input())
add = str(a + b)
sub = str(a - b)
mul = str(a * b)
print(add + "\n" + sub + "\n" + mul)
|
#!/bin/python3
import math
import os
import random
import re
import sys
# Complete the climbingLeaderboard function below.
def climbingLeaderboard(scores, alice):
distinct_scores = list(set(scores))
distinct_scores.sort()
ret = []
i = 0
for alice_score in alice:
if alice_score >= distinct_... |
if __name__ == '__main__':
n = int(input())
for num in range(n):
print (str(num * num))
|
#!/bin/python3
import math
import os
import random
import re
import sys
# Complete the utopianTree function below.
def utopianTree(n):
height = 1
i = 0
while i <= n:
if i > 0:
if i % 2 != 0:
height *= 2
else:
height += 1
i += 1
... |
def print_formatted(number):
output = ""
fmt = len(format(number, 'b'))
for i in range(number):
num = i + 1
dec = str(num)
octa = format(num, 'o')
hexa = format(num, 'x').upper()
bina = format(num, 'b')
output = output + dec.rjust(fmt) + " " + octa.rjust(fmt) + " " + he... |
n = int(input())
sum = 0
for i in range(1, n-1):
if i % 3 and i % 5:
sum+=1
print(sum) |
# CUAL ES LA SALIDA
side = int(input("Ingrese un valor entero:"))
for x in list(range(side)) + list(reversed(range(side-1))):
print('{: <{w1}}{:*<{w2}}'.format('', '', w1=side-x-1, w2=x*2+1))
|
import time
def test(n):
lst = []
print time.strftime('%H:%M:%S')
#for i in range(10000*n):
# lst = lst + [i]
# # lst.append(i)
lst = list(range(10000*n))
# lst = [i for i in range(10000*n)]
print time.strftime('%H:%M:%S')
print lst[:30]
# return lst
# return list(rann... |
from trees.node import Node
from typing import List
from collections import deque
def depth_first_in_order(root: Node) -> List:
res = []
def recurse(node):
if node is not None:
recurse(node.left)
res.append(node.data)
recurse(node.right)
recurse(root)
retu... |
import unittest
from graphs.dijkstra import find_shortest_path
class TestDjikstra(unittest.TestCase):
empty_graph = {}
graph = {
'A': [('B', 2), ('C', 1), ('D', 3)],
'B': [('A', 2), ('G', 3), ('H', 2), ('I', 4)],
'C': [('A', 1), ('D', 2), ('I', 2)],
'D': [('A', 3), ('C', 2), (... |
from typing import List, Set, Dict, Tuple, Optional
from math import inf
def find_shortest_path(graph: Dict[str, List[Tuple[str, int]]], start: str, target: str):
if start == target:
return [start]
vertices: List[str] = list(graph.keys())
if not vertices or start not in vertices or target not in v... |
import unittest
from strings.calculate_expression import calculate
class TestCalculateExpression(unittest.TestCase):
def test_empty_string(self):
self.assertEqual(calculate(""), 0)
def test_simple_expression(self):
self.assertEqual(calculate("1+2+3"), 6)
def test_long_expression(self):
... |
from .abstract_algorithm import AbstractAlgorithm
class OddOccurrences(AbstractAlgorithm):
def solution(self, A, debug):
element_set = set()
print(A)
for e in A:
if e in element_set:
element_set.discard(e)
else:
element_set.add(e)
... |
import unittest
from src.model.customer import Customer
from src.model.product import Product
from src.model.shoppingcart import ShoppingCart
CUSTOMER = Customer("test")
PRICE = 100
PRODUCT = "T"
class ShoppingCartTest(unittest.TestCase):
def test_should_calculate_price_with_no_discount(self):
products ... |
#program for factorial
n=eval(input("Enter The No"))
fac=1
for i in range(1,n+1):
fac=fac*i
print("factorial is",fac)
|
#global variables
#board
board=[" "," "," ",
" "," "," ",
" "," "," "]
# is game over or not
game_not_over=True
winner=[None]
#display board
def display_board():
print("-|1|--|2|--|3|-")
print("[ "+board[0]+" ][ "+board[1]+" ][ "+board[2]+" ]")
print("-|4|--|5|--|6|-")
print("[ " + board[... |
def get_sum(a , b):
return a+b
my_sum = get_sum(10,4)
print(my_sum)
def get_sum2 (a, b, c):
return a+b+c
my_sum2 = get_sum2(7.8,3.1, 2.2)
print(my_sum2)
def my_function (var_1, var_2):
print(var_1)
print(var_2)
my_function(3,"abc")
def my_function2 (var_1, var_2, var_3):
print(var_1)
pr... |
#通过列表生成式,我们可以直接创建一个列表。但是,受到内存限制,列表容量肯定是有限的。
#所以,如果列表元素可以按照某种算法推算出来,那我们是否可以在循环的过程中不断推算出后续的元素呢?这样就不必创建完整的list,从而节省大量的空间。在Python中,这种一边循环一边计算的机制,称为生成器:generator。
#要创建一个generator,有很多种方法。第一种方法很简单,只要把一个列表生成式的[]改成(),就创建了一个generator:
L=[x*x for x in range(10)]
print(L)
g = (x * x for x in range(10))
print(g)
#创建L和g的区别仅在于最外层的[]... |
# 使用type()
# 首先,我们来判断对象类型,使用type()函数:
#
# 基本类型都可以用type()判断
print(type(123))
print(type('abc'))
print(abs)
# 判断基本数据类型可以直接写int,str等,但如果要判断一个对象是否是函数怎么办?可以使用types模块中定义的常量:
import types
def fn():
pass
print(type(fn) == types.FunctionType)
print(type(abs) == types.BuiltinFunctionType)
print(type(lambda x: x) == ty... |
# 由于Python是动态语言,根据类创建的实例可以任意绑定属性。
# 给实例绑定属性的方法是通过实例变量,或者通过self变量:
class Student(object):
def __init__(self, name):
self.name = name
s = Student('Bob')
s.score = 90
# 但是,如果Student类本身需要绑定一个属性呢?可以直接在class中定义属性,这种属性是类属性,归Student类所有:
class Student(object):
name = 'Student'
# 当我们定义了一个类属性后,这个属性虽然归类所有,但类的... |
# 命名关键字参数
# 对于关键字参数,函数的调用者可以传入任意不受限制的关键字参数。至于到底传入了哪些,就需要在函数内部通过kw检查。
def person(name, age, **kw):
if 'city' in kw:
# 有city参数
pass
if 'job' in kw:
# 有job参数
pass
print('name:', name, 'age:', age, 'other:', kw)
# 但是调用者仍可以传入不受限制的关键字参数
person('Jack', 24, city='Beijing', addr='Ch... |
#def main():
for row in range(4):
for col in range(7):
if col==0 or col==6 or col==1 or col==5:
#if col==0 or col==6 or (col==1 and row==0) or (col==2 and row==0) or (col==3 and row==0) or (col==4 and row==0) or (col==5 and row==0) or (col==6 and row==0):
print ("*",end="")
else:
print (end=" ")
print ()
#... |
'''
def factorial(number):
result =1
while (number != 1):
result = result * number
number -=1
return result
def recursiveFactorial(number):
if (number)
def main():
num = eval(input("Enter the Number:"))
print(factorial(num))
if __name__=='__main__':
main()
def factorial(number):
fact = -1
if num... |
def verbing(input_str):
if len (input_str)<3:
return input_str
elif input_str[-3:]=='ing':
return input_str[:-3]+'ly'
else
return input_str + 'ing'
def main():
input_str=input("Enter string which is to be verbed")
output_str=verbing (input_str)
print ("ver of {} is {} .format (input_str,output_str))
... |
def row_sum_odd_numbers(n):
odd_numbers = [[-1]]
for i in range(n):
odd = [odd_numbers[-1][-1]+2]
for j in range(i):
odd.append(odd[-1]+2)
odd_numbers.append(odd)
return sum(odd_numbers[n])
# return n ** 3
if __name__ == "__main__":
print(row_sum_odd_numbers... |
# Created a simple loop that checks to see if a number is odd and prints them up to 100.
for i in range(0, 100):
if i % 2 != 0:
print(i)
i += 1 |
def digitstoletters(n):
'''
takes an integer and returns a string that is the name of the number in words
'''
d=dict()
d={0:"Zero",1:"One",2:"Two",3:"Three",4:"Four",5:"Five",6:"Six",7:"Seven",8:"Eight",9:"Nine"}
ans=""
for i in str(n):
ans+=d[int(i)]+" "
return ans
def... |
def permute(lst1,lst2=[],k=0,pos=0):
"""
Supposed to print all possible permuations of lst1
"""
lst2.insert(pos,lst1[k])
if len(lst2)==len(lst1):
print(lst2)
else:
permute(lst1,lst2,k+1,pos)
lst2.remove(lst1[k])
if pos< k:
permute(lst1,lst2,k,pos+1)
... |
def wordsf(file1):
'''
Takes file and displayes no. of words in it
'''
f=open(file1,"r")
lines=f.read()
lines=lines.split()
f.close()
return len(lines)
def main():
n=input("Enter name of file : ")
print(wordsf(n))
if __name__=="__main__":
main() |
def inverse():
try:
num=input('Enter the number: ')
num=float(num)
inverse=1.0/num
except ValueError:
print('ValueError')
except TypeError:
print('TypeError')
except ZeroDivisionError:
print('ZeroDivisionError')
except:
print('Any... |
#!/opt/rh/rh-python36/root/usr/bin/python3
tempCel=float(input("Digite um valor de temperatura em Graus Celsius: "))
tempFah=((tempCel *1.8)+32)
print("A temperatura em Fahrenheit é: ",tempFah)
|
#!/opt/rh/rh-python36/root/usr/bin/python3
raio=float(input('Digite o raio do circulo: ' ))
pi=float(3.141592)
area=float(pi*(raio*raio))
print('A área do círculo é: ')
print(area)
|
# Time Complexity:O(n*2)
# Space complexity: O(1)
# Insertion sort takes maximum time to sort if elements are sorted in reverse order.
# And it takes minimum time (Order of n) when elements are already sorted.
def insertion_sort(nums):
for i in range(len(nums)):
j = i
while j>0 and nums[j-1] > nums[j]:
... |
class Student:
school = " La Masia"
def __init__(self, name, school):
self.name = name
self.school = school
self.marks = []
def average(self): # self takes in the object
try:
return sum(self.marks)/ len(self.marks)
except:
ArithmeticE... |
#Name: Oluwatimi Owoturo
#Student Number: 8606957
#Assignment 3
def runLength_Encode(f1,output):
file1L = f1.read()
f1.close()
same = 0
letter = 0
sameL = []
previous = []
counter2=0
keepT = 1
keepT2 = 1
Encoded = ''
for i in range(len(file1L)-1):
... |
# Update using PDF from Euler Website 28 September
# This works with larger numbers as well!
# Two importan steps:
# 1. sum of all numbers divisible by x or y is equal to
# ( sum of all numbers divisible by x +
# sum of all numbers divisible by x ) -
# sum of all numbers divisible by x * y
# 2. The sum of all multipl... |
"""
Read file into texts and calls.
It's ok if you don't understand how to read files
"""
from collections import defaultdict
import csv
with open('texts.csv', 'r') as f:
reader = csv.reader(f)
texts = list(reader)
with open('calls.csv', 'r') as f:
reader = csv.reader(f)
calls = list(reader)
result =... |
import re
import requests
def get_text():
print("Please provide a word or sentence")
return input()
def parse_text(text):
regex = re.compile("[^a-zA-Z]+")
parsed = regex.sub("", text).lower()
if not parsed:
print("Your text is invalid")
exit(-1)
return parsed
def is_palindrome... |
import sys
import logging
logging.basicConfig(level=logging.DEBUG)
def calculator(operation, number1, number2):
result = ''
if int(operation) == 1:
result = float(number1) + float(number2)
elif int(operation) == 2:
result = float(number1) - float(number2)
elif int(operation) == 3:
result = float(nu... |
#PyPoll Python Challenge
# Dependencies
import os
import csv
# Set the Input datafile path
DataFile = os.path.join("election_data.csv")
# Variable Lists to store data
total_votes = 0
candidate = ""
candidate_votes = {}
votes_percentage = {}
winner_vote_count = 0
winner = ""
# Gets data file
with open(DataFile,'r',... |
import pygame.font
class Scoreboard:
""" A class to report scoring information on the top of the screen """
def __init__(self, screen, constants, stats):
self.screen = screen
self.screen_rect = screen.get_rect()
self.constants = constants
self.stats = stats
... |
from typing import List
class Solution:
@classmethod
def two_sum(cls, nums: List[int], target: int) -> List[int]:
for i, n1 in enumerate(nums):
for j, n2 in enumerate(nums):
if i >= j:
continue
if (nums[i] + nums[j]) == target:
... |
year = int(input("What year is it? "))
if year % 100 == 0 and year % 400 == 0:
print("It's a leap year. February has 29 days this year.")
else:
print("It's not a leap year. February has 28 days this year.")
|
mass = float(input("What's the object's mass? "))
weight = mass * 9.8
if weight > 500:
print("The object is too heavy.")
if weight < 100:
print("The object is too light.")
|
def main():
name = input("What's the name of the file? ")
file = open(name, 'r')
for x in range(5):
line = file.readline()
if line:
print(line)
main()
|
kms = int(input("How many kilometers? "))
miles = kms * 0.6214
print("That's", format(miles, '.2f'), "miles")
|
def main():
def calculate_fat():
fat = int(input("How many grams of fat do you eat per day? "))
fat_calories = fat * 9
print("That's ", fat_calories, " calories", sep="")
def calculate_carbs():
carbs = int(input("How many carbs do you eat per day? "))
carb_calories = ca... |
tuition = 8000
multiplier = 1
print("Year \tTuition")
for x in range(1, 6):
multiplier += 0.03
tuition *= multiplier
print(x, " \t$", format(tuition, '.2f'), sep="")
|
def main():
try:
file = open('numbers.txt', 'r')
total = 0
line = file.readline()
lines = 0
while line != "":
try:
number = int(line)
total += number
lines += 1
except ValueError:
print("T... |
a = int(input("How many Class A tickets were sold? "))
b = int(input("How many Class B tickets were sold? "))
c = int(input("How many Class C tickets were sold? "))
total = (a*20) + (b*15) + (c*10)
print("$", total, " was generated through ticket sales", sep="")
|
def main():
numbers = []
for x in range(20):
number = int(input("Enter a number: "))
numbers.append(number)
lowest = min(numbers)
highest = max(numbers)
total = 0
for y in numbers:
total += y
average = total / 20
print("The lowest number is", lowest)
print("Th... |
def main():
name = input("Enter your name: ")
blurb = input("Describe yourself: ")
file = open("html.txt", "w")
file.write("<html>\n")
file.write("<head>\n")
file.write("</head>\n")
file.write("<body>\n")
file.write(" <center>\n")
file.write(" <h1>" + name + "</h1>\n")
file... |
number = int(input("Enter a number 1 through 7: "))
if number < 1 or number > 7:
print("That's outside of the valid range")
else:
if number == 1:
print("Monday")
if number == 2:
print("Tuesday")
if number == 3:
print("Wednesday")
if number == 4:
print("Thursday")
... |
# -*- coding:utf-8 -*-
__author__ = 'huanghf'
"""
合并 k 个排序链表,返回合并后的排序链表。请分析和描述算法的复杂度。
示例:
输入:
[
1->4->5,
1->3->4,
2->6
]
输出: 1->1->2->3->4->4->5->6
"""
from utils.ListNode import ListNode,List2LN,LN2List,LN2String
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# ... |
# -*- coding:utf-8 -*-
__author__ = 'huanghf'
"""
在二叉树中,根节点位于深度 0 处,每个深度为 k 的节点的子节点位于深度 k+1 处。
如果二叉树的两个节点深度相同,但父节点不同,则它们是一对堂兄弟节点。
我们给出了具有唯一值的二叉树的根节点 root,以及树中两个不同节点的值 x 和 y。
只有与值 x 和 y 对应的节点是堂兄弟节点时,才返回 true。否则,返回 false。
示例 1:
输入:root = [1,2,3,4], x = 4, y = 3
输出:false
示例 2:
输入:root = [1,2,3,null,4,null,5],... |
# -*- coding:utf-8 -*-
"""
给定一个整数数组 nums,其中恰好有两个元素只出现一次,其余所有元素均出现两次。 找出只出现一次的那两个元素。
示例 :
输入: [1,2,1,3,2,5]
输出: [3,5]
注意:
结果输出的顺序并不重要,对于上面的例子, [5, 3] 也是正确答案。
你的算法应该具有线性时间复杂度。你能否仅使用常数空间复杂度来实现?
解题思路:
假设两个数只出现一次的数为 a, b
1. 第一次异或遍历求出 x = a ^ b
2. 找出 x 的最低位的1 (x & -x), 记这个数为y,
可以按这位上为1和0 (y & 1), 将数组可以分为 2 堆, a 和 b就... |
# -*- coding:utf-8 -*-
__author__ = 'huanghf'
"""
给定一个排序数组和一个目标值,在数组中找到目标值,并返回其索引。如果目标值不存在于数组中,返回它将会被按顺序插入的位置。
你可以假设数组中无重复元素。
示例 1:
输入: [1,3,5,6], 5
输出: 2
示例 2:
输入: [1,3,5,6], 2
输出: 1
示例 3:
输入: [1,3,5,6], 7
输出: 4
"""
def searchInsert(nums,target):
L = 0
R = len(nums) - 1
while L<=R:
mid = (... |
# -*- coding:utf-8 -*-
__author__ = 'huanghf'
"""
给你一个由 '('、')' 和小写字母组成的字符串 s。
你需要从字符串中删除最少数目的 '(' 或者 ')' (可以删除任意位置的括号),使得剩下的「括号字符串」有效。
请返回任意一个合法字符串。
有效「括号字符串」应当符合以下 任意一条 要求:
空字符串或只包含小写字母的字符串
可以被写作 AB(A 连接 B)的字符串,其中 A 和 B 都是有效「括号字符串」
可以被写作 (A) 的字符串,其中 A 是一个有效的「括号字符串」
示例 1:
输入:s = "lee(t(c)o)de)"
输出:"lee(t(c)o... |
# -*- coding:utf-8 -*-
__author__ = 'huanghf'
"""
给定一个正整数 num,编写一个函数,如果 num 是一个完全平方数,则返回 True,否则返回 False。
说明:不要使用任何内置的库函数,如 sqrt。
示例 1:
输入:16
输出:True
示例 2:
输入:14
输出:False
"""
class Solution:
def isPerfectSquare(self, num: int) -> bool:
"""
牛顿迭代法:
牛顿逼近法本来就是求方程近似解的,只要这道题目本来就是f(x)=x*x ... |
# -*- coding:utf-8 -*-
"""
给你两个 没有重复元素 的数组nums1 和nums2,其中nums1是nums2的子集。
请你找出 nums1中每个元素在nums2中的下一个比其大的值。
nums1中数字x的下一个更大元素是指x在nums2中对应位置的右边的第一个比x大的元素。如果不存在,对应位置输出 -1 。
示例 1:
输入: nums1 = [4,1,2], nums2 = [1,3,4,2].
输出: [-1,3,-1]
解释:
对于 num1 中的数字 4 ,你无法在第二个数组中找到下一个更大的数字,因此输出 -1 。
对于 num1 中的数字 1 ,第二个数组中数字1右边的下一... |
# -*- coding:utf-8 -*-
__author__ = 'huanghf'
"""
给你一个字符串 text,你需要使用 text 中的字母来拼凑尽可能多的单词 "balloon"(气球)。
字符串 text 中的每个字母最多只能被使用一次。请你返回最多可以拼凑出多少个单词 "balloon"。
示例 1:
输入:text = "nlaebolko"
输出:1
示例 2:
输入:text = "loonbalxballpoon"
输出:2
示例 3:
输入:text = "leetcode"
输出:0
提示:
1 <= text.length <= 10^4
text 全部由小写英文字母组成
"""
c... |
# -*- coding:utf-8 -*-
__author__ = 'huanghf'
"""
给定一个正整数,返回它在 Excel 表中相对应的列名称。
例如,
1 -> A
2 -> B
3 -> C
...
26 -> Z
27 -> AA
28 -> AB
...
示例 1:
输入: 1
输出: "A"
"""
def convertToTitle(n):
key_list = [x for x in range(1, 27)]
value_list = [chr(ord('A') + x) for x in range(0, ... |
# -*- coding:utf-8 -*-
"""
给你一个非递减的 有序 整数数组,已知这个数组中恰好有一个整数,它的出现次数超过数组元素总数的 25%。
请你找到并返回这个整数
示例:
输入:arr = [1,2,2,6,6,6,6,7,10]
输出:6
提示:
1 <= arr.length <= 10^4
0 <= arr[i] <= 10^5
"""
from typing import List
import collections
class Solution:
def findSpecialInteger(self, arr: List[int]) -> int:
c ... |
# -*- coding:utf-8 -*-
"""
给你一个整数数组 arr 。请你将数组中的元素按照其二进制表示中数字 1 的数目升序排序。
如果存在多个数字二进制中 1 的数目相同,则必须将它们按照数值大小升序排列。
请你返回排序后的数组。
示例 1:
输入:arr = [0,1,2,3,4,5,6,7,8]
输出:[0,1,2,4,8,3,5,6,7]
解释:[0] 是唯一一个有 0 个 1 的数。
[1,2,4,8] 都有 1 个 1 。
[3,5,6] 有 2 个 1 。
[7] 有 3 个 1 。
按照 1 的个数排序得到的结果数组为 [0,1,2,4,8,3,5,6,7]
示例 2:
输入:arr = [102... |
# -*- coding:utf-8 -*-
__author__ = 'huanghf'
"""
给定一个二叉搜索树, 找到该树中两个指定节点的最近公共祖先。
百度百科中最近公共祖先的定义为:“对于有根树 T 的两个结点 p、q,最近公共祖先表示为一个结点 x,满足 x 是 p、q 的祖先且 x 的深度尽可能大(一个节点也可以是它自己的祖先)。”
例如,给定如下二叉搜索树: root = [6,2,8,0,4,7,9,null,null,3,5]
示例 1:
输入: root = [6,2,8,0,4,7,9,null,null,3,5], p = 2, q = 8
输出: 6
解释: 节点 2 和节点 ... |
# -*- coding:utf-8 -*-
__author__ = 'huanghf'
"""
给定一个二叉树,原地将它展开为链表。
例如,给定二叉树
1
/ \
2 5
/ \ \
3 4 6
将其展开为:
1
\
2
\
3
\
4
\
5
\
6
"""
from utils.TreeNode import TreeNode, List2TN, TN2List
class Solution:
def flatten(self, root: TreeNode... |
# -*- coding:utf-8 -*-
__author__ = 'huanghf'
"""
给定一个大小为 n 的数组,找到其中的众数。众数是指在数组中出现次数大于 ⌊ n/2 ⌋ 的元素。
你可以假设数组是非空的,并且给定的数组总是存在众数。
示例 1:
输入: [3,2,3]
输出: 3
示例 2:
输入: [2,2,1,1,1,2,2]
输出: 2
"""
class Solution:
def majorityElement(self, nums):
nums.sort()
return nums[len(nums)//2]
def majorit... |
# -*- coding:utf-8 -*-
"""
输入一个整数数组,实现一个函数来调整该数组中数字的顺序,使得所有奇数位于数组的前半部分,所有偶数位于数组的后半部分。
示例:
输入:nums = [1,2,3,4]
输出:[1,3,2,4]
注:[3,1,2,4] 也是正确的答案之一。
提示:
1 <= nums.length <= 50000
1 <= nums[i] <= 10000
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/diao-zheng-shu-zu-shun-xu-shi-qi-shu-wei-yu-ou-shu-qian-mian-lcof... |
# -*- coding:utf-8 -*-
__author__ = 'huanghf'
"""
传送带上的包裹必须在 D 天内从一个港口运送到另一个港口。
传送带上的第 i 个包裹的重量为 weights[i]。每一天,我们都会按给出重量的顺序往传送带上装载包裹。我们装载的重量不会超过船的最大运载重量。
返回能在 D 天内将传送带上的所有包裹送达的船的最低运载能力。
示例 1:
输入:weights = [1,2,3,4,5,6,7,8,9,10], D = 5
输出:15
解释:
船舶最低载重 15 就能够在 5 天内送达所有包裹,如下所示:
第 1 天:1, 2, 3, 4, 5
第 2 天:6, 7
第 3 天:8... |
# -*- coding:utf-8 -*-
__author__ = 'huanghf'
"""
给出数字 N,返回由若干 "0" 和 "1"组成的字符串,该字符串为 N 的负二进制(base -2)表示。
除非字符串就是 "0",否则返回的字符串中不能含有前导零。
示例 1:
输入:2
输出:"110"
解释:(-2) ^ 2 + (-2) ^ 1 = 2
示例 2:
输入:3
输出:"111"
解释:(-2) ^ 2 + (-2) ^ 1 + (-2) ^ 0 = 3
示例 3:
输入:4
输出:"100"
解释:(-2) ^ 2 = 4
for each number, we first conside... |
# -*- coding:utf-8 -*-
"""
链接:https://leetcode-cn.com/problems/minimum-absolute-difference-in-bst
给你一棵所有节点为非负值的二叉搜索树,请你计算树中任意两节点的差的绝对值的最小值。
示例:
输入:
1
\
3
/
2
输出:
1
解释:
最小绝对差为 1,其中 2 和 1 的差的绝对值为 1(或者 2 和 3)。
提示:
树中至少有 2 个节点。
本题与 783 https://leetcode-cn.com/problems/minimum-distance-between-bst-... |
# -*- coding:utf-8 -*-
__author__ = 'huanghf'
"""
给你一个正整数的数组 A(其中的元素不一定完全不同),
请你返回可在 一次交换(交换两数字 A[i] 和 A[j] 的位置)后得到的、按字典序排列小于 A 的最大可能排列。
如果无法这么操作,就请返回原数组。
示例 1:
输入:[3,2,1]
输出:[3,1,2]
解释:
交换 2 和 1
示例 2:
输入:[1,1,5]
输出:[1,1,5]
解释:
这已经是最小排列
示例 3:
输入:[1,9,4,6,7]
输出:[1,7,4,6,9]
解释:
交换 9 和 7
示例 4:
输入:[3,1,1,3]
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.