text stringlengths 37 1.41M |
|---|
num_funcionario=int(input())
horas=int(input())
valor_hora=float(input())
salario=valor_hora*horas
print(f'NUMBER = {num_funcionario}')
print(f'SALARY = U$ {salario:.2f}')
|
X=int(input())
Y=int(input())
numeros=[Y,X]
numeros.sort()
Y=numeros[1]
X=numeros[0]
impares=[]
for i in range(X+1,Y):
if i%2==1:
impares.append(i)
print(sum(impares))
|
x1,y1 = input().split()
x2,y2 = input().split()
x1=float(x1)
y1=float(y1)
x2=float(x2)
y2=float(y2)
distancia=(((x2-x1)**2)+((y2-y1)**2))**(1/2)
print(f'{distancia:.4f}')
|
#"""Exercício 4
#(use o conhecimento que foi passado no curso)
#Crie um programa com um menu interativo:
#-----
#Cadastro de pessoas v1.0
#A) Cadastrar Pessoa
#B) Ver todos os nomes cadastrados:
#C) Ver cadastro pelo nome:
#D) Apagar um cadastro pelo nome:
#S) Sair
#-----
#Para A: Cadastre os dados do cliente (... |
# 2) Crie uma lista com 10 números qualquer.
#
# Usando as funções da lista responda:
#
# Quantos itens tem a lista?
# Qual é o número maior?
# Qual é o número menor?
# Qual é o resultado da soma da lista?
#
#
#
lista=[33,5,12,8,60,3,2,6,25,31]
print(f'a lista tem {len(lista)} itens')
print(f'o maior número é {m... |
# Exercicio 13
# Crie um programa que solicite o valor de x (inteiro)
#
# calcule usando a fórmula x+3
#
# mostre o resultado
x=int(input('informe um número '))
res=x+3
print(res) |
"""Exercicio 04
Faça um programa de cadastro de pessoas que receba 10 nomes, idades e e-mails e salve cada um em uma lista.
Depois mostre as listas separadamente
(print (lista) já é o suficiente)
"""
nomes=[]
idades=[]
emails=[]
for i in range(10):
nome=str(input(f'Informe o nome {i+1} '))
nomes.append(nome... |
import takeCommand as tc
import speak_Function as sf
import os
def read(filePath):
with open(filePath, 'r') as file1:
content=file1.readlines()
#print(content)
#sf.speak(content)
def write():
with open("data.txt","a") as file1: # write data in a file in append mode.
addNew = tc.TakeCom... |
# Imports
from tkinter import *
# Screen
root = Tk()
root.geometry("600x600")
root.title("Word and Character Counter")
# Declare Word Count and Character Count Function
def DeclareWord_CharCountFunc():
# Get Content from the TextBox
TextContent = TextBox.get("1.0", END)
# Turn The Contents (String) to... |
'''Given an integer N, the task is to check whether the given number is a pangram or not.
Note: A Pangram Number contains every digit [0- 9] at least once.'''
def pangram(num):
n = str(num)
new_set = set(n)
if len(new_set)==10:
return True
return False
N = 103876540022
print(pangram(N))
... |
#print shortest common supersequence (lcss)
#given two str and we have to print the shortest string that has both x and y as subsequence
str1=["h","e","l","l","o"]
str2=["g","e","e","k"]
#for printing first we have to form the matrix with the help of lcs
#for printing this problem is similar to lcs printing
n=len(... |
#dynamic programing
#wap to find fibonaci of a given number n with the help of dp
#in dp we use to store the value and use that value
#noraml recursion method
def fib(n):
if n == 1 or n==2:
return 1
return fib(n-1)+fib(n-2)
#through recursion time taken is more but with dp we can reduce the time
def... |
#iterable-->list,set,tuple
#iterator-->map,filter
my_list=[1,2,3,4]
for i in my_list:
print(i)
square=map(lambda i:i*i , my_list)
#print(square) --> here we only get the address of map object
'''
beacuse iteartor can only iterate one time for iterating more
than one time we convert the map object into list or tuple... |
#wap to solve fractional knapsack problem
#given -->weights of every item
#profit per items
#max weight that can be taken
#find the maximum weight
weights = [10,20,30]
profit = [60,100,120]
w = 50
def knapsack(weights,profit,w):
n = len(weights)
ratios = [p/w for p,w in zip(profit,weights)]
index = list(ran... |
class Customer:
def __init__(self,name,gender):
self.name=name
self.gender=gender
def greet(self):
if self.gender=="male":
print("hye",self.name,"sir")
else:
print("hye",self.name,"mam")
def intro(self):
print("hi i am",self.name,"and i am",self.gender)
#collections of object done as we do for list
... |
#lambda function normal
func=lambda i,j : i*j
print(func(5,6))
#lambda function using if and else
func1=lambda i: (i*i if i%2==0 else -i)
print(func1(101))
#application of lambda and sort function
#wap to sort an array according to another array
cars = ["Ford","Merccitiz","BMW","VW"]
#we create an array with value 1... |
# a list of boys
boys = ["rist", "jack", "hero", "alan", "meet", "bob", "katie", "jack", "kali" ]
#testing mutablity on index 3
boys[3] = "miss"
#list of selected candidates
selected = boys[:3]
print("selected candidates are: ", selected)
#list of eliminated candidates
eliminated = boys[3:]
print('eliminated ... |
def check_is_palindrome(word):
try:
revered = (word[::-1]).lower()
if revered == word.lower():
return True
return False
except Exception as e:
print(e)
word='svs'
print('input : svs')
Output = check_is_palindrome(word=word)
with open('Problem2_output.txt','w') as ... |
def itoBase(nb, base):
answer = []
dictionary = dict()
for i in range(len(base)):
dictionary[str(i)] = str(base[i]) #Создание словаря числовое значение:ключ из ввода
baza = len(base) #определение системы исчесления
while nb >= baza:
answer.append(dictionary.get(str(nb... |
# Time Complexity : O(n*l), where l is the average length of the words
# Space Complexity : O(n), where n is the number of words in wordList
# Did this code successfully run on Leetcode : Yes
# Any problem you faced while coding this : None
# Your code here along with comments explaining your approach
# This approach... |
#正则表达式:字符串模式(判断字符串是否符合一定的标准)
import re
#创建模式对象
# pat=re.compile("AA")
# m=pat.search("CBA")
# m=pat.search("AABCAABBAA") #search方法,进行比对查找
# m=re.search("asd","asdf") #前面的字符串是规则(模板),后面的字符串是被校验的对象
# print(m)
# m=re.findall('[a-z]+','asdfda')
# print(m)
# print(re.sub("a","A","asdfg"))#找到a用A替换,在第三个字符串中... |
#Gerard Agada, 2021-08-25
#Blackjack Game
import random
suits = ('Hearts', 'Diamonds', 'Spades', 'Clubs')
ranks = ('Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight', 'Nine', 'Ten', 'Jack', 'Queen', 'King', 'Ace')
values = {'Two':2, 'Three':3, 'Four':4, 'Five':5, 'Six':6, 'Seven':7, 'Eight':8, 'Nine':9, 'Ten':10... |
#Ask for a number from the user
#Depending on even or odd, print an appropriate message
num = raw_input('Please Enter a Number: ')
num = int(num)
#Checks if this is a Multiple of 4
if num % 2 == 0 and num % 4 == 0:
print('This is a multiple of 4')
elif num % 2 == 0:
print('Your Number is Even')
else:
... |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
#
# ============================================================================
# Copyright (c) Martin P. Hellwig <martin.hellwig@gmail.com> 2 June 2014
# All rights reserved.
# ============================================================================
#
"""
Exampl... |
"""
Realice un programa que lea dos números (dos parámetros), compare si son IGUALES, en ese caso,
mostrar un mensaje que muestre TRUE
"""
x=int(input("\nIngrese dos numeros:\n"))
y=int(input("\n"))
def igualdad(x,y):
if x==y:
print("TRUE")
else:
pass
igualdad(x,y)
|
numeros_usuario=[]
numero_del_usuario=""
while len(numeros_usuario) < 10:
while not numero_del_usuario.isdigit():
numero_del_usuario=input("Introduzca numero: ")
numeros_usuario.append(int(numero_del_usuario))
numero_del_usuario=""
print("¡Numero añadido!")
suma=0
i=0
for sumando in numeros_... |
lista=["hola",23,"me llamo",14,"willyrex",87]
lista_str=[]
lista_int=[]
for item in lista:
if type(item) is str:
lista_str.append(item)
elif type(item) is int:
lista_int.append(item)
print(lista_str , lista_int) |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2021/8/24 8:38
# @Author : ma.fei
# @File : lesson12.py
# @Software: PyCharm
# 字符串连接
s1 = "How are you ?"
s2 = "Fine,thank you, and you ?"
print(s1+' '+s2)
# 输出复复字符串,或字符
s3 ="apple "
print(s3*10)
print('q'*20)
# 输出重复字符: jlust(从字符左边填充一样的字符
s3="*"
print(s3.ljust(... |
"""
Tensorflow is basically a matrix operation library written in C++ for high performance
A Tensor is just a value, i.e it may be any dimensional matrix or an array.
In mathematics, tensors are geometric objects that describe linear relations between geometric vectors, scalars, and
other tensors. Elementary examples o... |
""" Sample usage of LSTMCell
https://github.com/farizrahman4u/recurrentshop
toy example from : http://karpathy.github.io/2015/05/21/rnn-effectiveness/
Author : Manohar Kuse <mpkuse@connect.ust.hk>
Created : 22nd Oct, 2018
"""
import keras
import numpy as np
import code
#---
... |
def search(list,target):
if len(list) == 0:
return False
else:
mid_point = (len(list)) // 2
if list[mid_point] == target:
return True
else:
if list[mid_point] < target:
return search(list[mid_point + 1:],target)
else:
return search(list[:list[mid_point] - 1],target)
|
class InstState:
def __get__(self, instance, owner):
print('InstState get')
return instance._X * 10
def __set__(self, instance, value):
print('InstState set')
instance._X = value
# 클라이언트 클래스
class CalcAttrs:
X = InstState() # 디스크립터 클래스 속성(=변수)
Y = 3 ... |
import random
'''print("Welcome to the english test!!\n"
"You will see the word on the russian language\n"
"and then translate it on the next line.\n"
"Good luck!\n")
'''
#--------------------------------------------------
def makeDic():
file = open("some.txt")
dic = {}
line = file.readl... |
'''
Source:
https://pythonprogramming.net/k-means-from-scratch-machine-learning-tutorial/
'''
import numpy as np
import random
import pandas as pd
import matplotlib.pyplot as plt
from copy import deepcopy
def generate_cluster():
data = pd.DataFrame(np.zeros((5000, 2)), columns=['x1', 'x2'])
# Let's make u... |
def wallis(n):
pi = 2
for i in range(1, n):
left = (2. * i)/(2. * i - 1.)
right = (2. * i)/(2. * i + 1.)
pi = pi * left * right
return pi
def monte_carlo(n):
import random
i=1
inspoint=0
while i<=n:
x=random.random()
y=random.random()
distance=math.sqrt(... |
#Valeria Montserrat Maya
#The Power Sum
import math
x = int(raw_input())
n = int(raw_input())
mx = int(math.pow(x,(1/float(n))))
e = [math.pow(i,n) for i in range(mx+1)]
s = int(sum(e)/x)
print s
|
''' message_router.py: An abstraction to connect any devices together.
This class enables communication and data transfer between devices.
'''
from core.messaging import Message
from core.clock import ClockReference
class MessageQueue:
''' An object which implements a queue (specifically for messages) with a m... |
#!/usr/bin/env python
'''
Creado el 08.04.2018
@author: Maximiliano R Soria
@version: 1.0
@note: Creado para la catedra de Programacion en tiempo real.
'''
#Funcion - Es una es la referencia a porcion de codigo
#Sumar espera dos parametros 'a' y 'b' y retorna su suma.
def sumar(a,b):
return a + b
#'mensaje()'... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
This script shows how to plot a column in a dataframe against its row number.
This is useful to visually detect outliers in the data.
Created on Sun Jun 4 20:03:02 2017
@author: rajulocal
"""
"""
demonstrates | create a new dataframe with fewer columns, add a seque... |
#! /usr/bin/env python3
# adapted from http://www.tutorialspoint.com/python/python_variable_types.htm
tuple = ('abcd', 786, 2.23, 'john', 70.2)
tinytuple = (123, 'john')
print( tuple ) # Prints complete tuple
print( tuple[0] ) # Prints first element of the tuple
print( tuple[1:3] ) # P... |
# Question:
# Write a program which takes 2 digits, X,Y as input and generates a
# 2-dimensional array. The element value in the i-th row and j-th column of the
# array should be i*j.
# Note: i=0,1.., X-1; j=0,1,.., Y-1.
# Example
# Suppose the following inputs are given to the program:
# 3,5
# Then, the output of the ... |
#Write your code here
class Calculator:
def power(self, first, second):
if first >= 0 and second >= 0:
return first ** second
return "n and p should be non-negative"
myCalculator = Calculator()
T = int(raw_input())
for i in range(T):
n, p = map(int, raw_input().split())
t... |
if __name__ == "__main__":
meal_cost = float(raw_input().strip())
tip_percent = int(raw_input().strip())
tax_percent = int(raw_input().strip())
tip = meal_cost * tip_percent / 100
tax = meal_cost * tax_percent / 100
total = meal_cost + tip + tax
print("The total meal cost is {:.0f} dollar... |
"""
A small example of robotsoccer-python usage.
To run this module type in terminal::
python example_simple.py host port
If host or port is omitted 'localhost' and 1024 are assumed as default
"""
import os
import sys
import math
import numpy
NUMBER_OF_POINTS = 500
BALL_ANGLE_RULES = 5
TARGET_ANGLE_RULES = 3
BA... |
import socket
def main():
host = '127.0.0.1'
port = 3400
#host = localhost IP address
#port= random port number to connect
sa = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
sa.connect((host,port))
#created client connection with host ip address and port
while True:
... |
'''
Created on 18-Sep-2020
@author: mohd.e.khan
'''
import time
def pass_argument(ls):
print(ls)
fls = ls
print("After assigning a new list to fls")
fls=["Modifying", "It", "Inside", "Function"]
print("Argument:", ls)
print(fls)
ls = ["A", "List", "To", "Pass"]
pas... |
def merge_the_tools(string, k):
# 0:3, 3:6, 6:9
# for i in range(1,k+1):
# hold = string[(k*(i-1)):k*i]
# arr = []
# for j in hold:
# if j not in arr:
# arr.append(j)
# # set_s = set(list(hold))
# print(''.join(arr))
arr=[]
for i in range(len(string)):
i... |
from collections import Counter
n = int(input())
arr = []
for _ in range(n):
arr.append(str(input()))
new_dict = Counter(arr)
print(len(new_dict))
for i in new_dict:
print(new_dict[i], end=" ")
# print(list(new_dict.values()))
|
## 导入所有必要的包和函数。
import csv # 读写 csv 文件
from datetime import datetime # 日期解析操作
from pprint import pprint # 用于输出字典等数据结构
# 这比 base print 函数要好用。
def print_first_point(filename):
"""
本函数会输出并返回指定的 csv 文件 (含页眉行)的第一个数据点(即文件的第二行)。
"""
# 输出城市名以供参考
city = filename.split('-... |
# https://leetcode.com/problems/reverse-integer/
class Solution:
def toSeq(self, x):
for char in iter(ascii(x)):
yield char
def reverse(self, x: int) -> int:
negative = x < 0
if negative:
x = -x
result = ''
started = False
for char in rev... |
#Store Sales In Asterisks
store1Sales = eval(input("Enter Store 1 Sales: "))
store2Sales = eval(input("Enter Store 2 Sales: "))
store3Sales = eval(input("Enter Store 3 Sales: "))
#Store1
print("Store 1 Sales: ",end = '')
for i in range(round(store1Sales/100)):
print("*", end = '')
print()
#Store2
print("Store 2 ... |
from tkinter import *
import sys
#Learning from https://likegeeks.com/python-gui-examples-tkinter-tutorial/
#Create Main Window
mainWindow = Tk()
mainWindow.title("Whoaaa a window")
mainWindow.geometry('400x600')
#Hello Label
howAreYou = Label(mainWindow, text="Hello", font=("Calibri", 12))
howAreYou.gri... |
def del_space(str):
str = list(str)
i = 0
lenth = len(str)
while str[0] == '':
str.pop(0)
while str[-1] == '':
str.pop()
return ''.join(str)
if __name__ == '__main__':
while True:
string = raw_input('Enter a string("q" to quit):')
if string == 'q':
break
else:
print del_space(stri... |
import math
def isprime(number):
num = int(math.sqrt(number))
while num > 1:
if number % num == 0:
return False
num -= 1
else:
return True
print zip(range(1, 12), (isprime(x) for x in range(1,12))) |
#-*- coding:utf-8 –*-
abc = sum(float(raw_input('enter a number: ')) for i in range(5))
print float(abc/5)
'''a = [342.23,13.23,43,231,123]
def f(x,y):
return x + y
print float(reduce(f,a)/len(a)) '''#reduce函数说明http://www.cnblogs.com/XXCXY/p/5180245.html |
# Problem Set 4A
# Name: Nicholas Pan
def get_permutations(sequence):
'''
Enumerate all permutations of a given string
sequence (string): an arbitrary string to permute. Assume that it is a
non-empty string.
You MUST use recursion for this part. Non-recursive solutions will not be
... |
#!/usr/bin/python3
""" Unittest for max_integer([...])
"""
import unittest
max_integer = __import__('6-max_integer').max_integer
class TestMaxInteger(unittest.TestCase):
"""define unittest"""
def test_int(self):
self.assertEqual(max_integer([4, 6, 8, 10]), 10)
def test_neg(self):
self... |
#!/usr/bin/python3
for abc in range(122, 96, -1):
if abc % 2 != 0:
abc -= 32
print("{}".format(chr(abc)), end="")
|
#!/usr/bin/python3
"""
modeule with function
"""
def append_write(filename="", text=""):
"""apend"""
with open(filename, mode="a", encoding="utf-8") as file:
return (file.write(text))
|
'''
https://leetcode.com/problems/non-decreasing-array/
'''
class Solution:
def checkPossibility(self, nums):
def monotone_increasing(arr):
for i in range(len(arr) - 1):
if arr[i] > arr[i+1]:
return False
return True
new = nums[:]
... |
# Python3 program to check whether a given tic tac toe
# board is valid or not
# https://www.geeksforgeeks.org/validity-of-a-given-tic-tac-toe-board-configuration/
# Returns true if char wins. Char can be either
# 'X' or 'O'
def win_check(arr, char):
# Check all possible winning combinations
# first, second and... |
def bracketBalanced(expr):
balance=0
for i in expr:
if i=='(': balance+=1
elif i==')': balance-=1
if balance<0:
return False
return balance==0
expr="(a)"
print(bracketBalanced(expr))
'''
-'ve means more )
+'ve means more (
0 means balanced
''' |
# https://leetcode.com/problems/minimum-size-subarray-sum/
# target sum
def minSubArrayLen(s, nums):
res=float('inf')
for i in range(len(nums)):
for j in range(i, len(nums)):
sum=0
for k in range(i,j+1):
sum+=nums[k]
if sum>=s:
res=min... |
# https://leetcode.com/problems/binary-tree-zigzag-level-order-traversal/
from collections import deque
class Node:
# A utility function to create a new node
def __init__(self, key):
self.val = key
self.left = None
self.right = None
def levelOrder(root):
if root is None:
return []
... |
#// https://practice.geeksforgeeks.org/problems/find-triplets-with-zero-sum/1
def find3Numbers(A, n, X):
A.sort()
for i in range(n - 2):
l = i + 1
r = n - 1
while (l < r):
if(A[i] + A[l] + A[r] == X):
print(A[i], ",", ",",
A[l], ",", A[r])
l += 1
r -= 1
elif ... |
'''
https://leetcode.com/problems/clone-graph/
Each node's value is the same as the node's index (1-indexed).
For example, the first node with val = 1, the second node with val = 2
DFS
we don't want to get stuck in a cycle while we are traversing the graph; keep track of visited
hash map with key as origi... |
'''
https://leetcode.com/problems/pacific-atlantic-water-flow/submissions/
water flow from pacific to atlantic
find coordinates in matrix from which water can flow to both ocean
dfs
'''
class Solution:
def isValidCell(r,c,matrix):
if(r>=0 and r<len(matrix) and c>=0 and c<len(matrix[0])):
retu... |
# https://leetcode.com/problems/task-scheduler/solution/
# idle i.e., cool down period time between two SAME tasks
# Number of busy slots is defined by the number of tasks to execute: len(tasks)
# idle slots = frequency of most frequent task: idle_time <= (f_max - 1) * n.
# f_max=5 bcz of A
# idle_time=5-1*2=8 bcz ... |
'''
https://leetcode.com/problems/maximal-square/
https://www.youtube.com/watch?v=6X7Ha2PrDmM&feature=emb_logo&ab_channel=NeetCode
# dynamic programing
# memoization
largest square, not rectangle
'''
def maximalSquare(matrix):
row=len(matrix)
col=len(matrix[0])
cache={} #dictionary of tuples with locati... |
"""
https://leetcode.com/problems/design-underground-system/
underground
railway station
car parking
toll both
"""
class UndergroundSystem:
def __init__(self):
# {id:[checkInStation, checkInTime], }
self.checkindata={}
# [(checkInStation, checkOutStation): journeyTime, Count, ]
... |
"""
https://leetcode.com/problems/design-tic-tac-toe/
tic tac toe
ticTacToe.move(2, 1, 1); // return 1 (player 1 wins)
|X| |O|
|O|O| | // Player 1 makes a move at (2, 1).
|X|X|X|
def check_grid(2, 1, 1):
2[0]=2[1]=2[2]='X' True
1[0]='',1[1]=0, 1[2]='X' False
similary check diagonal... |
"""
https://leetcode.com/problems/reverse-integer
reverse integer
reverse int
"""
class Solution:
def reverse(self, x: int) -> int:
"""
:type x: int
:rtype: int
"""
"convert int to string"
flag = False
x_char = str(x)
"if negative int remove the si... |
# https://leetcode.com/problems/leftmost-column-with-at-least-a-one/solution/
# A row-sorted binary matrix as input is given, we can also use binary search
# binary search in matrix
def leftMostColumnWithOne(binaryMatrix):
rows = len(binaryMatrix)
cols = len(binaryMatrix[0])
l=cols
for row in range(row... |
# https://www.geeksforgeeks.org/write-your-own-atoi/
# https://www.youtube.com/watch?v=QyDE7cPycnU&ab_channel=CppNuts
'''
string to integer
ord('0')=48
ord('1')=49
2 =50
3 =51
res=0*10+(49-48)=1
res=1*10+2=12
res=12*10+3=123
'''
def atoi(s):
res=0
sign=1
i=0
# remove white space
s... |
"""
https://leetcode.com/problems/design-parking-system/
ask questions, clarify assumptions
do i design or algorithm?
spots
size: small, medium, large and xlarge
small car can be parked on bus spot but, not vice versa
price
disability, premium
levels
entry and exit: concurrency
abstract vehicle
stri... |
'''
https://leetcode.com/problems/remove-duplicate-letters/
https://leetcode.com/problems/smallest-subsequence-of-distinct-characters/
arrange smallest
remove duplicates
smallest subsequence (subsequent) distinct characters
As a result any string beginning with a will always be less than any string
beginning wit... |
"""
https://leetcode.com/problems/minimum-window-substring/solution/
0. create dict_t of all unique chars in t; len of this is required number of chars
1. left and right pointer pointing to 0
2. keep moving right pointer until window has all elements
3. increment left pointer, check if windows has all elements, if so c... |
# https://leetcode.com/problems/subarray-sums-divisible-by-k/
# subarray sums divisible by k
# list comp
from collections import Counter
def subArrayDivEfficient(A,n,K):
curr_sum=count=0
for i in range(n):
curr_sum=A[i]
if curr_sum%K==0: count+=1
for j in range(i+1,n):
curr_sum+=A[j]
if curr_sum%K==0: ... |
"""
https://leetcode.com/problems/regular-expression-matching/solution/
'.' Matches any single character
'*' Matches zero or more of the preceding element.
if no *, we simply check from left to right if each character of the text matches the pattern
refer to def match() below; each recursion will parse from index ... |
# https://www.geeksforgeeks.org/find-minimum-number-of-coins-that-make-a-change/
# https://leetcode.com/problems/coin-change/solution/
# https://www.youtube.com/watch?v=jgiZlGzXMBw&feature=emb_logo&ab_channel=BackToBackSWE
# A Naive recursive python program to find minimum of coins
# to make a given change V
import... |
'''
https://leetcode.com/problems/group-anagrams/
anagrams
Group-Anagrams
when we sort the string, while adding to dictionary, we keep appending to same key; with actual unsorted values
'''
from collections import defaultdict
strs = ["eat","tea","tan","ate","nat","bat"]
ans=defaultdict(list)
for s in strs:
a... |
"""
https://www.youtube.com/watch?v=OM1MTokvxs4&ab_channel=NeetCode
https://leetcode.com/problems/triangle/
minimum path sum triangle
"""
class Solution:
def minimumTotal(self, triangle):
dp=[0]*(len(triangle[-1])+1) # last row is longest in triangle
for row in triangle[::-1]:
print(d... |
'''
https://leetcode.com/problems/monotone-increasing-digits/solution/
'''
class Solution:
def monotoneIncreasingDigits(self, N):
def monotone_increasing(arr):
for i in range(len(arr) - 1):
if arr[i] > arr[i+1]:
return False
return True
#... |
# https://leetcode.com/problems/max-area-of-island/solution/
# Use DFS to count max area of an island
# best DFS
# find-islands.py finds number of island, this solution finds max area of found islands
class Solution(object):
def maxAreaOfIsland(self, grid):
seen = set()
def area(r, c):
... |
'''
https://leetcode.com/problems/palindrome-partitioning/solution/
# palindrome partition backtracking
Iteratively generate all possible substrings beginning at start index. The end index increments from start till the end of the string.
Example, abba can be partitioned as ["a","ab","abb","abba"]
For each of the ... |
"""
https://leetcode.com/problems/remove-linked-list-elements
linked list
linkedlist
remove node from linked list
delete node from linked list
The things are more complicated when the node or nodes to delete are in the head of linked list.
We use a dummy node at front, called sentinel node
head: [1,2,6,3,4,5,6]
cu... |
'''
https://leetcode.com/problems/min-cost-climbing-stairs/
https://www.youtube.com/watch?v=OoGswqFU-zs&ab_channel=NickWhite
climbing stairs
climb stairs
steps
dynamic program
'''
class Solution:
def minCostClimbingStairs(self, cost):
for i in range(2, len(cost)):
cost[i]+=min(cost[i-2], cos... |
# https://www.geeksforgeeks.org/count-number-of-occurrences-or-frequency-in-a-sorted-array/
# can use dictionary
# Given a sorted array arr[] and a number x,
# write a function that counts the occurrences of x in arr[].
# Input: arr[] = {1, 1, 2, 2, 2, 2, 3,}, x = 1
# Output: 2
# #o(n)
# arr1 = [1, 1, 2, 2... |
def is_lower(x):
return x == 'F' or x == 'L'
def binary_search(string):
str_len = len(string)
start = 0
end = pow(2, str_len) - 1
# print(end)
for i in range(0, str_len - 1):
c = string[i]
half = (end - start + 1) / 2
if is_lower(c):
end -= half
else... |
#!/usr/bin/env python
from algorithms import *
import sys, os, getopt
def summary(fullArray, sumData):
if sumData == None:
return str(fullArray) + ", empty, 0"
return str(fullArray) + ", " +\
str(fullArray[sumData.left:sumData.right+1]) + ", " +\
str(sumData.sum)
def parseDataString(string):
st... |
# -*- coding: utf-8 -*-
"""
Created on Sun Apr 21 10:09:25 2019
@author: Mohit
"""
import os
import numpy as np
import pandas as pd
#1. Extract Given data into Python
os.chdir("C:/Users/Mohit/Desktop/Nikhil Analytics Material/Python/Python Part 2/Class 9")
os.getcwd()
data = pd.read_excel('Assignment.x... |
height = int(input())
for i in range(1, 1 + 2 * height, 2):
print(("#" * i).center(2 * height - 1))
|
# put your python code here
all_grades = input().split()
grades_a = [x for x in all_grades if x == "A"]
print(round(len(grades_a) / len(all_grades), 2))
|
"""
platformer.py
Author: Kyle Rozzi
Credit:Mr. Dennison, Mr. Dennison's sample program, and Tristan Meyer
Assignment:
Write and submit a program that implements the sandbox platformer game:
https://github.com/HHS-IntroProgramming/Platformer
"""
from ggame import App, Color, LineStyle, Sprite, RectangleAsset, CircleAss... |
"""
calculator.py
Using our further_arithmetic.py file from Exercise02, create the
calculator program yourself in this file.
"""
from further_arithmetic import *
# Your code goes here
def calculator_interface():
"""Prefix based calculator interface.
Function potentiality for +, -, *, /, square, cube, pow, m... |
######1.Exceptions
'''
Sample Input
3
1 0
2 $
3 1
Sample Output
Error Code: integer division or modulo by zero
Error Code: invalid literal for int() with base 10: '$'
3
'''
for i in range(int(input())):
try:
a, b = map(int, input().strip("\r").split(" "))
print(a//b)
except ZeroDivisionError:
... |
# Chris Pellerito
# Final project
# This program will run the game hangman
def hangman(): # Main function that runs everything
print('''Welcome, this game is a two player variation of hangman. Player 1 is choosing the word to be guessed
and Player 2 is guessing.''')
# list of every variation o... |
"""
Author: Reuben Ferrante
Date: 27/10/2017
"""
import re
import logging
import shutil
def strip_file_extension(file_name):
"""
Takes a file name and strips the file extension.
:param file_name: str
:return: file name str without the file extension.
"""
try:
temp = str(file_name).sp... |
import numpy as np
from scipy.spatial.distance import cdist
def calc_distance_ndarray(data, dist_method="euclidean"):
""" Calculates distance
Args:
data : pd.DataFrame
dist_method : str or callable
Returns:
np.ndarray :
shape(nd.array) = [len(data), len(data)]
... |
#统一转换为分钟后排序
class Solution:
def findMinDifference(self, timePoints: List[str]) -> int:
minutelist=[]
for i in range(len(timePoints)):
hour,minute=map(int,timePoints[i].split(":"))
minutelist.append(hour*60+minute)
minutelist=sorted(minutelist)
mindis=2000
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.