text stringlengths 5 121k |
|---|
fname = input("Enter file name: ")
fh = open(fname)
for line in fh:
cap = line.upper()
cap = cap.rstrip()
print(cap)
|
'''
Write a function:
def solution(A)
that, given an array A of N integers, returns the smallest positive integer (greater than 0) that does not occur in A.
For example, given A = [1, 3, 6, 4, 1, 2], the function should return 5.
Given A = [1, 2, 3], the function should return 4.
Given A = [−1, −3], the functi... |
class node:
def __init__(self,data):
self.data = data
self.next = None;
class Link_list:
def __init__(self):
self.start = None;
def make_node(self,value):
if(self.start==None):
self.start = node(value)
else:
temp = self.start
while... |
def f(x):
if abs(x)<=1:
if x==1:
return 1
if(x== -1):
return -1
if x==0:
return 0
else:
if x>0:
return f(x-1) + f(x-2)
if x<0:
return f(x+1) + f(x+2)
print (f(int(input()))) |
'''
A message containing letters from A-Z can be encoded into numbers using the following mapping:
'A' -> "1"
'B' -> "2"
...
'Z' -> "26"
To decode an encoded message, all the digits must be grouped then mapped back into letters using the reverse of the mapping above (there may be multiple ways). For example, "11106" c... |
'''
Given a binary tree, find its minimum depth.
The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node.
Note: A leaf is a node with no children.
'''
class Solution:
def minDepth(self, root: TreeNode) -> int:
if(root == None):
r... |
import pickle
from datetime import datetime
class atm:
def __init__(self, user):
self.transaction = ''
self.user = user
self.balance = 0
self.pin = input('Create a 4 digit pin: ')
with open('user_data.txt', 'r') as file:
account_number = file.read()
... |
import pygame
white = pygame.Color(255, 255, 255)
blue = pygame.Color(0, 0, 205)
yellow = pygame.Color(255, 255, 0)
black = pygame.Color(0, 0, 0)
green = pygame.Color(0, 100, 0)
red = pygame.Color(255, 0, 0)
class Rect(object):
def __init__(self, left, top, width, height):
self.left ... |
import re
string = "192.168.2.2"
m = re.match("([0-9]{1,3}\.){3}\d{1,3}", string)
print(m.group())
string2 = "Alex li"
m = re.search("[a-z]", string2, flags=re.I)
string2 = "alexi \nseven\bli"
m = re.search("^a.*$", string2, flags=re.M)
print(m.group())
phone_str = "hey my name is alex, and my phone number is 136... |
data = [[col for col in range(4,10)] for row in range(4,110)]
for i in data:
print(i)
print('')
for r_index,row in enumerate(data[0]):
print([data[c_index][r_index] for c_index in range(len(data))]) |
import decimal
from decimal import Decimal
borderLine = "///"*10
taxRate = Decimal('7.25')/Decimal(100)
purchaseAmount = Decimal('2.95')
penny = Decimal('0.01')
totalAmount = purchaseAmount+taxRate*purchaseAmount
totalAmount.quantize(penny, decimal.ROUND_UP)
print(totalAmount)
print(borderLine)
from fractions im... |
class Stk:
def __init__(self,size):
self.size = size
self.stk = []
def printStk(self):
print(self.stk)
def isEmpty(self):
if len(self.stk) == 0:
return "Empty"
else:
return "Not Empty"
def push(self,x):
self.stk.append(x)... |
import numpy as np
class LogisticRegression:
def __init__(self,lr=0.02,iter=10000):
self.lr = lr
self.iter = iter
def sigmoid(self, z):
return (1/(1 + np.exp(-z)))
def gradient_descent(self,y,x):
for i in range(self.iter):
yhat = self.sigmoid(np.dot(self.w.T,x)... |
"""
problem_5.py - BlockChain
build a link list to store basic blockchain data
the data in this example is just a random integer
"""
import hashlib
import time
class Block:
def __init__(self, timestamp, data, previous_hash):
self.timestamp = timestamp
self.data = data
self.previous_hash ... |
import pandas as pd
import sys
filepath = "Resources/budget_data.csv"
df = pd.read_csv(filepath)
total_month = len(df["Date"].unique())
total = df["Profit/Losses"].sum()
df2 = df["Profit/Losses"].diff()
average_change = df2.mean()
greatest_increase = df2.max()
greatest_decrease = df2.min()
df3 = df2.sort_valu... |
class Test():
class_var = "Class Variable"
class_var2 = "Class Variable2"
x = Test()
print(x.class_var)
print(x.class_var2)
class TestIns():
def __init__(self, name, age):
self.name = name
self.age = age
y = TestIns('Y', 9)
print(y.name)
print(y.age)
|
'''Invert a binary tree.'''
import __init__
from binarytree import BinaryTree
from treenode import TreeNode
from util.btutil import BinaryTreeUtil
class Invert:
def invertTree(self, root: TreeNode) -> TreeNode:
if root:
right = root.right
left = root.left
root.right ... |
"""Solution to trap the rain water."""
"""
Problem:
=======
Given n Non-negative integers representing an elevation map where the width of
each bar is 1, compute how much water it is able to trap after raining
"""
class TrapRainWater:
def trap(self, height):
left_hieghest = 0
right_hieghest = 0
... |
import os
import sys
def AddSysPath(new_path):
""" AddSysPath(new_path): adds a directory to python's sys.path
Does not add the directory if it doesnt exists or if its already on
sys.path. Return 1 if OK, -1 if new_path doesnt exists, 0 if it was already
on sys.path
"""
if not os.path.ex... |
"""Binary Tree util."""
from binarytree import BinaryTree
class BinaryTreeUtil:
def constructBinaryTree(self, btree: BinaryTree):
"""Construct the binary tree based on user input.
:param btree: Binary tree on which new nodes to be added
:type btree: BinaryTree
"""
while Tru... |
import sys
try:
superpower = input('Please input the heroes\' powers: ')
superpower = superpower.split(' ')
for i in range(len(superpower)):
if not int(superpower[i]):
raise ValueError
except ValueError:
print('Sorry, these are not valid power values.')
sys.exit()
try:
nb_... |
n = int(input ("Enter the number till which you want to find summation: "))
s=0
i=0
while i<=n:
if (i%3==0)or(i%7==0):
i+=1
continue
else:
s=s+i
i=i+1
print("sum is: ", s)
|
def digitTreeSum(t):
if not t:
return 0
stack = [(t, 0)]
sum = 0
while stack:
cur, v = stack.pop()
if cur.left or cur.right:
if cur.left:
stack.append((cur.left, cur.value + v * 10))
if cur.right:
stack.append((cur.right, cu... |
PetInfo = {
"name":"Puchy",
"age":8,
"hobby":["eating","walking","sleeping"],
"woke":{
"monday":"10am",
"tuesday":"9am",
"wednesday":"11am"
}
}
print(f'My pet´s name is {PetInfo["name"]} and he is {PetInfo["age"]} years old.')
print(f'My pet has {len(PetInfo["hobby"])} hob... |
from decimal import Decimal as decimal
kg = float(input('あなたの体重を入力してください'))
height = (input('あなたの身長を入力してください'))
if '.' not in height:
height = int(height) / 100
elif '.' in height:
height = float(height)
print(kg)
print(height)
BMI = kg / (height ** 2)
BMI = decimal(BMI).quantize(decimal('0.01'))
print(BMI)... |
from decimal import Decimal as decimal
def base_body_data():
while True:
try:
print('性別を入力してください')
gender = int(input('[0. 男性 1. 女性]'))
if gender != 0 and gender != 1:
print('適切な値を入力してください')
continue
break
except:
... |
"""Implementing the tail shell command in python."""
"""The import statement the import sys imports the library sys from the module along with the functions and methods of the library system"""
import sys
"""... from the lib.helper module we are importing the built in functions tail and readfile of the lib-helper mod... |
from random import choice
players = []
players.append = (input ("Enter the name of the Player:"))
players.append = (input ("Enter the name of the Player:"))
players.append = (input ("Enter the name of the Player:"))
players.append = (input ("Enter the name of the Player:"))
players.append = (input ("Enter the name... |
import math
allBrown = []
def brown(m,n):
brownMid = []
nResult = math.factorial(n) + 1
mResult = pow(m,2)
if mResult == nResult:
brownMid.append(m)
brownMid.append(n)
if brownMid:
allBrown.append(brownMid)
for x in range(100):
for y in range(100):
brown(x,y)
... |
userInt = input("Pick a number. ")
counter, primality, lower = 0, 0, 0
primeList = []
for x in range(2, int(userInt)):
primality = 1
for y in range(2, x+1):
if (x % y == 0) & (x != y):
primality = 0
break
if (x == y) & (primality == 1):
print("{} is prime.".fo... |
def main():
openFile('Files/file1.txt')
def openFile(filename):
fh = open(filename)
for line in fh:
print(line.strip())
if __name__ == "__main__":
main()
|
class ChiTiet:
def __init__(self, name):
self.name = name
def get_price(self):
pass
def get_weight(self):
pass
def __repr__(self):
return "name: {0}, price: {1}, weight: {2} ".format(self.name, self.get_price(), self.get_weight())
class Chitietdon(ChiTiet):
def _... |
import numpy as np
an_array = np.array([[3,33,333],[2,22,3]])
print("whole array ")
print(an_array)
print("elements ")
print(an_array[0,0])
print("fill the array with the given value")
ex1 = np.full((2,2), 9)
print(ex1)
print("create an array with ones in the diagonals")
ex2 = np.eye(2,2)
print(ex2)
print("create ... |
class Solution(object):
def isValidSudoku(self, board):
s=set()
list=board
for i in range(9):
for j in range(9):
if list[i][j] in s:
return False
if list[i][j]!='.':
s.add(... |
import csv
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
headers = ['age', 'sex','chest_pain','resting_blood_pressure',
'serum_cholestoral', 'fasting_blood_sugar', 'resting_ecg_resul... |
from turtle import *
a = int(input("How many flowers would you like?: "))
ht()
pu()
goto(((a/2)*-400),0)
screensize((400*a)+400,600)
bgcolor("skyblue")
speed(50)
pd()
b = 1
for i in range (a):
color("green","green")
begin_fill()
for i in range(1):
forward(10)
right(90)
forward(250)
... |
alfabeto = 'AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz '
def criptografar(alfabeto, texto, chave):
texto_criptografado = ''
for caractere in texto:
if caractere in alfabeto:
index = alfabeto.find(caractere) + chave
if index >= len(alfabeto):
index -... |
import math
n = float(input('Digite um numero Real: '))
print('Parte inteira do numero Real {}'.format(math.trunc(n)))
|
input_line = raw_input("Enter base (F or 10) and number to be converted: ")
input_list = input_line.split(" ")
base = input_list[0]
number = input_list[1]
if base == "F":
a, b = 0, 1
fib_numbers = []
for i in range(len(number)):
a, b = b, a+b
fib_numbers.append(a)
fi... |
import random
def yesno_question(chance=.5):
""" Returns a yes or a no
Args:
chance (float): Chance for yes result [0->0.999...]
Defaults to 0.5
"""
if random.random() <= chance:
return "Yes"
else:
return "No" |
import crypt
from termcolor import colored
def crackPass(cryptWord):
salt = cryptWord[0:2]
dictionary = open("dictionary.txt", 'r')
for word in dictionary.readlines():
word = word.strip('\n')
cryptPass = crypt.crypt(word, salt)
if (cryptWord == cryptPass):
print (colored("[+] Found password: " + word, 'g... |
import math
def normal_distribution(x, u, stdd):
return 0.5 + 0.5 * math.erf((x - u) / (stdd * 2 ** 0.5))
if __name__ == "__main__":
u = 70
stdd = 10
res1 = 1 - normal_distribution(80, u, stdd)
res2 = 1 - normal_distribution(60, u, stdd)
res3 = normal_distribution(60, u, stdd)
print(... |
inp = input("Enter something...: ")
while inp != 'q':
print("You entered: {}".format(inp))
inp = input("Enter something else: ")
'''
i = 0
while i < 10:
print(i)
i = i + 1
for i in range(0, 10):
print(i)
'''
list_a = ['a', 'b', 'c', 'joel', 'hi', '4', '5', '9']
print('-'.join(list_a))
dict_a = {'a'... |
def caesar(string):
res = str()
for letter in string:
if letter.lower() >= 'a' and letter.lower() <= 'm':
res += chr(ord(letter) + 13)
elif letter.lower() >= 'n' and letter.lower() <= 'z':
res += chr(ord(letter) - 13)
else:
res += letter
return r... |
class Car:
color = ''
speed = 0
count = 0
def __init__(self):
self.speed = 0
Car.count += 1
myCar1, myCar2 = None, None
myCar1 = Car()
myCar1.speed = 30
myCar2 = Car()
myCar2.speed = 60
myCar2.count += 1
print('자동차1의 현재 속도는 %dkm, 생산된 자동차는 총 %d대 ' % (myCar1.speed, Car.count))
print('자동차1의 현재 ... |
"""
Created on Wed Dec 13 10:06:04 2017
@author: student
"""
import tensorflow as tf
hello = tf.constant('Hello, TensorFlow!')
sess = tf.Session()
print(sess.run(hello))
matrix1 = tf.constant([[3., 3.]])
matrix2 = tf.constant([[2.], [2.]])
product = tf.matmul(matrix1, matrix2)
sess = tf.Session()
print(s... |
import requests
print("Enter url to download:")
url = input(">> ")
print("Enter filename to save:")
filename = input(">> ")
print("Downloading...")
response = requests.get(url)
if not response.status_code == 200:
print("Download error.")
exit()
print("Download successful.")
print("Saving to file...")... |
from collections import defaultdict
class BreadthFirstSearch(object):
def __init__(self, graph, source):
self.marked = defaultdict(bool)
self.edge_to = defaultdict(list)
self.source = source
self.bfs(graph, source)
def bfs(self, graph, source):
q ... |
from collections import defaultdict
class Graph(object):
def __init__(self, directed=False):
self.E = 0
self.V = 0
self.directed = directed
self.adj = defaultdict(list)
self.inverted_index = []
self.symbol_table = {}
def add_edge... |
def fac1(n):
result = 1
for i in range(2,n+1):
result *= i
return result
def fac2(n):
result = [1]
for i in range(2,n+1):
mul(result,i)
return toString(result)
def mul(result,a):
add =0
for position in range(len(result)):
aa = result[position] * a + add
... |
import random
def func(n):
list = [False] * n
light = False
while False in list:
countor = 0
a = random.randint(0,n-1)
print(f"{getName(a,countor)},{getWake(list[a])},{getLight(light)}")
prisoner = list[a]
if a == countor and light:
list[a] = True
... |
def hello(name='Nick', age='10'):
print("Hello, " + name )
print(age + " years old")
tp1 = input("Your Name: ")
tp2 = input("How old are you? ")
hello(age=tp2, name=tp1) |
import copy
import numpy as np
class Parameter:
def __init__(self, name):
self.name = name
class Input(Parameter):
def __init__(self, name):
super().__init__(name)
def __repr__(self):
return f'<Input({self.name})>'
def __eq__(self, other):
"""Two Inputs are consid... |
"""
[LeetCode] 111. Minimum Depth of Binary Tree
Given a binary tree, find its minimum depth.
The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node.
题目大意:
给定一棵二叉树,计算其最小深度。
最小深度是指从根节点出发到达最近的叶子节点所需要经过的节点个数。
解题思路:
DFS或者BFS均可,详见代码。
"""
import collections
c... |
"""
https://leetcode.com/problems/roman-to-integer/description/
13. Roman to Integer
Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M.
Symbol Value
I 1
V 5
X 10
L 50
C 100
D 500
M 1000
For e... |
"""
According to the Wikipedia's article: "The Game of Life, also known simply as Life, is a cellular automaton devised by the British mathematician John Horton Conway in 1970."
Given a board with m by n cells, each cell has an initial state live (1) or dead (0). Each cell interacts with its eight neighbors (hori... |
ls = [12, 64, 56, 89, 72, 90]
for grade in ls:
print(grade)
while grade >30:
print(">30")
break
print('end')
print("*********************")
for x in [1,2,3,4,5]:
for y in (9,8,7,6):
print(x+y)
print("end")
|
import haversine as hs
def calculate_distance(coordinates):
""" Will calculate the distance from Saint Basil's Cathedral and the address provided by client usind Haversine python lib. Saint Basil's Cathedral is used as an approximation to define whether the provided address is located inside the MKAD Moscow Ring ... |
class Solution:
def rotate(self, nums: List[int], k: int) -> None:
"""
Do not return anything, modify nums in-place instead.
https://leetcode-cn.com/problems/rotate-array
"""
leng = len(nums);
k %= leng;
loop_time = current = start = 0;
while True:
... |
import tkinter as tk
import tkinter.messagebox as msgbox
import os
HEIGHT = 300
WIDTH = 600
root = tk.Tk()
root.title("STORE PASSWORD")
canvas = tk.Canvas(root,height=HEIGHT,width=WIDTH)
canvas.pack()
frame = tk.Frame(root,bg='white' )
frame.place(relwidth=1,relheight=1)
def check(New... |
for num1 in range(2, 10):
for num2 in range(1, 10):
print("%s * %s = %s" % (num1, num2, num1 * num2)) |
"""
Spyder Editor
This is a temporary script file.
"""
import random
import datetime
import time
print("hello")
def luckyNumberRandom():
name= input ("please type your name here: ")
print ("hello", name.upper())
number= int(input("please give a number: "))
print ("your luck number is:" + str(random.r... |
my_favourite_fruits = ["apple", "orange", "banana"]
x = ["this", 55, "that", my_favourite_fruits]
x = ["this", 55, "that", my_favourite_fruits]
x[3][0]
x.remove(my_favourite_fruits)
print(x)
x[1] = "and"
x.append("again")
print(x)
y = x.append("hello")
print(x)
print(y)
y=x
x.append("test 1... |
def best_stock(data):
max_key = ""
max_value = 0
for i in (data):
if (data[i] > max_value):
max_key = i
max_value = data[i]
return max_key
if __name__ == '__main__':
print("Example:")
print(best_stock({
'CAC': 10.0,
'ATX... |
str = "ddvvrwwwrggg"
max_len = 0
counter = 0
for i in range(0, len(str)-1):
if (str[i] == str[i+1]):
counter = counter +1
print("if counter erteke: ", counter)
if (counter > max_len):
max_len = counter + 1
print("max_len: ", max_len)
else:
c... |
import matplotlib.pyplot as plt
import numpy as np
du = np.linspace(1, 5, 100)
g = np.divide(1, np.square(du))
plt.plot(du, g)
plt.xlabel('Distance in Earth Radii')
plt.ylabel('g/g_0')
plt.title('Inverse Square Decay of Gravity Force')
plt.show()
|
with open("file.txt", "r") as f:
for i in f.readlines():
for j in i.split():
print(j, end="#")
|
"""
여러
라인에
걸친
설명문
"""
number = 10
number = 15
print(number)
print("Hello Python~!")
print('오늘은 {0}월 {1}일 입니다.'.format(11, 18))
import tkinter as tk
window=tk.Tk()
window.title('Hello Python Window')
window.geometry('300x300+300+300')
window.resizable(False, True)
window.mainloop()
... |
class Calculator :
def __init__(self) :
while True :
self.n1 = input('첫번째 정수 : ')
try :
self.n1 = int(self.n1)
except :
print(f'{self.n1}은 숫자타입이 아닙니다.')
else :
... |
from matplotlib import pyplot as plt
x = list(range(1,10))
y = []
for dan in range(2, 10) :
y.append([])
for mul in range(1, 10) :
y[-1].append(dan*mul)
plt.title('GuGuDan Chart!')
for i, data in enumerate(y) :
plt.subplot(3,3,i+1)
plt.plot(x, data, '--r',
... |
import os
def list_dir(directory):
a = os.listdir(directory)
for i, item in enumerate(a):
print(i, ': ', item)
list_dir(current_dir)
|
class Solution(object):
lenx = 0
leny = 0
def set_val(self, board, point, val):
try:
board[point[0]][point[1]] = val
except:
board[point[0]] = board[point[0]][:point[1]] + str(val) + board[point[0]][point[1]+1:]
def updateBoard(self, board, click):
"""
... |
class Solution(object):
def rotateRight(self, head, k):
"""
:type head: ListNode
:type k: int
:rtype: ListNode
"""
if not head or not head.next:
return head
first = head
second = head
cnt = 0
while second and cnt... |
"""
You are given two non-empty linked lists representing two non-negative integers. The most significant digit comes first and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.
You may assume the two numbers do not contain any leading zero, except the number 0 itself.
Fo... |
class Solution(object):
def toHex(self, num):
"""
:type num: int
:rtype: str
"""
def main():
return 0
if __name__ == '__main__':
main()
|
class Solution(object):
def reorderList(self, head):
"""
:type head: ListNode
:rtype: None Do not return anything, modify head in-place instead.
"""
if not head or not head.next or not head.next.next:
return head
from collections import deque
... |
car_started = False
while True:
command = input('> ').lower()
if command == 'help':
msg = 'Start - to start the car\nStop - to stop the car\nQuit - to quit the car\n'
print(msg)
elif command == 'start':
if car_started:
msg = 'Car already started!\n'
... |
def compress(a):
ln = len(a)
if not ln:
return
char = a[0]
count = 1
compressed = char
for i in range(1,ln):
if char!=a[i]:
compressed+=str(count)
count=1
char=a[i]
compressed+=char
else:
count+=1
compressed+=str(count)
return compressed
def main():
word = raw_input("Enter string \n")
p... |
def steps(steps_left, steps_counts,hashmap):
if steps_left==0:
return 1
elif steps_left<0:
return 0
if not hashmap.get(steps_left):
hashmap[steps_left]=0
for i in steps_counts:
if i<=steps_left:
hashmap[steps_left]+=steps(steps_left-i,steps_counts,hashmap)
return hashmap[steps_left]
def main():
ste... |
def knapsack(W, weights, values):
K={w:v for w,v in zip(weights,values)}
for i in range(W+1):
max_weight=0
for j,wi in enumerate(weights):
if wi <=i:
rem_val=K.get(i-wi) if K.get(i-wi) else 0
max_weight=max(rem_val+wi,rem_val)
K[i]=max_weight
return K[W]
def main():
weights=[2,2,3,4]
values=[10,4... |
class Solution1:
def isBalanced(self, root):
"""
:type root: TreeNode
:rtype: bool
"""
if root is None:
return True
hleft = self.height(root.left)
hright = self.height(root.right)
if abs(hleft - hright) ... |
class Solution1(object):
def minDistance(self, word1, word2):
"""
:type word1: str
:type word2: str
:rtype: int
"""
len1 = len(word1)
len2 = len(word2)
grid = [[0 for i in range(len1 + 1)] for j in range(len2 +... |
def singleNumber(nums):
nu = 0
for n in nums:
nu = nu ^ n
return nu
def singleNumber2(nums):
adict = {}
for nu in nums:
if nu in adict:
del adict[nu]
else:
adict[nu] = None
return adict.popitem()[0]
def main():
print(singleNumber([4,... |
def isValidBST(root):
def isValid(root, minNode, maxNode):
if root is None:
return True
if (minNode and minNode.val >= root.val) or (maxNode and maxNode.val <= root.val):
return False
return isValid(root.left, minNode, root) and isValid(root.right, r... |
def findNonRepeatChar(stri):
chlist = [0 for ch in range(256)]
for ch in stri:
chlist[ord(ch)] += 1
for ch in stri:
if chlist[ord(ch)] == 1:
return ch
return None
def findNonRepeatCharFromCount(str1):
count = [[0, None] for i in range(256)]
for i, ch in... |
'''
Matrix chain = <A1 A2 A3 .... Ai .... An>
Each Ai matrix has dimension = Pi-1 X Pi
So index chain = <P0 P1 P2...Pi-1 Pi....Pn>
cost[i, j] = array cost[1..n-1, 1..n-1], cost of multiplying Ai to Aj
sol[i, j] = array sol[1..n-1, 2...n] is array where value of 'K' is stored. K
is index where to parenthesize for a gi... |
def reverseVowels(s):
lstr = list(s)
i = 0
j = len(lstr) - 1
vowels = ('a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U')
while i < j:
while i < j and lstr[i] not in vowels:
i = i + 1
while i < j and lstr[j] not in vowels:
j = j - 1
lstr[i],... |
class Solution:
def find132pattern(self, nums: List[int]) -> bool:
return self.find132pattern_smarter_bruteforce(nums)
def find132pattern_bruteforce(self, nums: List[int]) -> bool:
if len(nums) < 3:
return False
for i in range(len(nums)-2):
... |
class SllNode:
def __init__(self, val=None):
self.key = val
self.nextp = None
def __str__(self):
return str(self.key)
def createlist(alist):
head = tail = None
for val in alist:
if tail:
tail.nextp = SllNode(val)
tail = tail.nex... |
def find_inversion_brute(numlist, beg, end):
i = beg-1
count = 0
inver_indice = []
for index1, elem1 in enumerate(numlist[beg:end+1], start=beg):
i = i+1
for index2, elem2 in enumerate(numlist[i+1:end+1], start=i+1):
if elem1 > elem2:
count =... |
def minMove(arr):
n = len(arr)
count = 0
for i in arr[-1::-1]:
if i == n:
count += 1
n -= 1
return len(arr)-count
def main():
arr1 = [4, 2, 5, 1, 6, 3]
arr2 = [5, 1, 2, 3, 4]
arr3 = [3, 4, 2, 1]
print(minMove(arr1))
print(minMo... |
from __future__ import annotations
roman_dict = {
'I': 1,
'V': 5,
'X': 10,
'L': 50,
'C': 100,
'D': 500,
'M': 1000
}
class Solution:
def romanToInt(self, s: str) -> int:
result_int = 0
prev = None
for curr in s[-1::-1]:
... |
class Solution:
def removeDuplicates(self, nums: List[int]) -> int:
return self.removeDuplicates_sol2(nums)
def removeDuplicates_sol1(self, nums: List[int]) -> int:
if nums == None or len(nums) == 0:
return 0
unik = nums[0]
i = 1
while i < len(num... |
from collections import deque
class Solution(object):
def minMutation(self, start, end, bank):
"""
:type start: str
:type end: str
:type bank: List[str]
:rtype: int
"""
bankset = set(bank)
visited = set()
d... |
class Solution:
def hasCycle(self, head: ListNode) -> bool:
return self.hasCycle_sol3(head)
def hasCycle_sol1(self, head: ListNode) -> bool:
curr = head
while curr is not None:
... |
import numpy as np
x=np.array([3,6,8])
y=np.array([4,7,0])
multi=x*y
add =x+y
sub =x-y
dot =x.dot(y)
dot_1=y.dot(x)
cross=np.cross(x,y)
cross_1=np.cross(y,x)
print ('x = ',x)
print ('y = ',y)
print ('\n')
print ('x+y = ',add)
print ('x-y = ',sub)
print ('x*y = ',multi)
print ('\n')
... |
import re
for i in range (int(input())):
var_1 = input()
passUpper = 0
passNum = 0
flag = False
if var_1.isalnum() and len(var_1) == 10 :
for i in var_1:
if i.isupper():
passUpper+=1
if i.isnumeric():
passNum+=1
if var_1.cou... |
import petname
import random
import json
import uuid
import datetime
animals = []
heads = ["snake", "bull", "lion", "raven", "bunny"]
bodies = petname.names
while len(animals) < 20:
head = random.choice(heads)
body1 = random.choice(bodies)
body2 = random.choice... |
import urllib.request, urllib.parse, urllib.error
import re
import ssl
print('''You can use this program to find links in a webpage, the links can be used for downloading
For example:''')
print(' If you want to download something but')
print(' the website keep your see ads, ')
print(' then can use this f... |
def check_order(dest, order):
countL=0
countR=0
countU=0
countD=0
for i in order:
if i=='L':
countL+=1
if i=='R':
countR+=1
if i=='U':
countU+=1
if i=='D':
countD+=1
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.