text stringlengths 37 1.41M |
|---|
import re;
import random;
def removeExtraApostropheS(movie_title,tokenized_list):
'''Function removes extra 's' appearing as word in the tokenized list'''
original_words = len(movie_title.split()); # original words in the movie title - space separated
tokenized_words = len(tokenized_list); # get the total words i... |
"""
Scales are first-order functions that take an index as argument,
and return the distance in semitones from the root.
Modular arithmetic is used, so there is no limit to the index you may request.
"""
def chromatic(i):
return i
def major(i):
j=i%7
k=i//7
scale = [0,2,4,5,7,9,11]
return k*12 + scale[... |
#! /usr/bin/env python3
import numpy as np
list1 = []
print("Enter the values")
while 1:
data=input() # for only integer data possible
try:
list1.append(int(data))
except:
break
size=len(list1)
print(size)
n1=size**.5
n2=np.ceil(n1)
print(n2)
for i in range(2,... |
#not done. This needs a bit more work
#only thing that needs to be done is to figure out matching and fix Clue's print function
#this is a class to define a full puzzle. It's got a list of clues (which themselves
# store their connections to other clues), a solve function, and a print function
# so that basically all ... |
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from datetime import datetime
birddata = pd.read_csv("bird_tracking.csv", index_col=0)
#Exercise 1
# First, use `groupby()` to group the data by "bird_name".
grouped_birds = birddata.groupby('bird_name')
# Now calculate the mean of `... |
def fibo(n):
if n==0:
print("Digit should be greater than 0.")
elif n==1:
return 0
elif n==2:
return 1
else:
return fibo(n-1)+fibo(n-2)
n = int(input("Enter the digit upto which you want to find fibnacci series: "))
l = list()
l=[str(fibo(i)) for i in range(1,n+1)]
s = ",".join(l)
prin... |
import player as P
class Game:
def __init__(self, numShips):
"""
Initializes the game
:param numShips: The number of ships players start with
"""
self.win = False
self.numShips = numShips;
self.player1 = P.Player()
self.player2 = P.Player... |
message = "One of Python's"
print(message)
print(3 ** 2)
# 创建列表
name = ['ricardo', 'bob', 'lucc']
print(name)
# 向列表末尾添加数据
name.append('walter')
print(name)
# 向列表0位置增加数据
name.insert(0, 'nazz')
print(name)
# 删除一条数据
del name[0]
print(name)
# 删除末尾数据
name.pop()
print(name)
# 按值删除
name.remove('bob')
# 临时排序 sorted
print(sort... |
# -*- coding: utf-8 -*-
"""
Created on Tue Nov 5 21:54:31 2019
Assignment 1 Prob 3
Fibonacci sequence
@author: CHINTAN
"""
s=[1,1]
for i in range(2,10):
s.append(s[i-1]+s[i-2])
print(s)
|
import random
moves = ["rock", "paper", "scissor"]
keep_playing = True
while keep_playing:
cmove = random.choice(moves)
pmove = input("You are about to start Rock, Paper and Scissor game. Please enter your input: ")
if cmove == pmove:
print('Tie')
elif pmove == 'rock' and cmove == 'scissor':
... |
file='input.txt'
fhand=open(file,"r")
full_txt=fhand.read()
words=full_txt.split()
print(words)
words.sort()
print('Sorted list', words)
print([ (i,words.count(i)) for i in set(words) ])
|
a=[5, 10, 15, 20, 25]
l = len(a)
print("The first element of the list is",a[0],"and the last element of the list is",a[l-1])
b=[a[0],a[l-1]]
print("The new list is: ",b)
|
# 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 levelOrderBottom(self, root):
"""
:type root: TreeNode
:rtype: List[List[int]]
"""
... |
#Deleting different dictionary elements
dict1={"student1":"madhuri","student2":"diya","student3":"karthik"}
dict2={"id":int("234"),"roll":int("2"),"phoneno":int("1234567898")}
dict3={"branch1":"ECE","branch2":"CSE","branch3":"IT"}
#Deleting Specific element
del dict1["student3"]
dict2.pop("roll")
print(dict1)
print(dic... |
import sqlite3
with sqlite3.connect("blog_posts.db") as connection:
c = connection.cursor()
c.execute('DROP TABLE posts')
c.execute('CREATE TABLE posts(title TEXT, description TEXT)')
c.execute('INSERT INTO posts VALUES("Lorem Ispum", "Lorem Ipsum dolor sit amet."(')
c.execute('INSERT INTO posts V... |
#!/usr/bin/env python
import sys
import os.path
import os
import csv
import glob
from pandas import DataFrame, Series
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
from sklearn import datasets, linear_model
from sklearn.discriminant_analysis import LinearDiscriminantAnalysis
import scipy.stats... |
#多进程
"""
Unix/Linux操作系统提供了一个fork()系统调用,它非常特殊。
普通的函数调用,调用一次,返回一次,但是fork()调用一次,返回两次,
因为操作系统自动把当前进程(称为父进程)复制了一份(称为子进程),
然后,分别在父进程和子进程内返回。
子进程永远返回0,而父进程返回子进程的ID。
这样做的理由是,一个父进程可以fork出很多子进程,所以,父进程要记下每个子进程的ID,
而子进程只需要调用getppid()就可以拿到父进程的ID。
Python的os模块封装了常见的系统调用,其中就包括fork,可以在Python程序中轻松创建子进程
"""
"""
import os
print('Process... |
#Automatas
def a_int(src):
s = 1
for c in src:
if s == 1 and c == "i":
s = 2
elif s == 2 and c == "n":
s = 3
elif s == 3 and c == "t":
s = 4
else:
s = -1
break
return s == 4
def a_float(src):
s =... |
from holes import Hole, Rumba
class Board:
def __init__(self, num_holes):
# Rumba MUST BE zeroth element of self.holes
self.holes = [Rumba() if i == 0 else Hole()
for i in range(num_holes)]
def _harvest(self, hole_index):
hole = self.holes[hole_index]
se... |
#P08_PythonProject_10
HargaBuah = {'apel' : 5000,
'jeruk' : 8500,
'mangga' : 7800,
'duku' : 6500}
dataBuah =[]
i = 1
nama = str(input('Nama buah yang dibeli :'))
kg = int(input('Berapa Kg :'))
print()
try:
harga = HargaBuah[nama]
TotalHarga = harga*kg
dataBuah.append... |
#P08_PythonProject_2
def dataStat(x):
a = sum(x)/len(x)
b = max(x)
c = min(x)
dataABC = [a,b,c]
return dataABC
while True:
n = int(input('Masukkan banyak angka:'))
break
Nilai = []
i = 0
while(i < n):
angka = int(input('Masukkan angka yang diinginkan:'))
Nilai.append(angka)
... |
kode_karyawan = int(input('Masukkan Kode Karyawan :'))
nama_karyawan = input('Masukkan Nama Karyawan:')
golongan = input('Masukkan Golongan:')
print('====================================')
print('STRUK RINCIAN GAJI KARYAWAN')
print('------------------------------------')
print('Nama Karyawan :' + nama_karyawan + '(... |
name = input('What is your name? ')
lenth_is = (len(name))
if lenth_is < 3:
print('Name must be at least 3 characters.')
print('Try again.')
elif lenth_is > 50 :
print ('Name can be a max of 50 characters.')
else :
print('Name looks good.')
|
course = '''
Good morning,
Thanks for your email, we will get back to you as soon as we can.
Regards,
Miguel
CEO
'''
test2 = (course[:])
test3 = (test2 * 100)
name = 'Jennifer'
last = 'Perez'
msg = name + ' ' + last
print (msg)
message = f'{name} [{last}] is a coder.'
print (message)
message2 = name + (name[0])+... |
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.linear_model import LogisticRegression
inputFile = 'MoviesDataset.csv'
# Using panda to import the csv file and separate the summaries from the sentiments
# header=... |
for x in range(0, 151, 1):
print(x)
for i in range(5, 1005, 5):
print(i)
for i in range(0, 100, 1):
if i % 10 == 0:
print("Coding Dojo")
elif i % 5 == 0:
print("coding")
sum = 0
for i in range(0, 500001, 1):
if i % 2 == 1:
sum += i
print(i, sum)
for i in rang... |
import urllib.request
# urllib.request is a Python module for fetching URLs (Uniform Resource Locators).
from bs4 import BeautifulSoup
# Beautiful Soup is a Python library for pulling data out of HTML and XML files. It works with your favorite parser to provide idiomatic ways of navigating, searching, and modifying th... |
import numpy as np
def generate_matrix(m, n):
Z = np.random.randint(0, 100, (m, n))
# Matrix for testing
"""
Z = np.array([
(1, 2, 3, 5),
(2, 1, 2, 3),
(3, 2, 1, 2),
(4, 3, 2, 1),
(5, 4, 3, 2)
])
"""
print(Z)
return Z
def is_toepl... |
"""
Desenvolva um programa que leia o comprimento de três retas e diga ao usuário se elas podem ou não formar
um triângulo.
"""
reta_1 = float(input("Digite o comprimento da primeira reta: "))
reta_2 = float(input("Digite o comprimento da segunda reta: "))
reta_3 = float(input("Digite o comprimento da terceira reta: ")... |
"""
Faça um programa que leia três números e mostre qual é o maior e qual é o menor.
"""
"""
numero_1 = float(input("Digite o primeiro número: "))
numero_2 = float(input("Digite o segundo número: "))
numero_3 = float(input("Digite o terceiro número: "))
if numero_1 > numero_2 and numero_1 > numero_3:
print("numer... |
"""
Escreva um programa que pergunte a quantidade de Km percorrido por um carro alugado e a quantidade de dias pelos
quais ele foi alugado. Calcule o preço a pagar, sabendo que o carro custa R$60 por dia e R$0,15 por Km rodado.
"""
dias = int(input("Digite quantos dias você ficou com o carro: "))
km = float(input("Digi... |
"""
Crie um programa que leia vários números inteiros pelo teclado. No final da execução, mostre a média entre todos os
valores e qual foi o maior e o menor valores lidos. O programa deve perguntar ao usuário se ele quer ou não continuar
a digitar valores.
"""
maior = 0
menor = 0
soma = 0
media = 0
contador = 0
respost... |
"""
Crie um programa que leia o nome de uma pessoa e diga se ela tem "SILVA no nome.
"""
nome = str(input("Digite o seu nome:\n").strip().upper())
print("O seu nome {} tem 'SILVA' contido nele? {}".format(nome, "SILVA" in nome))
|
"""
Crie um programa que leia duas notas de um aluno e calcule sua média, mostrando uma mensagem no final, de acordo com a
média atingida:
- Média abaixo de 5.0:
REPROVADO
- Média entre 5.0 e 6.9:
RECUPERAÇÃO
-Média 7.0 ou superior:
APROVADO
"""
nota_1 = float(input("Digite a primeira nota: "))
nota_2 = flo... |
"""
Desenvolva um programa que leia o primeiro termo e a razão de uma PA. No final mostre os 10 primeiros termos
dessa progressão.
"""
"""
a1 = int(input("Digite o primeiro termo: "))
a2 = int(input("Digite a razão de uma PA: "))
pa = a1
if a1 > 0 or a1 == 0:
for numero in range(1, 10 + 1):
print(pa, end=" ... |
"""
Faça um programa que leia o comprimento do cateto oposto e do cateto adjacente de um triângulo retângulo, calcule
e mostre o comprimento da hipotesusa.
"""
"""
co = float(input("Comprimento do cateto oposto: "))
ca = float(input("Comprimento do cateto adjacente: "))
hi = ((co ** 2) + (ca ** 2)) ** (1/2)
print('A hi... |
# Copy File
# Choose My Type file
# Choose Local Disk
# print(' Do you want to keep stealing files? ')
# print(' if you want to Choose [1]')
# print(" if you dont want to Choose [2]")
# T2 = str(input('Choose [1] or [2] : '))
# if ('1' or '[1]') in T2 :
# B = str(input('Enter Local path fi... |
"""
Dado um número inteiro não negativo n, determinar n!
Exemplo:
5! = 5*4*3*2*1
3! = 3*2*1
# Usando exemplo decrementando:
# Início
num = int(input("Digite um número: "))
# Vamos supor que num=4, cont seria cont=4-1, ou seja, cont=3
cont = num - 1
# Será uma variável auxiliar que ficará sendo decrementada e... |
"""
Dada uma sequência de números inteiros não nulos,
finalize a lista em 0, imprimir quadrados.
"""
num = int(input("Digite o primeiro número: "))
while num != 0:
print(num,"ao quadrado =",num*num)
num = int(input("Digite o próximo número: "))
if num == 0:
print("Valor nulo. Finalizando programa!!") |
"""
Faça um programa para um caixa eletrônico. O programa deverá perguntar
ao usuário o valor do saque e depois informar quantas notas de cada
valor serão fornecidas.
As notas disponíveis serão às de 1, 5, 10, 50 e 100 reais.
O valor mínimo é de 10 reais e o máximo de 600 reais.
O programa não deve se preocupar com a q... |
num1, num2 = 15,10
print("x =",num1)
print("y =",num2)
print(num1,"+",num2,"=",num1+num2)
print(num1,"-",num2,"=",num1-num2)
print(num1,"/",num2,"=",num1/num2)
print(num1,"//",num2,"=",num1//num2)
print(num1,"resto",num2,"=",num1%num2) |
"""
Faça um programa que leia três números e mostre-os em ordem
decrescente
"""
num1 = int(input("Digite o primeiro número: "))
num2 = int(input("Digite o segundo número: "))
num3 = int(input("Digite o terceiro número: "))
if num1 >= num2 >= num3:
print(num1, num2, num3)
elif num1 >= num3 >= num2:
print(num1, ... |
from tkinter import *
from PIL import Image,ImageTk
window=Tk()
window.geometry('500x500')
window.title('Registration Form')
# root=Tk()
# root.geometry('500x500')
# root.title('Registration Form2')
width = 100
height = 100
img=Image.open("D:/Python/tikinter/clipart.jpg")
img = img.resize((width,height),... |
# -*- coding: utf-8 -*-
"""
Created on Thu Jul 25 12:59:17 2019
@author: AShete
"""
# implementation of switch case
# Using Dictionary
def add_nums(a,b):
return a+b
def sub_nums(a,b):
return a-b
def mul_nums(a,b):
return a*b
def div_nums(a,b):
return a/b
def default():
return "Invalid Inpu... |
"""
Stop and think: words with which prefix should you remove from tweets?
#, @?
"""
import re #regular expressions module
# Define abbreviations
# as regular expressions together with their expansions
# (\b marks the word boundary):
re_repl = {
r"\br\b": "are",
r"\bu\b": "you",
r"\bhaha\b": "ha",
r"\b... |
def berechneUrlaubsanspruch():
if alter <18:
urlaubsanspruch=30
elif alter <55:
urlaubsanspruch=26
else:
urlaubsanspruch=28
if behinderung==1:
urlaubsanspruch=urlaubsanspruch+5
else:
urlaubsanspruch=urlaubsanspruch
if beschäftigungsläner<=1... |
from enum import Enum
class SideType(Enum):
TYPE_WIDTH = 'width'
TYPE_HEIGHT = 'height'
class RightAngleShape:
def set_side(self, size, side):
pass
def area_of(self):
pass
class Rectangle(RightAngleShape):
def __init__(self, width, height):
self.width = width
s... |
class Floor:
def __init__(self):
self.name = 'floor'
def build(self):
print(f'Build {self.name}')
class Ceiling:
def __init__(self):
self.name = 'ceiling'
def build(self):
print(f'Build {self.name}')
class Wall:
def __init__(self):
self.name = 'wall'
... |
'''
589. N-ary Tree Preorder Traversal
Easy
Given the root of an n-ary tree, return the preorder traversal of its nodes' values.
Nary-Tree input serialization is represented in their level order traversal. Each group of children is separated by the null value (See examples)
Example 1:
Input: root = [1,null,3,2... |
'''
382. Linked List Random Node
Medium
Given a singly linked list, return a random node's value from the linked list. Each node must have the same probability of being chosen.
Follow up:
What if the linked list is extremely large and its length is unknown to you? Could you solve this efficiently without using extra ... |
'''
1345. Jump Game IV
Hard
Given an array of integers arr, you are initially positioned at the first index of the array.
In one step you can jump from index i to index:
i + 1 where: i + 1 < arr.length.
i - 1 where: i - 1 >= 0.
j where: arr[i] == arr[j] and i != j.
Return the minimum number of steps to reach the las... |
'''
754. Reach a Number
Medium
You are standing at position 0 on an infinite number line. There is a goal at position target.
On each move, you can either go left or right. During the n-th move (starting from 1), you take n steps.
Return the minimum number of steps required to reach the destination.
Example 1:
Inpu... |
'''
1448. Count Good Nodes in Binary Tree
Medium
Given a binary tree root, a node X in the tree is named good if in the path from root to X there are no nodes with a value greater than X.
Return the number of good nodes in the binary tree.
Example 1:
Input: root = [3,1,4,3,null,1,5]
Output: 4
Explanation: Node... |
'''
47. Permutations II
Medium
Given a collection of numbers, nums, that might contain duplicates, return all possible unique permutations in any order.
Example 1:
Input: nums = [1,1,2]
Output:
[[1,1,2],
[1,2,1],
[2,1,1]]
https://leetcode.com/problems/permutations-ii/
'''
class Solution:
def permuteUnique(... |
'''
991. Broken Calculator
Medium
On a broken calculator that has a number showing on its display, we can perform two operations:
Double: Multiply the number on the display by 2, or;
Decrement: Subtract 1 from the number on the display.
Initially, the calculator is displaying the number X.
Return the minimum number ... |
'''
816. Ambiguous Coordinates
Medium
We had some 2-dimensional coordinates, like "(1, 3)" or "(2, 0.5)". Then, we removed all commas, decimal points, and spaces, and ended up with the string s. Return a list of strings representing all possibilities for what our original coordinates could have been.
Our original r... |
'''
988. Smallest String Starting From Leaf
Medium
Given the root of a binary tree, each node has a value from 0 to 25 representing the letters 'a' to 'z': a value of 0 represents 'a', a value of 1 represents 'b', and so on.
Find the lexicographically smallest string that starts at a leaf of this tree and ends at the... |
'''
690. Employee Importance
Easy
You are given a data structure of employee information, which includes the employee's unique id, his importance value and his direct subordinates' id.
For example, employee 1 is the leader of employee 2, and employee 2 is the leader of employee 3. They have importance value 15, 10 an... |
'''
44. Wildcard Matching
Hard
Given an input string (s) and a pattern (p), implement wildcard pattern matching with support for '?' and '*'.
'?' Matches any single character.
'*' Matches any sequence of characters (including the empty sequence).
The matching should cover the entire input string (not partial).
Note:... |
'''
1649. Create Sorted Array through Instructions
Hard
Given an integer array instructions, you are asked to create a sorted array from the elements in instructions. You start with an empty container nums. For each element from left to right in instructions, insert it into nums. The cost of each insertion is the mini... |
'''
735. Asteroid Collision
Medium
We are given an array asteroids of integers representing asteroids in a row.
For each asteroid, the absolute value represents its size, and the sign represents its direction (positive meaning right, negative meaning left). Each asteroid moves at the same speed.
Find out the state o... |
'''
124. Binary Tree Maximum Path Sum
Hard
Given a non-empty binary tree, find the maximum path sum.
For this problem, a path is defined as any sequence of nodes from some starting node to any node in the tree along the parent-child connections. The path must contain at least one node and does not need to go through ... |
'''
1365. How Many Numbers Are Smaller Than the Current Number
Easy
Given the array nums, for each nums[i] find out how many numbers in the array are smaller than it. That is, for each nums[i] you have to count the number of valid j's such that j != i and nums[j] < nums[i].
Return the answer in an array.
Example ... |
'''
946. Validate Stack Sequences
Medium
Given two sequences pushed and popped with distinct values, return true if and only if this could have been the result of a sequence of push and pop operations on an initially empty stack.
Example 1:
Input: pushed = [1,2,3,4,5], popped = [4,5,3,2,1]
Output: true
Explanatio... |
# Definition for a binary tree node.
'''
1339. Maximum Product of Splitted Binary Tree
Medium
Given the root of a binary tree, split the binary tree into two subtrees by removing one edge such that the product of the sums of the subtrees is maximized.
Return the maximum product of the sums of the two subtrees. Since ... |
'''
23. Merge k Sorted Lists
Hard
You are given an array of k linked-lists lists, each linked-list is sorted in ascending order.
Merge all the linked-lists into one sorted linked-list and return it.
Example 1:
Input: lists = [[1,4,5],[1,3,4],[2,6]]
Output: [1,1,2,3,4,4,5,6]
Explanation: The linked-lists are:
[
... |
'''
594. Longest Harmonious Subsequence
Easy
We define a harmonious array as an array where the difference between its maximum value and its minimum value is exactly 1.
Given an integer array nums, return the length of its longest harmonious subsequence among all its possible subsequences.
A subsequence of array is ... |
'''
390. Elimination Game
Medium
There is a list of sorted integers from 1 to n. Starting from left to right, remove the first number and every other number afterward until you reach the end of the list.
Repeat the previous step again, but this time from right to left, remove the right most number and every other num... |
'''
60. Permutation Sequence
Medium
Share
The set [1,2,3,...,n] contains a total of n! unique permutations.
By listing and labeling all of the permutations in order, we get the following sequence for n = 3:
"123"
"132"
"213"
"231"
"312"
"321"
Given n and k, return the kth permutation sequence.
Note:
Given n will b... |
'''
1332. Remove Palindromic Subsequences
Easy
Given a string s consisting only of letters 'a' and 'b'. In a single step you can remove one palindromic subsequence from s.
Return the minimum number of steps to make the given string empty.
A string is a subsequence of a given string, if it is generated by deleting so... |
'''
456. 132 Pattern
Medium
Given a sequence of n integers a1, a2, ..., an, a 132 pattern is a subsequence ai, aj, ak such that i < j < k and ai < ak < aj. Design an algorithm that takes a list of n numbers as input and checks whether there is a 132 pattern in the list.
Note: n will be less than 15,000.
Example 1:
I... |
'''
99. Recover Binary Search Tree
Hard
Two elements of a binary search tree (BST) are swapped by mistake.
Recover the tree without changing its structure.
Example 1:
Input: [1,3,null,null,2]
1
/
3
\
2
Output: [3,1,null,null,2]
3
/
1
\
2
https://leetcode.com/problems/recover-binary-search-... |
'''
474. Ones and Zeroes
Medium
You are given an array of binary strings strs and two integers m and n.
Return the size of the largest subset of strs such that there are at most m 0's and n 1's in the subset.
A set x is a subset of a set y if all elements of x are also elements of y.
Example 1:
Input: strs = ["... |
'''
916. Word Subsets
Medium
We are given two arrays A and B of words. Each word is a string of lowercase letters.
Now, say that word b is a subset of word a if every letter in b occurs in a, including multiplicity. For example, "wrr" is a subset of "warrior", but is not a subset of "world".
Now say a word a from ... |
'''
1313. Decompress Run-Length Encoded List
Easy
We are given a list nums of integers representing a list compressed with run-length encoding.
Consider each adjacent pair of elements [freq, val] = [nums[2*i], nums[2*i+1]] (with i >= 0). For each such pair, there are freq elements with value val concatenated in a su... |
'''
36. Valid Sudoku
Medium
Determine if a 9 x 9 Sudoku board is valid. Only the filled cells need to be validated according to the following rules:
Each row must contain the digits 1-9 without repetition.
Each column must contain the digits 1-9 without repetition.
Each of the nine 3 x 3 sub-boxes of the grid must co... |
'''
430. Flatten a Multilevel Doubly Linked List
Medium
You are given a doubly linked list which in addition to the next and previous pointers, it could have a child pointer, which may or may not point to a separate doubly linked list. These child lists may have one or more children of their own, and so on, to produce... |
'''
231. Power of Two
Easy
Given an integer, write a function to determine if it is a power of two.
Example 1:
Input: 1
Output: true
Explanation: 20 = 1
https://leetcode.com/problems/power-of-two/
'''
class Solution:
def isPowerOfTwo(self, n: int) -> bool:
if n == 0 :
return False
b... |
'''
1658. Minimum Operations to Reduce X to Zero
Medium
You are given an integer array nums and an integer x. In one operation, you can either remove the leftmost or the rightmost element from the array nums and subtract its value from x. Note that this modifies the array for future operations.
Return the minimum num... |
'''
190. Reverse Bits
Easy
Reverse bits of a given 32 bits unsigned integer.
Example 1:
Input: 00000010100101000001111010011100
Output: 00111001011110000010100101000000
Explanation: The input binary string 00000010100101000001111010011100 represents the unsigned integer 43261596, so return 964176192 which its bin... |
'''
713. Subarray Product Less Than K
Medium
Your are given an array of positive integers nums.
Count and print the number of (contiguous) subarrays where the product of all the elements in the subarray is less than k.
Example 1:
Input: nums = [10, 5, 2, 6], k = 100
Output: 8
Explanation: The 8 subarrays that have p... |
'''
880. Decoded String at Index
Medium
An encoded string S is given. To find and write the decoded string to a tape, the encoded string is read one character at a time and the following steps are taken:
If the character read is a letter, that letter is written onto the tape.
If the character read is a digit (say d)... |
'''
169. Majority Element
Easy
Given an array of size n, find the majority element. The majority element is the element that appears more than ⌊ n/2 ⌋ times.
You may assume that the array is non-empty and the majority element always exist in the array.
Example 1:
Input: [3,2,3]
Output: 3
https://leetcode.com/probl... |
'''
1039. Minimum Score Triangulation of Polygon
Medium
Share
Given N, consider a convex N-sided polygon with vertices labelled A[0], A[i], ..., A[N-1] in clockwise order.
Suppose you triangulate the polygon into N-2 triangles. For each triangle, the value of that triangle is the product of the labels of the vertice... |
'''
140. Word Break II
Hard
Given a non-empty string s and a dictionary wordDict containing a list of non-empty words, add spaces in s to construct a sentence where each word is a valid dictionary word. Return all such possible sentences.
Note:
The same word in the dictionary may be reused multiple times in the segm... |
'''
154. Find Minimum in Rotated Sorted Array II
Hard
Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand.
(i.e., [0,1,2,4,5,6,7] might become [4,5,6,7,0,1,2]).
Find the minimum element.
The array may contain duplicates.
Example 1:
Input: [1,3,5]
Output: 1
https://leet... |
'''
394. Decode String
Given an encoded string, return its decoded string.
The encoding rule is: k[encoded_string], where the encoded_string inside the square brackets is being repeated exactly k times. Note that k is guaranteed to be a positive integer.
You may assume that the input string is always valid; No extra... |
'''
201. Bitwise AND of Numbers Range
Medium
Given a range [m, n] where 0 <= m <= n <= 2147483647, return the bitwise AND of all numbers in this range, inclusive.
Example 1:
Input: [5,7]
Output: 4
https://leetcode.com/problems/bitwise-and-of-numbers-range/
'''
class Solution:
def rangeBitwiseAnd(self, m: int, n... |
'''
95. Unique Binary Search Trees II
Medium
Given an integer n, return all the structurally unique BST's (binary search trees), which has exactly n nodes of unique values from 1 to n. Return the answer in any order.
Example 1:
Input: n = 3
Output: [[1,null,2,null,3],[1,null,3,2],[2,1,3],[3,1,null,null,2],[3,2,n... |
'''
1026. Maximum Difference Between Node and Ancestor
Medium
Given the root of a binary tree, find the maximum value V for which there exist different nodes A and B where V = |A.val - B.val| and A is an ancestor of B.
A node A is an ancestor of B if either: any child of A is equal to B, or any child of A is an ances... |
'''
589. N-ary Tree Preorder Traversal
Easy
Given an n-ary tree, return the preorder traversal of its nodes' values.
For example, given a 3-ary tree:
Return its preorder traversal as: [1,3,5,6,2,4].
Note:
Recursive solution is trivial, could you do it iteratively?
https://leetcode.com/problems/n-ary-tree-preorder... |
'''
463. Island Perimeter
Easy
You are given a map in form of a two-dimensional integer grid where 1 represents land and 0 represents water.
Grid cells are connected horizontally/vertically (not diagonally). The grid is completely surrounded by water, and there is exactly one island (i.e., one or more connected land ... |
'''
143. Reorder List
Medium
Given a singly linked list L: L0→L1→…→Ln-1→Ln,
reorder it to: L0→Ln→L1→Ln-1→L2→Ln-2→…
You may not modify the values in the list's nodes, only nodes itself may be changed.
Example 1:
Given 1->2->3->4, reorder it to 1->4->2->3.
https://leetcode.com/problems/reorder-list/
'''
# Definition... |
'''
966. Vowel Spellchecker
Medium
Given a wordlist, we want to implement a spellchecker that converts a query word into a correct word.
For a given query word, the spell checker handles two categories of spelling mistakes:
Capitalization: If the query matches a word in the wordlist (case-insensitive), then the quer... |
'''
404. Sum of Left Leaves
Easy
Find the sum of all left leaves in a given binary tree.
Example:
3
/ \
9 20
/ \
15 7
There are two left leaves in the binary tree, with values 9 and 15 respectively. Return 24.
https://leetcode.com/problems/sum-of-left-leaves/
'''
# Definition for a binary tree ... |
for i in range(0,100):
if i % 15 == 0:
print "beep boop"
elif i % 5 == 0:
print "boop"
elif i % 3 == 0:
print "beep"
else:
print i |
a=input(" ")
b=a[::-1]
if (a==b):
print("yes")
else:
print("no")
|
from math import pi
var1=10
def greeting(x,y):
z="Hello, "+x+" "+y
return z
def sphere_volume(x):
x=float(x)
y=4/3*(pi)*(x**3)
return y
|
magicians = ["amy", "lucy", "jimmy"]
for magician in magicians:
print(magician)
"""
output:
amy
lucy
jimmy
"""
#Regular Errors:
#IndentationError: expected an indented block
#IndentationError: unexpected indent
#SyntaxError: invalid syntax
for value in range(1,5):
print(value)
# output : 1,2,3,4
# if we want the ... |
# Review for input() and while loop
message = raw_input("Tell me something, and I will repeat it back to you: ")
print(message)
name = raw_input("Please enter your name: ")
print("Hello, " + name + "!")
prompt = "If you tell us who you are, we can personalize the messages you see."
prompt += "\nWhat is your first na... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.