text
stringlengths
37
1.41M
from nltk.corpus import stopwords from nltk.tokenize import word_tokenize from nltk.stem.wordnet import WordNetLemmatizer import string def clear_text(txt): # Tokenization tokens = word_tokenize(txt) # Lowercase conversion tokens = [w.lower() for w in tokens] # Removing punctuation ...
# write a program that uses input to prompt a user for their name and then welcomes them entered_name = input("Please enter your name :") print("Hello", entered_name)
def calculator(): num_coll = list() while True: num = input("Enter a number:") # check if user entered something and they are all digits if len(num) > 0 and num.isdigit(): # add number to the list num_coll.append(int(num)) print("Current numbers:", num_coll) elif len(num) > 0 and num == "done": ...
word = "banana" count = 0 for letter in word: if letter == "a": count += 1 else: continue print("The letter [a] appears %s times!" % (str(count)))
# Prompt user for the first point x_1 = input("Enter x1:") # Prompt user for the first point y_1 = input("Enter y1:") # Prompt user for the first point x_2 = input("Enter x2:") # Prompt user for the first point y_2 = input("Enter y2:") # calculate difference between the x coordinates first_diff = int(x_2) - int(x_1) ...
from math import sqrt from math import ceil import pygame """ Just a dot moving left or right depending on given settings """ class Entity: """ x, y direction --> -1 is left and 1 is right velocity """ def __init__(self, x, y, direction, velocity): self.x = x ...
print("Welcome ") name = input("Enter your name: ") age = int(input("Enter your age: ")) energy = int(10) while age >= 5: print("You are eligible to play\nLet's begin\nEnergy = 10") print("In the evening you are walking through a forest and you come across a lake") choice1 = input('''What will you do...
def solve(bo): find = find_empty(bo) if not find: return True else: (row, col) = find for i in range(1, 10): if valid(bo, i, (row, col)): bo[row][col] = i if solve(bo): # calling solve on new board return True ...
def main(): example = ['hello', 'good morning', 'bye bye', 'have a good day'] placeOfChange = int(input("Choose the position of the element that you want change : ")) Change = input("What you want place : ") example[placeOfChange-1] = Change print(example) if __name__=="__main__" : main()
list_one = ['six', 'three', 'two', 'one'] list_two = ['four', 'seven', 'five'] final_list = list_two + list_one print(final_list[-1:-4:-1] + final_list[0:3:2] + final_list[-4:-7:-2])
# Programmer - python_scripts (Abhijith Warrier) # PYTHON GUI TO CONVERT USER-INPUT AMOUNT FROM SELECTED CURRENCY VALUE TO SELECTED CURRENCY BASED ON REAL-TIME CURRENCY RATES # GET YOUR FREE API KEY FROM : https://www.alphavantage.co # Importing necessary packages import requests import tkinter as tk from t...
""" 题目022:两个乒乓球队进行比赛,各出三人。 甲队为a,b,c三人,乙队为x,y,z三人。 已抽签决定比赛名单。有人向队员打听比赛的名单。 a说他不和x比,c说他不和x,z比,请编程序找出三队赛手的名单。 """ def t22(): for a in ['x', 'y', 'z']: for b in ['x', 'y', 'z']: for c in ['x', 'y', 'z']: if a != b and b != c and c != a: if a != 'x' ...
def decorator_function(original_function): def wrapper_function(*args, **kwargs): print('wrapper executed this before {}'.format(original_function.__name__)) original_function(*args, **kwargs) return wrapper_function @decorator_function def display(name, age): print('Display Function Ran wi...
inputstr = input('Enter you statement:').split() unq = [] for each in inputstr: if each not in unq: unq.append(each) print(' '.join(unq))
def isprime(num): for i in range(2,num-1): if(num==2): return True elif(num%i==0): break else: return True def findnextprime(num): prime =num i=1 while(i==1): prime=prime+1 if(isprime(prime)==True): return(prime) ...
# Нэрсийн дарааллаас хамгийн богино нэрийг олж 'Сайн уу?' гэж соль. names = ["danzanravjaa","bold","bat"] print(names) z = 99 for i in names: urt = len(i) if z >= urt: z = urt a = i index = names.index(a) names.insert(index,"Sain uu?") print(names)
# Өгөгдсөн тоон дарааллыг буурахаар эрэмбэл. nums = [int(x) for x in input().split()] nums.sort() nums.reverse() print(nums) print(sorted(nums, reverse=True))
#!/bin/python #https://www.hackerrank.com/challenges/common-child/ import sys def commonChild(s1, s2): # Complete this function lcs = [] m = len(s1) n = len(s2) for i in range(m): lcs.append([0]*n) for i in range(m): if (s2[0] == s1[i]): lcs[i][0] = 1 ...
#https://www.hackerrank.com/challenges/flatland-space-stations #!/bin/python3 import sys def flatlandSpaceStations(n, stations): # Complete this function stations.sort() size = len(stations) if size == 1: return max(n-1-stations[0], stations[0] - 0) diff = stations[1] - stations[...
'''The prime factors of 13195 are 5, 7, 13 and 29. What is the largest prime factor of the number 600851475143 ?''' res = 0 primes = [] number = 600851475143 upper = number ** 0.5 + 1 i = 1 def isPrime(x): if x % 2 == 0 or x < 3: return False else: for i in range(3, int(x ** 0.5) + 1): ...
running = True epsilon = .01 guess = 1 counter = 0 while running: try: user_number = int(input("Please enter a Number: ")) if user_number < 0: user_number = user_number * -1 running = False except ValueError: print("Enter a valid Number!!") continue thinkin...
from itertools import product def generate_names(): """Generate a list of random `adjective + noun` strings.""" adjectives = [ 'Exquisite', 'Delicious', 'Elegant', 'Swanky', 'Spicy', 'Food Truck', 'Artisanal', 'Tasty', ] nouns = [ ...
#Function that prints total amount of coding exercises in a dictionary. Also uses.value function that returns values of a dictionary num_exercises = {"functions": 10, "syntax": 13, "control flow": 15, "loops": 22, "lists": 19, "classes": 18, "dictionaries": 18} total_exercises=0 for value in num_exercises.values(): ...
# -*-coding:utf8 import hashmap # create a mapping of states to abbreviation states = hashmap.new() hashmap.set(states, 'Oregon', 'OR') hashmap.set(states, 'Florida', 'FL') hashmap.set(states, 'California', 'CA') hashmap.set(states, 'Nwe York', 'NY') hashmap.set(states, 'Hawaii', 'HI') cities = hashmap.new() hashm...
class Category: def __init__(self, description): self.description = description self.ledger = [] def __str__(self): ledger_str = (self.description).center(30, '*') + '\n' for entry in self.ledger: ledger_str = ledger_str + ((entry["description"]).ljust(23))[:23] + ...
""" This module offers a solution to the "Hamming" exercise on Exercism.io. """ import sys def distance(strand_a: str, strand_b: str) -> int: if len(strand_a) != len(strand_b): raise ValueError("sequences not of equal length") return [n_a == n_b for (n_a, n_b) in zip(strand_a, strand_b)].count...
""" This module offers a solution to the "Isogram" exercise on Exercism.io. """ import sys from typing import List def is_isogram(string:str) -> bool: def alpha_pos(c:str) -> int: return ord(c) - ord("A") + 1 alphagram: List[int] = [None] + [0] * 26 for c in string: if c.isalpha(...
# Exercise for Udemy course: python-for-data-science-and-machine-learning-bootcamp/ import pandas as pd import seaborn as sns import matplotlib.pyplot as plt from sklearn.linear_model import LinearRegression from sklearn.model_selection import train_test_split from sklearn import metrics import numpy as np customers =...
# Skill Challenges for Udemy course: The Ultimate Pandas Bootcamp: Advanced Python Data Analysis # Not cleaned import pandas as pd tech_giants = pd.read_csv("data//tech_giants.csv", index_col=["date", "name"]) print(tech_giants.info()) print(tech_giants.head()) tech_df2 = tech_giants.loc[(slice("2015-07-13", "2016-08...
import pandas as pd import numpy as np df = pd.read_csv("pandas_tutorial.csv", index_col="S.No", dtype={"Salary": np.float64}) print(df) df = pd.read_csv("pandas_tutorial.csv", dtype={"Salary": np.float64}, names=["a", "b", "c", "d", "e"]) print(df) # remove header df = pd.read_csv("pandas_tutorial.csv", dtype={"Salar...
import math def quadratic(a, b, c): if not isinstance(a, (int, float)) or not isinstance(b, (int, float)) or not isinstance(c, (int, float)): raise TypeError('bad operand type') x1 = (-b + math.sqrt(b * b - 4 * a * c)) / 2 * a x2 = (-b - math.sqrt(b * b - 4 * a * c)) / 2 * a return x1, x2
""" Create a user table in the blog database """ # coding: utf-8 from sqlalchemy import create_engine from sqlalchemy.ext.declarative import declarative_base from sqlalchemy import Column, String, Integer, Text from sqlalchemy import ForeignKey from sqlalchemy.orm import relationship ENGINE = create_engine('mysql://r...
# -*- coding: utf-8 -*- class Singleton: """ Singleton class decorator can be used to implement any class of singleton case. But it can't be multiple threading environment. """ def __init__(self, cls): """ The command parameter is a class """ self._cls = cls def Instance(self)...
#!/usr/bin/env python3 def poly_derivative(poly): if type(poly) is not list or len(poly) < 1: return None for coefficient in poly: if type(coefficient) is not int and type(coefficient) is not float: return None for power, coefficient in enumerate(poly): if power is 0: ...
# Hackerrank 30 Days of code Challenge # https://www.hackerrank.com/domains/tutorials/30-days-of-code # Day 8 import sys N = int(sys.stdin.readline()) phonebook = dict() for _ in range(N): name, number = sys.stdin.readline().rstrip().split() phonebook[name] = number for _ in range(N): name = sys.stdin.r...
# Hackerrank 30 Days of code Challenge # https://www.hackerrank.com/domains/tutorials/30-days-of-code # Day 26 real_day, real_month, real_year = list(map(int, input().split())) expc_day, expc_month, expc_year = list(map(int, input().split())) if real_year > expc_year: print(10000) elif real_year == expc_year: ...
a=range(10) for b in a: print(b) d=range(10,20) for c in d: print(c) e=range(20,30,2) for f in e: print(f) g=range(40,30,-1) for h in g: print(h)
while True: name=input('Enter User Name:') if name !='Rahul': print('Enter the correct User Name') continue password=input('Hello , Rahul. What is the Password?') if password !='Singh': break print('Access Granted')
import time from playsound import playsound #function for getting their alarm input def get_alarm_time(): hours = float(input("Enter hour(24 hour system): ")) minute = float(input("Enter minute: ")) second = float(input("Enter second: ")) return (hours*60*60) + (minute*60) + second #functi...
# global variable board = [['_', '_', '_'], ['_', '_', '_'], ['_', '_', '_']] # games board def print_board(): print(board[0][0] + ' ' + board[0][1] + ' ' + board[0][2]) print(board[1][0] + ' ' + board[1][1] + ' ' + board[1][2]) print(board[2][0] + ' ' + board[2][1] + ' ' + board[2][2]) # fun...
""" 下面的文件将会从csv文件中读取读取短信与电话记录, 你将在以后的课程中了解更多有关读取文件的知识。 """ 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) #返回只拨打电话的set def getAllZhuJiao(calls): zhujiao = set() beijiao = se...
A = [1,5,7,10] def function1(A): summ = 0 for i in range(len(A)): summ += A[i] return summ summa = function1(A) print (summa) def function2(A): i=0 summ=0 while(i<len(A)): summ += A[i] i+=1 return summ summa2=function2(A) print(summa2) def function3(A,i): ...
""" DB作成 """ # coding: utf-8 import sys import sqlite3 def create_database(): # db作成 db = sqlite3.connect('db.sqlite3') cur = db.cursor() try: sql = """ CREATE TABLE PARAM( CD TEXT NOT NULL PRIMARY KEY, VALUE TEXT NOT NULL, ...
import tensorflow as tf import numpy as np import tensorflow.examples.tutorials.mnist.input_data as input_data mnist = input_data.read_data_sets("MNIST_data/", one_hot=True) x_data = tf.placeholder(tf.float32, [None, 784]) y_data = tf.placeholder(tf.float32, [None, 10]) weight1 = tf.Variable(tf.ones([784, 256])) bi...
#PPC Challange 7 name = input('What is your name?' ) age = int(input("What is your age? ")) birthday = age + 1 print("So your next birthday you are" birthday "?") #Completed Successfully? Yes #Did I have Errors? Nope #How did I solve them? Didn't have any #What Did I find difficult? figuring out my python math
import time from test6 import player import keyboard def main(): print("Bienvenue dans l'Attaque des titans.\nIl n'en tient qu'a vous pour gagner !\n" "Soyer vif et la victoire sera a vous !") punch = 0 players = [] pseudo = [] while len(pseudo) < 2: pseudo.append(str(input("Que...
def welcome(): print('Hello', end=' ') print('Bob') welcome() def displayAge(age): print(f'Your age: {age}') displayAge(20) #Utwórz funkcję zwracającą iloczyn dwóch liczb. Użytkownik podaje dane z klawiatury. def iloczyn(a, b): return a*b first = float(input('Podaj pierwszą liczbę: ')) second = fl...
__author__ = 'ishaan' from jinja2 import Template from templates import * import os class GroupedField(object): """ Represents a Section like Work Experience , which can have multiple entries of the same fields """ def __init__(self, group, fields, required=False): """ Args - g...
""" Faça um Programa que peça um número e então mostre a mensagem O número informado foi [número] """ number = input("digite um numero:") print("o numero informado foi", number)
""" Faça um programa que pergunte o preço de três produtos e informe qual produto você deve comprar, sabendo que a decisão é sempre pelo mais barato """ produto_one = input("Digite o valor do produto um:") produto_two = input("Digite o Valor do Produto dois:") produto_tree = input("Digite o Valor do produto três:") i...
#https://programmers.co.kr/learn/courses/30/lessons/42627?language=python3 import heapq def solution(jobs): answer = 0 heapJob = [] start, now, end = -1, 0, 0 jobsAll = len(jobs) while end < jobsAll: for job in jobs: if start < job[0] <= now: heapq.heappush(heapJ...
#https://programmers.co.kr/learn/courses/30/lessons/42746?language=python3 def solution(numbers): answer = '' num1 = [str(i)*3 for i in numbers] nums = list(enumerate(num1)) nums.sort(key = lambda x:x[1], reverse = True) for index, value in nums: answer += str(numbers[index]) ...
import unittest import gensent import nltk class TestSentenceGenerator(unittest.TestCase): sentence_list = [ 'I am Sam, Sam-I-am.', 'That Sam-I-am.', 'That Sam-I-am.', 'I do not like that Sam-I-am.', 'Do you like green eggs and ham?' ] def test_generator_...
from tkinter import * from tkinter import messagebox def call_me(): answer = messagebox.askquestion("Exit","Do you really want to exit ?") if answer == 'yes': root.quit() root = Tk() b = Button(root, text="Exit ?", command=call_me, fg="green", bg ="black") b.pack(side = RIGHT,fill = Y) root.minsiz...
from tkinter import * from tkinter import simpledialog def get_me(): s = simpledialog.askstring("Ask","Enter your name:") t = str(simpledialog.askfloat("Ask","Enter your weight:")) u = str(simpledialog.askinteger("Ask","Enter your age:")) info = ('Name:\t' + s + '\nWeight:\t' + t + '\nAge:\t' + u) ...
def add(a,b): return a + b def prin(): print('Your answer is:') print('start=') x = int(input("Number 1:")) y = int(input("Number 2:")) result = add(x,y) prin() print(result)
x = 100 if x==10: print('this is ten') else: print('this is not ten') if x is 10: print('ten') if x is not 10: print('this is not ten')
def reverseInParentheses(s): for i in range(len(s)): if s[i] == "(": start = i if s[i] == ")": end = i return reverseInParentheses(s[:start] + s[start + 1:end][::-1] + s[end + 1:]) return s s = "foo(bar(baz))blim" print(reverseInParentheses(s))
class Student: def __init__(self,name,age): self.name = name self.age = age def __str__(self): return 'Name : '+self.name+'\nAge : '+str(self.age) def __repr__(self): return {'name':self.name, 'age':self.age} s1 = Student("Meet",14) print(s1) print(s1.__repr__())
from tkinter import * from tkinter.font import Font root = Tk() my_font = Font(size=16, family="algerian",weight="bold",slant="italic",underline=1,overstrike=1) #here weight is the option where you can make text bold text = Label(root,text="Meet Patel",font = my_font) text.pack() root.minsize(300,300) root.mainloop...
import random import math import time import sys def get_random_robot_choice(): label = ["rock", "paper", "scissors"] return label[random.randint(0, 2)] def decide_winner(payer_one, robot_choice): result = 0 print_result = "" print("\nYou chose "+payer_one + " and Robot chose "+robot_choice) ...
"""calculates your updates-per-second""" from __future__ import division import time class Updatefreq: """make one of these, call update() on it as much as you want, and then float() or str() the object to learn the updates per second. the samples param to __init__ specifies how many past updates will ...
from lib.abstract_strategy import SortAlgorithm class BubbleSort(SortAlgorithm): def __init__(self, target_list: list): super().__init__(target_list) def sort(self) -> None: n = len(self._target_list) for i in range(n - 1): for j in range(n - 1 - i): if se...
import string a=list(string.ascii_lowercase+string.ascii_uppercase) b=input() c=[] for i in list(b): if (i in a) and (i not in c): c.append(i) if len(c)>=26: print("yes") else: print("no")
'''def f(x): return 2*x+3 print f(2) print(3+4*6) print f(f(6)) v=89 print f(v) Task 1 def greater(x,y): if x>y: return x else: return y x=float(raw_input("Enter your first number: ")) y=float(raw_input("Enter your second number: ")) print greater(x,y) Task 2 def echo(): x= raw_inpu...
# Crie um programa que tenha uma tupla única com nomes de produtos e seus respectivos preços, na sequência. # No final, mostre uma listagem de preços, organizando os dados em forma tabular. #fazer o len da palavra loja de roupas e dividir o valor por 2, para ficar centralizado #após isso, somar da metade do tota...
import random def loto(): print ("Welcome to the Lottery numbers generator.") vprasanje = raw_input("Please enter how many random numbers would you like to have: ") try: stevilo = int(vprasanje) print loto(stevilo) except ValueError: print "Please enter a number." ...
import requests import json city=input('input the city name: ') url='http://api.openweathermap.org/data/2.5/weather?q={}&appid=56eeb1eb05170558d1333d044c94df18&units=metric'.format(city) res= requests.get(url) api=json.loads(res.content) temp=api['main']['temp'] humidity=api['main']['humidity'] wind_speed=api['win...
class Stack(list): #stc_ is used to mark original or chaged methods of Stack obj def stc_is_ismpty(self): return self == [] def stc_get_size(self): return len(self) def _last_idx(self): return self.stc_get_size() - 1 def stc_push(self, something): self.append(something) def stc_pop(...
line = input("Enter some words separated with SPACE, I`ll find the longest: ") my_list = line.split(" ") #print(my_list) my_dict = dict.fromkeys(my_list, 0) for elem in my_list: my_dict[elem] = len(elem) #print(my_dict) moda = max(my_dict.values()) my_list.clear() for key in my_dict: if my_dict[...
height = int(input(" Height :")) x_range = 2*(height - 1) new_height = x_range // 2 for x in range(x_range,-1,-1): k_range = abs(x - new_height) j_range = 2*(height - k_range) - 1 for k in range(k_range): print(" ",end="") for j in range(j_range): print("*",end="") print() print(''' ....
def fact(n): if (n<2): return 1 return n*fact(n-1) q = None while(q!= "q"): x = int(input("Enter the number :")) p = fact(x) print("Factorial of ",x," :",p) q = input("Press q to exit , any other key to continue :")
# Measure the execution time for small bits of python code import timeit # s = "-".join(map(str, range(100))) # print(s) print(timeit.timeit('"_".join(str(n) for n in range(100))', number=10000)) print(timeit.timeit('"-".join([str(n) for n in range(100)])', number=10000)) print(timeit.timeit('"-".join(map(str, ran...
from turtle import Turtle, Screen from random import randint, choice ballspeed = 10 playerspeed = 30 cursor_size = 20 player_height = 60 player_width = 20 court_width = 800 court_height = 600 FONT = ("Arial", 44, "normal") def draw_border(): border.pensize(3) border.penup() border.setposition(-court_wi...
bit: int = int(input()) A = [0] * bit def binary(n): if n < 1: print(A) else: A[n - 1] = 0 binary(n - 1) A[n - 1] = 1 binary(n - 1) binary(bit)
# -*- coding:utf-8 -*- # 导入两个方法 from sys import argv from os.path import exists # 定义两个变量 script, from_file, to_file = argv # 打印from_file,to_file变量 print "Coping from %s to %s" % (from_file, to_file) # we could do these two on one line too, how? # 用变量in_file存储文件内容 in_file = open(from_file) # 读取文件 indata = in_file.read()...
# 5. 最长回文子串 # 给定一个字符串 s,找到 s 中最长的回文子串。你可以假设 s 的最大长度为 1000。 class Solution: def longestPalindrome(self, s): # 中心扩散法 size = len(s) if size == 0: return '' # 最短回文串的长度至少是 1 longest_palindrome = 1 longest_palindrome_str = s[0] for i in range(size): ...
# 53. 最大子序和 # 给定一个整数数组 nums ,找到一个具有最大和的连续子数组(子数组最少包含一个元素),返回其最大和。 # 动态规划 from typing import List class Solution: def maxSubArray(self, nums: List[int]) -> int: size = len(nums) if size == 0: return 0 # 起名叫 pre 表示的意思是“上一个状态”的值 pre = nums[0] res = pre f...
# https://leetcode-cn.com/problems/remove-duplicates-from-sorted-array/description/ # 给定一个排序数组,你需要在原地删除重复出现的元素,使得每个元素只出现一次,返回移除后数组的新长度。 # 不要使用额外的数组空间,你必须在原地修改输入数组并在使用 O(1) 额外空间的条件下完成。 # 给你一个已经排好序的数组,删除重复的元素,是原地删除,相同元素只保留一个,返回数组的长度。 # 应该充分利用排好序的数组这个特性来完成。 # 应该注意到一些特殊的测试用例,例如 nums = [] 的时候。注意,题目要求返回新数组的长度。 class Soluti...
# 126. 单词接龙 II 困难 # 给定两个单词(beginWord 和 endWord)和一个字典 wordList,找出所有从 beginWord 到 endWord 的最短转换序列。转换需遵循如下规则: # # 每次转换只能改变一个字母。 # 转换过程中的中间单词必须是字典中的单词。 # 说明: # # 如果不存在这样的转换序列,返回一个空列表。 # 所有单词具有相同的长度。 # 所有单词只由小写字母组成。 # 字典中不存在重复的单词。 # 你可以假设 beginWord 和 endWord 是非空的,且二者不相同。 class Solution: def findLadders(self, beginWord, ...
from typing import List class Solution: def containsNearbyDuplicate(self, nums: List[int], k: int) -> bool: # 判断存在重复元素的索引之差小于某个数 # 先判断 nums [i] = nums [j] # 然后判断索引值是否相等,所以索引值可以用 map 存起来。 size = len(nums) if size == 0: return False map = dict() ...
# 130. 被围绕的区域 # 给定一个二维的矩阵,包含 'X' 和 'O'(字母 O)。 # 找到所有被 'X' 围绕的区域,并将这些区域里所有的 'O' 用 'X' 填充。 # https://segmentfault.com/a/1190000012898131 class Solution: def solve(self, board): """ :type board: List[List[str]] :rtype: void Do not return anything, modify board in-place instead. """ ...
from typing import List class Solution: def letterCasePermutation(self, S: str) -> List[str]: size = len(S) if size == 0: return [] res = [] arr = list(S) self.__dfs(arr, size, 0, res) return res def __dfs(self, arr, size, index, res): if ...
# 219. 存在重复元素 II # 给定一个整数数组和一个整数 k, # 判断数组中是否存在两个不同的索引 i 和 j, # 使得 nums [i] = nums [j],并且 i 和 j 的差的绝对值最大为 k。 class Solution: def containsNearbyDuplicate(self, nums, k): """ :type nums: List[int] :type k: int :rtype: bool """
# 154. 寻找旋转排序数组中的最小值 II # 假设按照升序排序的数组在预先未知的某个点上进行了旋转。 # ( 例如,数组 [0,1,2,4,5,6,7] 可能变为 [4,5,6,7,0,1,2] )。 # 请找出其中最小的元素。 # 注意数组中可能存在重复的元素。 from typing import List class Solution: def findMin(self, nums: List[int]) -> int: size = len(nums) # 根据题意,没有必要单独判断 size = 0 的情况 left = 0 right =...
# Definition for a binary tree node. class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = None class Solution(object): def buildTree(self, preorder, inorder): """ :type preorder: List[int] :type inorder: List[int] :rt...
# 95. 不同的二叉搜索树 II # 给定一个整数 n,生成所有由 1 ... n 为节点所组成的二叉搜索树。 # # 示例: # # 输入: 3 # 输出: # [ # [1,null,3,2], # [3,2,null,1], # [3,1,null,null,2], # [2,1,3], # [1,null,2,null,3] # ] # 解释: # 以上的输出对应以下 5 种不同结构的二叉搜索树: # # 1 3 3 2 1 # \ / / / \ \ # 3 2 1 1...
class Solution: def integerBreak(self, n): if n == 2: return 1 if n == 3: return 2 if n == 4: return 4 res = 1 while n > 4: res *= 3 n -= 3 res *= n return res if __name__ == '__main__': n = 10...
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None # 使用 dfs 来解决 # 113. 路径总和 II # 给定一个二叉树和一个目标和,找到所有从根节点到叶子节点路径总和等于给定目标和的路径。 # 解法 1 和 解法 2 是一回事。 class Solution(object): def pathSum(self, root, sum...
# 33. 搜索旋转排序数组 # 假设按照升序排序的数组在预先未知的某个点上进行了旋转。 # # ( 例如,数组 [0,1,2,4,5,6,7] 可能变为 [4,5,6,7,0,1,2] )。 # # 搜索一个给定的目标值,如果数组中存在这个目标值,则返回它的索引,否则返回 -1 。 # # 你可以假设数组中不存在重复的元素。 # # 你的算法时间复杂度必须是 O(log n) 级别。 from typing import List # 中间元素和右边界比较 class Solution: def search(self, nums: List[int], target: int) -> int: siz...
class Solution: # 代码有错误,要考虑的边界条件有点复杂,因此不考虑 def searchMatrix(self, matrix, target): # 特判 rows = len(matrix) if rows == 0: return False cols = len(matrix[0]) if cols == 0: return False # 起点:左下角 x = rows - 1 y = 0 ...
# 130. 被围绕的区域 # 给定一个二维的矩阵,包含 'X' 和 'O'(字母 O)。 # 找到所有被 'X' 围绕的区域,并将这些区域里所有的 'O' 用 'X' 填充。 # https://segmentfault.com/a/1190000012898131 class Solution: def solve(self, board): """ :type board: List[List[str]] :rtype: void Do not return anything, modify board in-place instead. """ ...
import gzip import cPickle import numpy as np def load_data(): """Opens the file containing the MNIST data set and returns it in a format to be modified by the load_data_wrapper function. """ f = gzip.open('../data/mnist.pkl.gz', 'rb') training_data, validation_data, test_data = cPickle.lo...
def LipYear(y): if ((y % 400 == 0) or (y % 100 != 0) and (y % 4 == 0)): return "its a leap year"; else: return "its not a leap year"; # Driver code if __name__ == '__main__': year = int(input("Enter a year: ")); print(LipYear(year)); ''' [10: 49AM] TejasChokshi y...
#!env python ''' Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be: 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ... By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-va...
from copy import copy, deepcopy def main(): file1 = open('input.txt', 'r') lst = [] while True: line = file1.readline() if not line: break lst.append(int(line)) max_elem = max(lst) lst.append(0) lst.append(max_elem + 3) lst = sorted(lst)...
def count_trees(right, down): lst = [] file1 = open('input.txt', 'r') while True: line = file1.readline() if not line: break lst.append(line) col = right row = down count = 0 while row < len(lst): if lst[row][col] == '#': ...
from copy import copy, deepcopy from enum import Enum class Direction(Enum): EAST = 'east' WEST = 'west' NORTH = 'north' SOUTH = 'south' north = 'N' south = 'S' east = 'E' west = 'W' forward = 'F' right = 'R' left = 'L' def turn_right(degrees, waypoint_x, waypoint_y): if degrees...
""" A year is a leap year if it is divisible by 4, except that years divisible by 100 are not leap years unless they are also divisible by 400. Ask the user to enter a year, and, using the // operator, determine how many leap years there have been between 1600 and that year. """ thatYear = eval(input("enter that yea...
import sys from itertools import cycle, izip KEY = 's3cr3t' # method from: https://dustri.org/b/elegant-xor-encryption-in-python.html def encrypt(message): return(''.join(chr(ord(c)^ord(k)) for c,k in izip(message, cycle(KEY)))) def main(argv): if len(argv) == 0: print("Error! No argument(s) specifie...