text
stringlengths
37
1.41M
""" A Python script to illustrate manipulating the data without retrieving the orignal dataset from the web. """ import retrieve_data import reformat_data_lib as reform import csv def main(): old_mtx = [] with open("data/project_data.csv", mode = 'r') as old_file: reader = csv.reader(old_file) ...
word = input('Introduce word: ') letter = input('Introduce letter: ') #esta función cuenta el número de letras que aparece en una palabra def count(word, letter): cuenta = 0 for char in word: if char == letter: cuenta = cuenta + 1 return cuenta print(count(word, letter))
text = open('mbox-short.txt') result = dict() order = list() for line in text: lineLower = line.lower() #print(line) for word in lineLower.split(): for letter in word: if letter >='a' and letter <='z': if letter not in result: result[letter] = 1 ...
# Simple SQL tests for playing with database setups import unittest try: import psycopg2 DBCONN = psycopg2.connect(database='test') except ImportError: import sqlite3 DBCONN = sqlite3.connect(':memory:') class TestSQL(unittest.TestCase): def setUp(self): cursor = DBCONN.cursor() ...
from .piece import Piece, Position class Rook(Piece): # Class of the rook piece init_position = {0: {0: Position(0, 0), 1: Position(7, 0)}, 1: {0: Position(0, 7), 1: Position(7, 7)}} init_moves = [] def __init__(self, color: int, piece_number: int): super().__init__(color...
fruits = ['mango', 'apple', 'grape', 'banana'] def list_manipulation(newItem,new_fruit_loc,action): if(action == 1): if(new_fruit_loc == 'e'): fruits.append(newItem) print(fruits) elif(new_fruit_loc == 'b'): fruits.insert(0,newItem) print(fruits) ...
def check_string(the_txt, a): num_of_occurence = 0 for char in the_txt: if(char == a): num_of_occurence = num_of_occurence + 1 print(num_of_occurence) # print (num_of_occurence) do_the_txt = input("enter text-->") a = input("what text? --> ") check_string(do_the_txt, a) # print (do_the_txt)
# PIANO TILES BOT PYTHON SCRIPT. # AKSHITH KANDIVANAM. # importing the required modules. import pyautogui import time import keyboard ''' This project aimed to automate the Piano Tiles game using the PyAutoGUI module's functions. The main idea is to simply recognize if any of the 4 pixels we took match the RGB colou...
class card: # A class to represent a single card def __init__(self, newSuit, newValue): self.suit = newSuit #Suit self.value = newValue #Value, 9-A self.trump = False self.winPercentage = 0.0 self.color = getColor(self.suit) class kitty: def __init__(self): self.cards = [] def getT...
a=8 if(a<0) print("negative") elif(a>0) print("postive") else print("zero")
def merge(playlist, l, m, r): fh = m - l + 1 lh = r - m L = [0] * (fh) R = [0] * (lh) for i in range(0 , fh): L[i] = playlist[l + i] for j in range(0 , lh): R[j] = playlist[m + 1 + j] i = j = 0 k = l while i < fh and j < lh: #Need something here to get input from module (user) in the form of a #ch...
""" From page 263 Write a program that goes to a photo-sharing site like Flickr or Imgur, searches for a category of photos, and then downloads all the resulting images. You could write a program that works with any photo site that has a search feature. """ import logging import os import requests import sys import ur...
import csv with open('scores.csv', 'r') as scores: reader = csv.reader(scores, delimiter=';') maxt = 0 for row in reader: # Row is a list if int(row[2]) > int(maxt): naam = row[0] datum = row[1] maxt = int(row[2]) print('De hoogste score is: {2} op {1} beh...
import re def password(): print ('Enter a password\n\nThe password must be between 6 and 12 characters.\n') while True: password = input('Password: ... ') if 6 <= len(password) < 12: break print ('The password must be between 6 and 12 characters.\n') password_scores = ...
import datetime import csv with open('inloggers.csv', 'a', newline='') as inloggersCSV: writer = csv.writer(inloggersCSV, delimiter=';') #csv.writer writer.writerow(('naam', 'voorl', 'gbdatum', 'email', 'time')) # Columnnames (one tuple!), optional! while True: naam = input("Wat is je achternaam?...
def convert(celcius): farenheit = (celcius * 1.8) + 32 return farenheit print('{:^5} {:^7}'.format("F", "C")) for celcius in range(-30, 41, 5): farenheit = convert(celcius) print('{:5} {:7}'.format(farenheit, celcius))
import numpy as np from marketdata import get_data class trader(): def __init__(self, name, holding_days, sd, min_deviations, max_deviations): # Name of the bot self.name = name # How many days that it will hang on to self.holding_days = holding_days # How much will the stoc...
""" Stack Data Structure. A B C D D C B A """ class Stack(): def __init__(self): self.items = [] def push(self, item): self.items.append(item) def pop(self): return self.items.pop() def is_empty(self): return self.items == [] def get_stack(self): return...
__author__ = 'Josh' import os import urllib alphabet = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'] vowels = ['a', 'e', 'i', 'o', 'u'] consonants = [x for x in alphabet if x not in vowels] def join_with_spaces(lst): #joins togethe...
import numpy as np ''' ndarray对象的内容可以通过索引或切片来访问和修改,与 Python 中 list 的切片操作一样。 ndarray 数组可以基于 0 - n 的下标进行索引,切片对象可以通过内置的 slice 函数,并设置 start, stop 及 step 参数进行,从原数组中切割出一个新数组。 ''' a = np.arange(10) print(a) s = slice(2, 7, 2) # 从索引 2 开始到索引 7 停止,间隔为2 print(a[s]) # 通过冒号分隔切片参数 start:stop:step 来进行切片操作 print(a[2:7:2]) print...
''' 迭代是访问集合元素的一种方式,迭代器是一个可以记住,迭代器是一个可以记住遍历位置的男人。迭代器对象从集合的第一个元素开始访问,直到所有的要素被访问结束。 特点: 迭代器只能往前不会后退。 可以被next()函数调用并不断返回下一个值的对象成为迭代器:Iterable 可迭代的是不是迭代器??? list是可迭代的,俺不是迭代器 借助函数iter(),参数为可迭代对象 生成器与迭代器 生成器是迭代器的子集,迭代器还包括元组,集合,列表,字典,字符串等可迭代对象,这些对象借助iter()函数的转换,可以变成迭代器 ''' # 可迭代对象:1.生成器 2.元组,列表,集合,字典, 字符串 # 如何判断一个对象的是否可迭...
import numpy as np ''' 种类 速度 最坏情况 工作空间 稳定性 'quicksort'(快速排序) 1 O(n^2) 0 否 'mergesort'(归并排序) 2 O(n*log(n)) ~n/2 是 'heapsort'(堆排序) 3 O(n*log(n)) 0 否 ''' ''' numpy.sort() numpy.sort() 函数返回输入数组的排序副本。函数格式如下: numpy.sort(a, axis, kind, order) 参数说明: a: 要排序的数组 axis: 沿着它排序数组的轴,如果没有数组会被展开,...
# 递归的次数是入口决定的,防止死循环的关键在于是否规划好“何时退出循环” print("\n") print("demo1") def sum(x): if x == 0: return 0 else: return x+sum(x-1) print(sum(10)) print("\n") print("demo2") def sum1(n): if n > 100: return 0 else: return n + sum1(n+1) print(sum1(1))
# Create a list and just append whatever you want to it! positive_sayings = list() positive_sayings.append("You are a unique child of this world.") positive_sayings.append("You have as much brightness to offer the world as the next person.") positive_sayings.append("You matter and what you have to this world also...
def get_default_wheel_list(): result = [] for i in range(3): result.append(get_default_wheel()) return result class Wheel(object): def __init__(self, vector_from_robot_center, wheel_spin=0, linear_velocity): pass
#!/usr/bin/env python import time start_time = time.time() calc = time.time() end_time = time.time() print (end_time - start_time)/2.0 start_time = time.clock() calc = time.clock() end_time = time.clock() print (end_time - start_time)/2.0
class Musician(object): def __init__(self, sounds): self.sounds = sounds def solo(self, length): for i in range(length): print(self.sounds[i % len(self.sounds)]) # The Musician class is the parent of the Bassist class class Bassist(Musician): def __init__(self): ...
import numpy as np def sigmoid(x): # f(x) = 1 / (1 + e^(-x)) دالة السيجمويد return 1 / (1 + np.exp(-x)) def deriv_sigmoid(x): # f'(x) = f(x) * (1 - f(x)) : مشتقة السيجمويد fx = sigmoid(x) return fx * (1 - fx) def mse_loss(y_true, y_pred): # بنفس الطول arrays عبارة عن y_true و y_pred return ((y_true ...
print("Q.1- Take 10 integers from user and print it on screen.") for i in range(1,6): x=input("enter a no") print(x) print("Q.3- Create a list of integer elements by user input. Make a new list which will store square of elements of previous list.") a={} for i in range(1,4): a[i]=int(input("enter a...
#Create a list with user defined inputs mylist=[input("enter first no"),input("emter second no")] print(mylist) #2.Add the following list to above created list: #[‘google’,’apple’,’facebook’,’microsoft’,’tesla’] mylist2=["google","apple","facebook","microsoft","tesla"] mylist.extend(mylist2) print(mylist) ...
from pyquery import PyQuery as pq from lxml import etree import urllib #Acceso al html #d = pq("<html></html>") #d = pq(etree.fromstring("<html></html>")) d = pq(url='http://www.mambiente.munimadrid.es/opencms/opencms/calaire/consulta/Gases_y_particulas/informegaseshorarios.html?__locale=es') #d = pq(url='http://goog...
class Person: def __init__(self, name, age, sex): self.name = name self.age = age self.sex = sex def print_info(self): print('姓名:', self.name, '年龄:', self.age, '性别', self.sex) class Student(Person): def __init__(self, name, age, sex, stuNo): Person.__init__(self, n...
title=''' 6.编写程序,输入一个字符,判断该字符是大写字母、小写字母,数字还是其他字符,并作相应的显示。 提示:利用ord()函数来获得字符的ASCII。 ''' def distinguish(c: chr): c_ascii = ord(c) if c_ascii >= 48 and c_ascii <= 57: print('该字符为数字') elif c_ascii >= 65 and c_ascii <= 90: print('该字符为大写字母') elif c_ascii >= 97 and c_ascii <= 122: pri...
""" 文法: E->E+T | T T->T*F | F F->(E)|i 消除左递归: E->TH H->+TH|e(e替代空) T->FY Y->*FY|e F->(E)|i """ # 手动构造预测分析表 dists = { ('E', 'i'): 'TH', ('E', '('): 'TH', ('H', '+'): '+TH', ('H', ')'): 'e', ('H', '#'): 'e', ('T', 'i'): 'FY', ('T', '('): 'F...
class Person: def __init__(self, name, age, sex): self.name = name self.age = age self.sex = sex def print_info(self): print('姓名:', self.name, '年龄:', self.age, '性别', self.sex) p = Person('cuppar', 22, '男') p.print_info()
import math title=''' 3.编写程序,输入球体半径,计算出球的体积和表面积,并输出结果。 提示:球体表面积计算公式为 S=4πR²,球体体积计算公式为 V=(4/3)πR³。 ''' print(title) r=float(input("please input the ball's radius:")) s=4*math.pi*r**2 v=(4/3)*math.pi**3 print("This ball's surface is: ", s) print("This ball's valume is: ", v)
name = "Mike" user_name = input("Please enter your name: \n").strip().title() if name == user_name: print("Hello Mike! The password is W@12") else: print("Hello ", user_name, "See you later!")
''' Created on Apr 19, 2018 A player will have its associated style like X or O A player will be able to perform action to put a piece on the board When performing an action, a piece instance will be created and placed on the board @author: varunjai ''' from abc import ABC class Player(ABC): d...
y=10 #stel een getal in if y > 0: #is dit getal groter dan 0? print("Y is positief") else: #anders is het kleiner of gelijk aan 0 print("Y is negatief of 0")
from num2words import num2words letters=0 for i in range(1, 1001): numstr=num2words(i) numstr=numstr.replace(" ", "") numstr=numstr.replace("-", "") letters+=len(numstr) print numstr print letters
def collatz(n, cd): i = 0 n_orig = n n = int(n) while n not in cd: i += 1 if n % 2 == 0: n //= 2 else: n = n*3 + 1 return cd.update({n_orig: cd[n] + i}) collatzdict = {1: 0} max_route = 0 furthest = 1 for j in range(1, 10**6): collatz(j, collatz...
import unittest def is_unique(s): char_map = [False for _ in range(128)] for i in range(len(s)): ord_ch = ord(s[i]) if char_map[ord_ch]: return False else: char_map[ord_ch] = True return True class Test(unittest.TestCase): dataT = [('abcde'), ('12arc...
# -*- coding: utf-8 -*- """ Created on Thu Feb 15 15:42:34 2018 @author: David Input: positive values for total_cost, portion_saved and annual_salary. Output: A positive integer, the number of months needed to save for down payment. """ # Get user input. annual_salary = float(input('Enter your annual salary?: ')) po...
import random import collections import copy from tabulate import tabulate NUMBER_OF_GAMES = 5 def rockPaperScissors(): print("\n"*2) userinput = input("Choose out of the following options \n 1.rock \n 2.paper \n 3.scissors? ") print("\n"*100) gameOptions = ['rock','paper','scissors'] gameWinOptio...
#LISTAS Y MUTABILIDAD #Son secuencias de objetos mutables #Cuando modificamos una lista, puede haber efectos secundarios #Es posible iterar con ellas #Ejemplos en consola my_list = [1, 2, 3] my_list[0] my_list[1,:] #[2, 3] my_list.append(4) print(my_list) #[1, 2, 3, 4] #agregar my_list[0] = 'a' print(my_list) ['a',...
import re numerals = { "numbers": ["zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen"], "tens": ["", "", "twenty", "thirty", "forty", "fifty"...
#!/usr/bin/python3 ''' The 3-say_my_name module This module has a funciton that says a name ''' def say_my_name(first_name, last_name=""): ''' The function that that prints My name is <first name> <last name> ''' if isinstance(first_name, str) is False: raise TypeError('first_name must be a st...
#!/usr/bin/python3 """ Module """ def append_write(filename="", text=""): """ Append to a file """ with open(filename, 'a', encoding="utf-8") as f: f.write(text) f.close() return len(text)
# Bekijk je fizzbuzz van vorige week. # Nu willen we fizzbuzz voor alle getallen van 1 tot en met 100 uitvoeren # Met input zou dit te lang duren ;) # Schrijf dit nu met een loop, zodat dit automagisch gebeurt #%% for fizzbuzz in range(100): if fizzbuzz % 3 == 0 and fizzbuzz % 5 == 0: print("fizzbuzz") ...
#!/usr/bin/env python3 from collections import Iterable print(isinstance('abc', Iterable)) print(isinstance([1, 2, 4], Iterable)) print(isinstance(123, Iterable)) for i, value in enumerate(['A', 'B', 'C']): print(i, value) for x, y in [(1, 1), (3, 5), (6, 8)]: print(x, y) def find_max_and_min(l): max_...
# 두 정수(a, b)를 입력받아 # a의 값이 b의 값과 서로 다르면 True 를, 같으면 False 를 출력하는 프로그램을 작성해보자. a,b = map(int, input().split()) print(a!=b)
# 16진수를 입력받아 8진수(octal)로 출력해보자. # 예시 # a = input() # n = int(a, 16) #입력된 a를 16진수로 인식해 변수 n에 저장 # print('%o' % n) #n에 저장되어있는 값을 8진수(octal) 형태 문자열로 출력 # 참고 # 8진법은 한 자리에 8개(0 1 2 3 4 5 6 7)의 문자를 사용한다. # 8진수 10은 10진수의 8, 11은 9, 12는 10 ... 와 같다. a = input() n = int(a, 16) print('%o' % n)
import math from queue import Queue import numpy as np def is_connected(A): """ :param A:np.array the adjacency matrix :return:bool whether the graph is connected or not """ for _ in range(int(1 + math.ceil(math.log2(A.shape[0])))): A = np.dot(A, A) return np.min(A) > 0 def identity...
import pandas as pd import numpy as np #importing the required datasets into dataframes trainset = pd.read_csv('train.csv',index_col = 0 ) testset = pd.read_csv('test.csv',index_col = 0) result = pd.read_csv('gender_submission.csv',index_col = 0) #Examining the training dataset trainset.head() #Preparing...
class Node(): def __init__(self): self.next = None self.item = None class Stack(): def __init__(self): self._first = None def push(self, item): old_first = self._first self._first = Node() self._first.item = item self._first.next = old_first de...
import maze import helper import matplotlib.pyplot as plt import question23 import random import helper_24 # Using Threshold Probability from previous question p0=question23.probability_threshold() prob=[round(random.uniform(0,p0),2) for _ in range(6)] #Random Probability generated from 0 to p0 prob.sort() # prob=[0....
# -*- coding: utf-8 -*- """ Created on Thu Apr 29 23:05:47 2021 @author: annie """ import numpy as np import pickle def check_winner(matrix): xpos = '' opos = '' allpos = '' #horizontal win patterns winnercombs = [b'000000111',b'000111000',b'111000000', #vert...
import typing as tp def two_sum(nums: tp.Sequence[int], target: int) -> tp.List[int]: """ Takes a list of integers, return indices of the two numbers such that they add up to a specific target. You may assume that each input would have exactly one solution, and you may not use the same element twi...
import random ## 09. Typoglycemia def typoglycemia(target): result = [] for word in target.split(): if len(word) < 4: result.append(word) else: word_ran = list(word[1:-1]) #convert str to list since random.shuffle needs a list random.shuffle(word_ran) ...
## 16. ファイルをN分割する import math, pandas as pd N = int(input('N is: ')) # with open('hightemp.txt') as data_file: # lines = data_file.readlines() # file_len = len(lines) # unit = math.ceil(file_len / n) #how many lines in one file # # i is from 1, offset is from 0, and then offset + unit # for i, offset in enume...
""" Greg Stewart Your python script should take d, the number of digits, as a command line parameter. You will need to perform r=10 runs to record the average time to multiply two d-digit integers in decimal using the three methods above. For each run generate a random pair of integers x and y, that are d digits lon...
# filename: Salvador_e2.py # author: Ronald Salvador # description: This is a python program that classifies a tropical cyclone wrt its sustain winds import sys sustained_winds = sys.argv[1] sustained_winds = float(sustained_winds) if sustained_winds >= 220.0: print("Super Typhoon") elif sustained_winds >= 18...
''' Jesus Manuel Rodriguez Castro 12/04/2019 Assigment 8 Data Collections *Create a class called Grade that contains the class name, the credits and the grade point (from 0 to 4) for the grade. *Create a second class called Student that contains the students name and id number and a list of grade objects...
# Assignment 1 " Average" # This program will find the average of three exam scores. # Jesus Manuel Rodriguez Castro # 9/23/2019 def main(): print(" This program will show you the average of the three exam scores. ") score1 = eval(input("Enter the first score ")) score2 = eval(input("Enter the s...
#Jesus Manuel Rodriguez Castro #10/20/2019 #Peer Assigment 4 #steps: 1. Get the number of values to be enter from the user. # 2. Prompt the user for each numbre # 3. Total the numbers. # 4. Print the total def main(): print("This program will total values entered by the user. ") n=e...
# Assignment 1 KM to Miles. # This program will convert kilometers to milles. # Jesus Manuel Rodriguez Castro # 9/23/2019 def main(): print(" Convert Kilometers to Miles ") kilometers = int(input(" Enter Kilometer that you would like to know in Miles: ")) miles = kilometers * 0.62137119...
''' Jesus Manuel Rodriguez Castro 11/13/2019 Assignment 6 A certain college classifies students according to credits earned. A student with less than 7 credits is a Freshman. At least 7 credits are required to be a Sophomorem, 16 to be Junior and 26 to be classified as a Senior Write a program that calculates...
def NormalizeMult(data, set_range): ''' 返回归一化后的数据和最大最小值 ''' normalize = np.arange(2*data.shape[1], dtype='float64') normalize = normalize.reshape(data.shape[1], 2) for i in range(0, data.shape[1]): if set_range == True: list = data[:, i] listlow, listh...
def swap_bits(x:int, i: int, j: int) -> int: if ((x >> i & 1) != (x >> j & 1)): # print("Bits are different") bit_mask = (1 << i) | (1 << j) x ^= bit_mask return x while True: try: number = int(input("Enter a decimal number: ")) print(number.bit_length()) i =...
courses = ['Python', 'SQL', 'Docker', 'Airflow', 'NoSQL'] print('Courses:', courses) print(courses.index('SQL')) # Fetch index of item in a list print(min(courses)) # aggregates print('Python' in courses) # returns a boolean print("Traditional indexing:") for index, course in enumerate(courses): print(f"{in...
""" A scenario where it would be important to use a class variable, would be when an attribute is to have a constant value across all instances. This can then be referenced in a class method e.g a total number of employees (num_of_emps) which increases each time a new employee is created. """ class Employee: ...
# instance methods and variables """ --Instance variables are used to store data that is unique to each instances -- """ class Employee: def __init__(self, first_name, last_name, pay): self.first_name = first_name self.last_name = last_name self.pay = pay self.email = first_na...
import speech_recognition as sr import os, sys from actions import action from conversation import * r = sr.Recognizer() m = sr.Microphone() position = 1 try: print("A moment of silence, please...") with m as source: r.adjust_for_ambient_noise(source) print("Set minimum energy threshold to {}"...
from Utils.bt_scheme import PartialSolutionWithOptimization, BacktrackingOptSolver, State, Solution from typing import * from random import random, seed from time import time def knapsack_solve(weights, values, capacity): class KnapsackPS(PartialSolutionWithOptimization): def __init__(self, solution=(), s...
# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None """ two-pass alogrithm """ class Solution: def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode: num = 0 cur = head while(cur) : ...
class Power(): def __init__(self,name,type,damage,diploma): #The name, damage, diploma defines the power self.__name=name self.__type=type self.__damage=damage self.__diploma=diploma def set_name(name): self.__name=name def get_name(self): return self....
import random class BasePlayer: ''' This class contains all logic for a player. Note: - do not change the names of any existing methods To Do: - incomingTrade() - beginTurn() (eg. turn logic) ''' def __init__(self, gamemaster, GBview, playerID): ''' BasePlayer....
a = 2 b = 4 print("a:{}".format(a)) print("b:{}".format(b)) print("a+b:{}".format(a+b))
import math a, b, x = (int(i) for i in input().split()) t = 2 * (b/a - x/(a*a*a)) z = math.atan(b/a) rad = math.atan(t) if(rad <= z): deg = math.degrees(rad) else: rad = math.atan((a*b*b)/(2*x)) deg = math.degrees(rad) print(deg)
## TODO: define the convolutional neural network architecture import torch import torch.nn as nn import torch.nn.functional as F # can use the below import should you choose to initialize the weights of your Net import torch.nn.init as I class Net(nn.Module): def __init__(self): super(Net, self).__init_...
#!/usr/bin/python # -*- coding: utf-8 -*- from Position import * """ SUCCESS : La position a était crée ERROR : La position est incorrecte """ def testCreation(pos1): return (pos1.x() == 1 and pos1.y() == 2) """ ERROR : La position est touchee SUCCESS : La position est bien non touchee """ def testEstTouche(pos1)...
''' 929. 独特的电子邮件地址 每封电子邮件都由一个本地名称和一个域名组成,以 @ 符号分隔。 例如,在 alice@leetcode.com中, alice 是本地名称,而 leetcode.com 是域名。 除了小写字母,这些电子邮件还可能包含 '.' 或 '+'。 如果在电子邮件地址的本地名称部分中的某些字符之间添加句点('.'),则发往那里的邮件将会转发到本地名称中没有点的同一地址。 例如,"alice.z@leetcode.com” 和 “alicez@leetcode.com” 会转发到同一电子邮件地址。 (请注意,此规则不适用于域名。) 如果在本地名称中添加加号('+'),则会忽略第一个加号后面的所有内容。这允许...
''' 739. 每日温度 根据每日 气温 列表,请重新生成一个列表,对应位置的输出是需要再等待多久温度才会升高超过该日的天数。如果之后都不会升高,请在该位置用 0 来代替。 例如,给定一个列表 temperatures = [73, 74, 75, 71, 69, 72, 76, 73],你的输出应该是 [1, 1, 4, 2, 1, 1, 0, 0]。 提示:气温 列表长度的范围是 [1, 30000]。每个气温的值的均为华氏度,都是在 [30, 100] 范围内的整数。 ''' from typing import List class Solution: def dailyTemperatures(self, T...
''' 5398. 统计二叉树中好节点的数目 给你一棵根为 root 的二叉树,请你返回二叉树中好节点的数目。 「好节点」X 定义为:从根到该节点 X 所经过的节点中,没有任何节点的值大于 X 的值。 ''' from base import TreeNode class Solution: def goodNodes(self, root: TreeNode) -> int: self.count = 0 def _find_deep(p, max_before): if not p: return 0 i...
''' 414. 第三大的数 给定一个非空数组,返回此数组中第三大的数。如果不存在,则返回数组中最大的数。要求算法时间复杂度必须是O(n)。 示例 1: 输入: [3, 2, 1] 输出: 1 解释: 第三大的数是 1. 示例 2: 输入: [1, 2] 输出: 2 解释: 第三大的数不存在, 所以返回最大的数 2 . 示例 3: 输入: [2, 2, 3, 1] 输出: 1 解释: 注意,要求返回第三大的数,是指第三大且唯一出现的数。 存在两个值为2的数,它们都排第二。 思路:按照找最大值的方式,找三次 ''' class Solution: def thirdMax(self, nums) -> int: ...
''' 443. 压缩字符串 给定一组字符,使用原地算法将其压缩。 压缩后的长度必须始终小于或等于原数组长度。 数组的每个元素应该是长度为1 的字符(不是 int 整数类型)。 在完成原地修改输入数组后,返回数组的新长度。 进阶: 你能否仅使用O(1) 空间解决问题? 示例 1: 输入: ["a","a","b","b","c","c","c"] 输出: 返回6,输入数组的前6个字符应该是:["a","2","b","2","c","3"] 说明: "aa"被"a2"替代。"bb"被"b2"替代。"ccc"被"c3"替代。 示例 2: 输入: ["a"] 输出: 返回1,输入数组的前1个字符应该是:["a"] 说明: 没有...
""" LCP 22. 黑白方格画 小扣注意到秋日市集上有一个创作黑白方格画的摊位。摊主给每个顾客提供一个固定在墙上的白色画板,画板不能转动。 画板上有 n * n 的网格。绘画规则为,小扣可以选择任意多行以及任意多列的格子涂成黑色,所选行数、列数均可为 0。 小扣希望最终的成品上需要有 k 个黑色格子,请返回小扣共有多少种涂色方案。 注意:两个方案中任意一个相同位置的格子颜色不同,就视为不同的方案。 示例 1: 输入:n = 2, k = 2 输出:4 解释:一共有四种不同的方案: 第一种方案:涂第一列; 第二种方案:涂第二列; 第三种方案:涂第一行; 第四种方案:涂第二行。 示例 2: 输入:n = 2, k = 1 输出:0 ...
""" 1518. 换酒问题 小区便利店正在促销,用 numExchange 个空酒瓶可以兑换一瓶新酒。你购入了 numBottles 瓶酒。 如果喝掉了酒瓶中的酒,那么酒瓶就会变成空的。 请你计算 最多 能喝到多少瓶酒。 示例 1: 输入:numBottles = 9, numExchange = 3 输出:13 解释:你可以用 3 个空酒瓶兑换 1 瓶酒。 所以最多能喝到 9 + 3 + 1 = 13 瓶酒。 示例 2: 输入:numBottles = 15, numExchange = 4 输出:19 解释:你可以用 4 个空酒瓶兑换 1 瓶酒。 所以最多能喝到 15 + 3 + 1 = 19 瓶酒。 示例 3: 输入:num...
''' 693. 交替位二进制数 给定一个正整数,检查他是否为交替位二进制数:换句话说,就是他的二进制数相邻的两个位数永不相等。 示例 1: 输入: 5 输出: True 解释: 5的二进制数是: 101 示例 2: 输入: 7 输出: False 解释: 7的二进制数是: 111 示例 3: 输入: 11 输出: False 解释: 11的二进制数是: 1011 示例 4: 输入: 10 输出: True 解释: 10的二进制数是: 1010 通过次数13,338提交次数22,085 ''' class Solution: def hasAlternatingBits(self, n: int) -> bool: ...
""" 1252. 奇数值单元格的数目 给你一个 n 行 m 列的矩阵,最开始的时候,每个单元格中的值都是 0。 另有一个索引数组 indices,indices[i] = [ri, ci] 中的 ri 和 ci 分别表示指定的行和列(从 0 开始编号)。 你需要将每对 [ri, ci] 指定的行和列上的所有单元格的值加 1。 请你在执行完所有 indices 指定的增量操作后,返回矩阵中 「奇数值单元格」 的数目。 示例 1: 输入:n = 2, m = 3, indices = [[0,1],[1,1]] 输出:6 解释:最开始的矩阵是 [[0,0,0],[0,0,0]]。 第一次增量操作后得到 [[1,2,1],[0,1,0]...
''' 645. 错误的集合 集合 S 包含从1到 n 的整数。不幸的是,因为数据错误,导致集合里面某一个元素复制了成了集合里面的另外一个元素的值,导致集合丢失了一个整数并且有一个元素重复。 给定一个数组 nums 代表了集合 S 发生错误后的结果。你的任务是首先寻找到重复出现的整数,再找到丢失的整数,将它们以数组的形式返回。 示例 1: 输入: nums = [1,2,2,4] 输出: [2,3] 注意: 给定数组的长度范围是 [2, 10000]。 给定的数组是无序的。 ''' class Solution: def findErrorNums(self, nums): # 先排序,找到重复的 re...
''' 728. 自除数 自除数 是指可以被它包含的每一位数除尽的数。 例如,128 是一个自除数,因为 128 % 1 == 0,128 % 2 == 0,128 % 8 == 0。 还有,自除数不允许包含 0 。 给定上边界和下边界数字,输出一个列表,列表的元素是边界(含边界)内所有的自除数。 示例 1: 输入: 上边界left = 1, 下边界right = 22 输出: [1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 12, 15, 22] 注意: 每个输入参数的边界满足 1 <= left <= right <= 10000。 ''' from typing import List class Solu...
''' 832. 翻转图像 给定一个二进制矩阵 A,我们想先水平翻转图像,然后反转图像并返回结果。 水平翻转图片就是将图片的每一行都进行翻转,即逆序。例如,水平翻转 [1, 1, 0] 的结果是 [0, 1, 1]。 反转图片的意思是图片中的 0 全部被 1 替换, 1 全部被 0 替换。例如,反转 [0, 1, 1] 的结果是 [1, 0, 0]。 示例 1: 输入: [[1,1,0],[1,0,1],[0,0,0]] 输出: [[1,0,0],[0,1,0],[1,1,1]] 解释: 首先翻转每一行: [[0,1,1],[1,0,1],[0,0,0]]; 然后反转图片: [[1,0,0],[0,1,0],[1,1,1]...
''' 453. 最小移动次数使数组元素相等 给定一个长度为 n 的非空整数数组,找到让数组所有元素相等的最小移动次数。每次移动可以使 n - 1 个元素增加 1。 示例: 输入: [1,2,3] 输出: 3 解释: 只需要3次移动(注意每次移动会增加两个元素的值): [1,2,3] => [2,3,3] => [3,4,3] => [4,4,4] ''' class Solution: def minMoves1(self, nums) -> int: # 暴力破解法 count = 0 status = True while status: ...
''' 551. 学生出勤记录 I 给定一个字符串来代表一个学生的出勤记录,这个记录仅包含以下三个字符: 'A' : Absent,缺勤 'L' : Late,迟到 'P' : Present,到场 如果一个学生的出勤记录中不超过一个'A'(缺勤)并且不超过两个连续的'L'(迟到),那么这个学生会被奖赏。 你需要根据这个学生的出勤记录判断他是否会被奖赏。 示例 1: 输入: "PPALLP" 输出: True 示例 2: 输入: "PPALLL" 输出: False ''' class Solution: def checkRecord(self, s: str) -> bool: a_count = ...
''' 594. 最长和谐子序列 和谐数组是指一个数组里元素的最大值和最小值之间的差别正好是1。 现在,给定一个整数数组,你需要在所有可能的子序列中找到最长的和谐子序列的长度。 示例 1: 输入: [1,3,2,2,5,2,3,7] 输出: 5 原因: 最长的和谐数组是:[3,2,2,2,3]. 说明: 输入的数组长度最大不超过20,000. ''' class Solution: def findLHS(self, nums) -> int: # hash法 has_dict = dict() for num in nums: if num in has_dic...
''' 378. 有序矩阵中第K小的元素 给定一个 n x n 矩阵,其中每行和每列元素均按升序排序,找到矩阵中第 k 小的元素。 请注意,它是排序后的第 k 小元素,而不是第 k 个不同的元素。 示例: matrix = [ [ 1, 5, 9], [10, 11, 13], [12, 13, 15] ], k = 8, 返回 13。 提示: 你可以假设 k 的值永远是有效的,1 ≤ k ≤ n2 ''' from typing import List class Solution: def kthSmallest(self, matrix: List[List[int]], k: int) ->...
''' 633. 平方数之和 给定一个非负整数 c ,你要判断是否存在两个整数 a 和 b,使得 a2 + b2 = c。 示例1: 输入: 5 输出: True 解释: 1 * 1 + 2 * 2 = 5 示例2: 输入: 3 输出: False ''' class Solution: def judgeSquareSum(self, c: int) -> bool: # 穷举法 has_in = set() a = 0 while a * a <= c: has_in.add(a * a) a += 1 ...
''' 977. 有序数组的平方 给定一个按非递减顺序排序的整数数组 A,返回每个数字的平方组成的新数组,要求也按非递减顺序排序。 示例 1: 输入:[-4,-1,0,3,10] 输出:[0,1,9,16,100] 示例 2: 输入:[-7,-3,2,3,11] 输出:[4,9,9,49,121] 提示: 1 <= A.length <= 10000 -10000 <= A[i] <= 10000 A 已按非递减顺序排序。 ''' from typing import List class Solution: def sortedSquares(self, A: List[int]) -> List[int]: ...
''' 5415. 圆形靶内的最大飞镖数量 显示英文描述 墙壁上挂着一个圆形的飞镖靶。现在请你蒙着眼睛向靶上投掷飞镖。 投掷到墙上的飞镖用二维平面上的点坐标数组表示。飞镖靶的半径为 r 。 请返回能够落在 任意 半径为 r 的圆形靶内或靶上的最大飞镖数。 ''' class Solution: def numPoints(self, points, r: int) -> int: return 0 so = Solution() print(so.numPoints([[-2, 0], [2, 0], [0, 2], [0, -2]], 2) == 4) print(so.numPoints([[...