text stringlengths 37 1.41M |
|---|
import pandas as pd
import matplotlib.pyplot as plt
"""
requires a csv with money and date columns
What do we want to know?
biggest stock movement day
what does my money movement look like without paychecks
what is just growth per day without "paycheck growth" in dollars
what is just growth per day without "paycheck ... |
import pytesseract
import cv2
from googletrans import Translator
def text_recognition(image_path):
#Proccesses the image and makes it the right size
# load the input image and grab the image dimensions
image = cv2.imread(image_path)
#makes the image pop up
cv2.imshow( 'image' , image)
... |
class Node:
def __init__(self, data=None, left=None, right=None):
self.data = data
self.left = left
self.right = right
def set_right(self, node):
self.right = node
def set_left(self, node):
self.left = node
def get_right(self):
return self.right
d... |
import Queue
class Graph:
'''
NOTE!!!! : this Graph class is describing un-weight graph, graph where all edges have constant "weight".
It means it's not important nature of node's connection but only fact that they are connected.
'''
def __init__(self):
self.nodes = []
@staticmethod
... |
# -*- coding: utf-8 -*-
# 2 задание
# список из квадратов, которые являются четными и находятся на нечетных позициях,
# тут все просто перебираем от 0 до 10, с шагом в 2, особенность в том что индексация
# в питоне начинается с 0 поэтому четные и нечетные позиции меняются местами.
a = [i * 2 for i in range(0, 10, 2) if... |
import numpy as np
import numpy.linalg as la
import scipy.optimize as opt
######## EXAMPLE FOR USING MINIMIZE_SCALAR ##############
# Define function
def f(alpha,x,s):
return rosenbrock(x + alpha*s)
# Call routine - min now contains the minimum x for the function
#min = opt.minimize_scalar(f,args=(x,s)).alpha
###... |
#!/usr/bin/python3
import re
ip = "my name is srinu"
kk = re.sub(r'srinu', r'vas',ip)
print (kk)
|
#!/usr/bin/python3
'''
Without using any string methods, try to print the following:
Note that "" represents the values in between.
enter 3
res 123
'''
no = int(input("Enter the no : "))
i = 1
st = ''
while (i <= no):
st = st + str(i)
i +=1
print ("{} value result is {}".format(no,st))
|
#!/usr/bin/python3
'''
You have a record of N students. Each record contains the student's name, and their percent marks in Maths, Physics and Chemistry. The marks can be floating values. The user enters some integer N followed by the names and marks for N students. You are required to save the record in a diction... |
#!/usr/bin/python3
aa = int(input("Enter the no : "))
bb = int(input("Enter the no: "))
## int div
dd = aa//bb
print (dd)
## float div
ee = aa/bb
print (ee)
|
#!/usr/bin/python3
n = 6
for i in range(1,15,2):
print(" "*n+"*"*i)
n-=1
|
#!/usr/bin/python3
test_list = [True, False, True, False, True, True, False]
# printing original list
print ("The original list is : " + str(test_list))
# using lambda + filter() + range()
# False indices
res = list(filter(lambda i: not test_list[i], range(len(test_list))))
print (res)
|
#!/usr/bin/python3
a = input("Enter the value :")
#a = str(a)
b = a[::-1]
if (a == b):
print ("{} is palindram.".format(a))
else:
print ("{} is not palindram.".format(a))
ll = 123;
print (type(ll))
oo = str(ll)
print (type(oo))
print (ll)
print (oo)
aa = "hh aa"
str = 'Python' #initial string
... |
#!/usr/bin/python3
pets = {'cats': 1, 'dogs': 2, 'fish': 3}
if 'dogs' in pets:
print('Dogs are found!')
else:
print('Dogs are notfound!')
ll = 50
if ll is None:
print(ll)
|
#!/usr/bin/python3
# Use of Inheritance in Python
## parrent class or base class
class Pets:
def __init__(self):
print ("okkk")
def cc1(self):
print ("parrent cc1 fun")
def dd1(self):
print ("parrent dd1 fun")
## child class or derived class
class Dog(Pets):
def __inti__(self):
super().__init__(se... |
#!/usr/bin/python3
import re
class Employee:
# 'Common base class for all employees'
empCount = 0
def __init__(self, name, salary):
self.name = name
self.salary = salary
Employee.empCount += 1
def displayCount(self):
print ("Total Employee %d" % Employee.empCount)
def display... |
#!/usr/bin/python3
import re
def Read_file(file):
dict = {}
fh = open(file,"r")
for line in fh.readlines():
line = line.strip()
if re.match(r'^\s*$',line): continue
line = ' '.join(line.split(' '))
#print (line)
try:
dict[line] +=1
except:
... |
#!/usr/bin/python3
def Switch_case(aa):
switches = {
2 : "this is value 2",
5 : "this is value 5",
0 : "this is value 0"
}
return switches.get(aa,"nothing")
if __name__ == "__main__":
aa = 10;
pp = Switch_case(aa)
print (pp)
|
#!/usr/bin/python3
list = (1,2,3,4,5,6,7)
print(list[::1])
|
#!/usr/bin/python3
a = 10
b = 20
c = "hello"
## strig concat
bb = c + str(a) + str(b)
print (bb)
## rep
cc = c * 2
print (cc)
if (cc == bb):
print ("match")
else:
print ("doen't match")
|
#!/usr/bin/python3
## without using range
no = input("Enter the no for range : ")
i = 1
while (i < int(no)):
print (i)
i +=1
|
#!/usr/bin/python3
def Flages(*hh):
aa = 8
falg = 0
for i in hh:
# print (i)
if (i == 8):
flag = 1
break
else:
flag = 0
return flag
if __name__ == "__main__":
aa = Flages(1,2,3,4,5,6,8,9,8,9,26)
print ("print flag returns ==> ... |
from numpy.random import rand, exponential
class basic_vertex(object):
"""
Represents a vertex to be matched in the system.
Implements three methods:
- match_value (value of matching to another vertex of the same type).
important that a.match_value(b) == b.match_value(a)
- unmatched_value: val... |
print(f'{"="*26}\n{"BANCO JC":^26}\n{"="*26}')
valor = int(input('Que valor você quer sacar? R$'))
total = valor
ced = 50
totced = 0
while True:
if total >= ced:
total -= ced
totced += 1
else:
if totced > 0:
print(f'Total dde {totced} cédulas de R${ced}')
if ced == 50... |
media = 0
nomeMaisVelho = 0
mulherMenos20 = 0
idadeMaisVelho = 0
for p in range(1, 5):
print('---- {}º PESSOA ----'.format(p))
nome = str(input('Nome: ')).strip().upper()
idade = int(input('Idade: '))
sexo = str(input('Sexo [M/F]: ')).strip().upper()
media += idade
if sexo == 'M':
if p =... |
num = ((int(input('Digite um número: '))),
(int(input('Digite outro número: '))),
(int(input('Digite mais um número: '))),
(int(input('Digite o último númrto: '))))
print(f'Você digitou os valores {num}\n'
f'O valor 9 apareceu {num.count(9)} vez')
if 3 in num:
print(f'O valor 3 apareceu n... |
v = float(input('Qual é o valor do produto que deseja comprar? R$'))
nv = v*0.95
d = v*0.05
print(f'Com um desconto de 5%, a vista, você irá pagar apenas R${nv:.2f} neste produto.'
f'\nRecebendo um desconto de R${d:.2f}.') |
s = 0
cont = 0
for c in range(1, 501, 2):
if c % 3 == 0:
s += c
cont += 1
print('O somatório de todos os {} números ímpares múltiplos de três foi {}!'.format(cont, s))
|
n = int(input('Digite um número para calcular seu fatorial: '))
print(f'Calculando {n}! = ', end='')
cont = 1
while n != 0:
print(f'{n}', end='')
print(' x ' if n > 1 else ' = ', end='')
cont *= n
n = n - 1
print(f'{cont}')
|
n1 = float(input('Digite um valor: '))
n2 = float(input('Digite um valor: '))
s = n1 + n2
print(f'A soma entre o valor {n1} e {n2} é igual: {s}')
|
valores = [int(input('Digite um valor: '))]
print('Valor adicionado com sucesso...')
while True:
continuar = str(input('Quer continuar? ')).strip().upper()[0]
if continuar == 'S':
valor = int(input('Digite um valor: '))
if valor not in valores:
valores.append(valor)
print... |
palavras = ('EU', 'AMO', 'à', 'ADELCINA',
'GOSTO', 'DE', 'JOGAR', 'CLASH', 'OF', 'CLANS',
'ESTOU', 'APREDENDO', 'PYTHON')
for pal in palavras:
print(f'\nNa palara {pal.upper()} temos ', end='')
for letra in pal:
if letra.lower() in 'aâãáàeéèêiìíîoõôòóuúùû':
print(letr... |
d = int(input('Informe a quantidade de dias usando o carro: '))
k = float(input('Informe a quantidade de kilometros percorridos: '))
v = (d*60) + (k*0.15)
print (f'O total a pagar pelo aluguel do carro, que foi usado por {d} dias e que rodou {k}km, é de {v:.2f} reais.')
|
pessoas = list()
soma = 0
while True:
pessoa = {'Nome': str(input('Nome: ')).strip()}
while True:
pessoa['Sexo'] = str(input('Sexo: [M/F] ')).strip().upper()[0]
if pessoa['Sexo'] in 'MF':
break
print('ERRO! Por favor, digite apenas M ou F.')
pessoa['Idade'] = int(input('I... |
valores = []
cont = 0
for c in range(0, 5):
valor = int(input('Digite um valor: '))
if c == 0 or valor > valores[-1]:
valores.append(valor)
print('Adicionado no final da lista...')
else:
pos = 0
while pos < len(valores):
if valor <= valores[pos]:
v... |
n1 = float(input('Digete a metragem: '))
k = n1/1000
h = n1/100
da = n1/10
d = n1*10
c = n1*100
m = n1*1000
print(f'O valor desta metragem\nem quilômetros é {k}\nem hectometros é {h};'
f'\nem decâmetro é {da};\n em decímetro é {d}\nem centímetros é {c};\nem milímetros é {m};')
|
n1 = int(input('Digite um valor: '))
m2 = n1*2
m3 = n1*3
r = n1**(1/2)
print(f'O dobro de {n1} é {m2};\no triplo de {n1} é {m3};\na raiz de {n1} é {r:.2f}')
|
#python3 script
#constant step size method, the difference of values between consecutive steps are random
#author: Xiang Chao
import numpy as np
import matplotlib.pyplot as plt
import random
def OneRun_1(arm_num, eps, step_num):#using sample averages, alpha = 1/n
value = np.zeros(arm_num)
Q = np.zeros(arm_num... |
name= input("Name: ")
print("Welcome, " +name )
print(f"Welcome, {name} ") |
import matplotlib.pyplot as plt
# 'go' stands for green dots
plt.plot([1,2,3,4,5], [1,2,3,4,10], 'go')
plt.show()
# Draw two sets of scatterplots in same plot
# Draw two sets of points
plt.plot([1,2,3,4,5], [1,2,3,4,10], 'go') # green dots
plt.plot([1,2,3,4,5], [2,3,4,5,11], 'b*') # blue stars
plt.show()
#The plt... |
class Solution:
"""
Given a string s, find the longest palindromic substring in s. You may
assume that the maximum length of s is 1000.
Example 1:
Input: "babad"
Output: "bab"
Note: "aba" is also a valid answer.
Example 2:
Input: "cbbd"
Output: "bb"
"""
def naive_lo... |
import pygame
pygame.init()
screen = (600, 500)
win = pygame.display.set_mode(screen)
pygame.display.set_caption("Sudoku!")
red = (255, 0, 0)
black = (0, 0, 0)
grey = (210, 210, 210)
blue = (0, 0, 255)
green = (0, 255, 0)
clock = pygame.time.Clock()
font = pygame.font.SysFont("Gill Sans MT (Body)", 50)
font2 = pyga... |
from html_scraper import scrape_all_html
import csv
from download_html import download_all
def generate_csv():
print 'Collecting toilet information from html files. This may take a few minutes.'
toilets = scrape_all_html(True)
print 'Generating CSV'
filename = 'ableroad_data.csv'
with open(filename, 'wb') as csv... |
import random
start = input('请输入初始值:')
end = input('请输入末尾值:')
start = int(start)
end = int(end)
r = random.randint(start,end)
count = 0
while True :
count += 1
num = input("请输入数字:")
num = int(num)
if num > r :
print('太大了,小一点!')
elif num < r :
print('太小了,大一点!')
else :
print('恭喜你猜对了')
print('这是你猜对的第',count,... |
import re
import string
input = open("../data/day5.txt").read()[:-1]
pattern = "|".join([str(lower) + str(lower.upper()) + "|" +
str(lower.upper()) + str(lower)
for lower in list(string.ascii_lowercase)])
while True:
str_length_prev = len(input)
input = re.sub(pattern,... |
# install chatterbot lib.
# then we import chatbot class from chatterbot module
# and now we will create a new chatbot
# so take a var(bot) and put class(chatbot)in it and make class object and pass constructor here(constructor)
# ----- we must create a set(no duplicacy) of conversation / and put this set of conver... |
# Park Se-hun, Exercise4
import math
def distance(x1, y1, x2, y2):
dist_x = x2-x1
dist_y = y2-y1
return math.sqrt(dist_x**2 + dist_y**2)
dot1_x = input("input x-coordinate of Dot1 : ")
dot1_y = input("input y-coordinate of Dot1 : ")
dot2_x = input("input x-coordinate of Dot2 : ")
dot2_y = input("input y-coordinat... |
import cv2
#from cv2 import cv
#method = cv.CV_TM_SQDIFF_NORMED
methods = ['cv.TM_CCOEFF', 'cv.TM_CCOEFF_NORMED', 'cv.TM_CCORR',
'cv.TM_CCORR_NORMED', 'cv.TM_SQDIFF', 'cv.TM_SQDIFF_NORMED']
# Read the images from the file
small_image = cv2.imread('img/2_rot.jpg')
large_image = cv2.imread('img/1.jpg')
res... |
"""
9. Среди натуральных чисел, которые были введены, найти
наибольшее по сумме цифр. Вывести на экран это число и сумму его цифр.
"""
A = input("введите число 1 ")
B = input("введите число 2 ")
C = input("введите число 3 ")
def sum_for_string(A):
sum = 0
for num in A:
sum = sum + int(num)
return ... |
"""
4. Найти сумму n элементов следующего ряда чисел: 1 -0.5 0.25 -0.125 ...
Количество элементов (n) вводится с клавиатуры.
"""
N = int(input("Введите число"))
A_NEXT = 1
A_SUM = 1
while N > 0:
A_NEXT = A_NEXT*-0.5
A_SUM = A_SUM + A_NEXT
N -=1
print(A_SUM)
|
from typing import Optional
class PostalCode:
"""
This model represents a japanese postal code.
Postal codes in Japan are 7-digit numeric codes using the format NNN-NNNN, where N is a digit.
The first two digits refer to one of the 47 prefectures (for example, 40 for the Yamanashi Prefecture),
th... |
def inout():
# simple input and output with a text file
my_file = open("text.txt") # can also put file location
# print(my_file)
print(my_file.read())
print(my_file.read()) # this does not print because the cursor is @ EOF
my_file.seek(0) # put it back to start
print(my_file.read())... |
while True:
days = 1
start = float(input('Введите дистанцию, которую пробеает спортсмен за первый день - '))
last = float(input('Введите дистанцию, к которой готовиться спортсмен - '))
if start <= 0 or last <= 0:
print('Результаты должны быть больше нуля! Стартовое значение != 0')
else:
... |
a = 5
b = 4
print(a + b)
print(a - b)
print(a * b)
print(a / b)
print(a % b) |
import numpy as np
import matplotlib.pyplot as plt
def estimateB0B1(x, y):
n = np.size(x)
averageX = np.mean(x)
averageY = np.mean(y)
sumXY = np.sum((x - averageX) * (y - averageY))
sumXX = np.sum(x * (x - averageX))
b1 = sumXY / sumXX
b0 = averageY - (b1 * averageX)
return b0, b1
d... |
keywords = {
"and": "Logical and",
"as": "Part of the with-as statement",
"assert": "Assert (ensure) that something is true",
"break": "Stop the loop right now",
"class": "Define a class",
"continue": "Don't process more of the loop, do it again",
"def": "Define a function",
"del": "Dele... |
"""
Implement a Circular Array class.
"""
class CircularArray:
def __init__(self):
self.head = 0
self.data = []
self.max_iter = 100
def append(self, item):
self.data.append(item)
def extend(self, items):
for item in items:
self.data.append(item)
... |
import numpy as np
class Suit:
def __init__(self, v):
self.suit_map = {0:"Club", 1:"Diamond", 2:"Heart", 3:"Spade"}
self.value = v
def getValue(self):
return self.value
def getSuitFromValue(self, value):
return self.suit_map[value]
class Deck:
def __init__(self, deckOfC... |
from numpy import random
class Card:
def __init__(self, family, value):
self.family = family
self.value = value
def __str__(self):
if self.value == 1:
value_desc = "As"
elif self.value <= 10:
value_desc = str(self.value)
else:
value_dict = {11:"Valet", 12:"Reine", 13:"Roi"}
value_desc = value... |
from queue import deque
class BasicNode:
def __init__(self, level):
self.level = level
self.isAvailable = True
self.parent = None
def setParent(self, node):
self.parent = node
def getParent(self):
return self.parent
class CallPool:
def __init__(self):
se... |
"""
Partition
"""
class Node:
def __init__(self, data):
self.data = data
self.next = None
def partition(node, x):
head = node
tail = node
while node:
next = node.next
if node.data < x:
node.next = head
head = node
else:
ta... |
"""
Chapter 4: Trees and Graph
Question 2: Minimal Tree
"""
import networkx as nx
import pdb
import random
from collections import defaultdict
import matplotlib.pyplot as plt
class TreeNode:
def __init__(self, val):
self.value = val
self.left = None
self.right = None
def build_bst... |
"""
Implement the Jigsaw game.
"""
import random
class Board:
def __init__(self):
self.board = list(range(9))
self.board[-1] = "X"
self.empty_pos = (2, 2)
print("Create an empty board")
print(self)
def __repr__(self):
string = ""
line = " ______"
... |
def generateParens(remaining):
S = set()
if remaining == 0:
S.add("")
else:
prev = generateParens(remaining-1)
for string in prev:
for i in range(0, len(string)):
if string[i] == "(":
s = insertInside(string, i)
S.ad... |
class Salary:
def __init__(self, pay, reward):
self.pay = pay
self.reward = reward
def annual_salary(self):
return (self.pay * 12) + self.reward
class Employee:
def __init__(self, name, position, sal):
self.name = name
self.position = position
self.final_sala... |
# def function_name_print(a, b, c, d):
# print(a, b, c, d)
# function_name_print("Sarosh", "Faraz", "Atiq", "Sabiha")
def funargs(owner, *args, **kwargs):
print("Normal Arguments")
print(owner)
print("Printing arguments (*args)")
for name in args:
print(name)
print("Printing **kwargs")... |
class Polygon:
__width = None
__height = None
def set_value(self, width, height):
self.__width = width
self.__height = height
def get_width(self):
return self.__width
def get_height(self):
return self.__height
class Square (Polygon):
def area(self):
... |
'''
converter.py: test suite for converter class
This test can be run using PyUnit's test discovery from the comment line.
> cd project_directory
> python -m unittest discover
NB. For the sake of simplicity we are only testing the conversion of a single
unit value. Were this real production code it would probabl... |
"""
list and tuplas exercise
#exercicio 1
A= ['1', '0', '5', '-2', '-5', '7']
soma = A[0]+A[1]+A[5]
A[4]=100
#print(soma)
for i in A:
print(i)
#exercicio 2
vetor = ['']
for x in range(0,6):
n=int(input('Digite um valor:\n'))
vetor.append(n)
for valor in vetor:
print(valor)... |
"""calculator.py
Using our arithmetic.py file from Exercise02, create the
calculator program yourself in this file.
"""
from arithmetic import *
while True:
user_input = raw_input("> ")
tokens = user_input.split()
arg3 = ["+", "-", "*", "/", "pow", "mod"]
arg2 = ["square", "cube"]
if ((tokens[0]... |
def primes():
p = [2,3,5,7,11,13,17,19]
for i in p:
yield i
def primes_again():
prime_gen = primes()
for prime_number in prime_gen:
yield prime_number
if __name__ == '__main__':
primes_again_gen = primes_again()
for i in primes_again_gen:
print(i)
|
def multi(n):
sum3 = 0
sum5 = 0
for i in range(n):
if i % 3 == 0:
sum3 += i
elif i % 5 == 0:
sum5 += i
print(sum3 + sum5)
multi(1000)
|
print('Nomor 2, Class Ikan')
class Ikan():
'Ikan adalah hewan yang hidup di air'
jumlah=0
def __init__ (self, nama_ikan, jenis_ikan, umur_ikan, ukuran_ikan, harga):
self.nama_ikan = nama_ikan
self.jenis_ikan = jenis_ikan
self.umur_ikan = umur_ikan
self.ukuran_ikan = u... |
"""
Write a function that reverses a string. The input string is given as an array of characters char[].
Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory.
You may assume all the characters consist of printable ascii characters.
=> Example 1:
I... |
"""
International Morse Code defines a standard encoding where each letter is mapped to a series of dots and dashes, as follows: "a" maps to ".-", "b" maps to "-...", "c" maps to "-.-.", and so on.
For convenience, the full table for the 26 letters of the English alphabet is given below:
[".-","-...","-.-.","-..",".","... |
"""
Given a fixed length array arr of integers, duplicate each occurrence of zero, shifting the remaining elements to the right.
Note that elements beyond the length of the original array are not written.
Do the above modifications to the input array in place, do not return anything from your function.
=> Example 1:
I... |
'''
Sell, sell, sell!
Python Algorithms
Suppose we are given an array of n integers which represent the value of some stock over time. Assuming you are allowed to buy the stock exactly once and sell the stock once, what is the maximum profit you can make? Can you write an algorithm that takes in an array of values a... |
"""
Given a signed 32-bit integer x, return x with its digits reversed. If reversing x causes the value to go outside the signed 32-bit integer range [-231, 231 - 1], then return 0.
Assume the environment does not allow you to store 64-bit integers (signed or unsigned).
=> Example 1:
Input: x = 123
Output: 321
=> Ex... |
"""
On a 2D plane, there are n points with integer coordinates points[i] = [xi, yi]. Return the minimum time in seconds to visit all the points in the order given by points.
=> You can move according to these rules:
In 1 second, you can either:
move vertically by one unit,
move horizontally by one unit, or
... |
# Return the fibonacci number at the position given by user
def fib_number_at(pos):
list_numbers = []
for i in range(pos+1):
if i == 0 or i == 1:
list_numbers.append(i)
else:
list_numbers.append(list_numbers[i-2]+list_numbers[i-1])
return list_numbers[pos]
# It retu... |
for i in range(1, 11):
for j in range(1, 11):
multi = str(i * j)
right_multi = multi.rjust(3)
print(f'{right_multi}', end=' ')
print(' ')
|
"""module with the definitions of an area and of a Maze"""
from sources.characters import Hero, Villain
from sources.items import Item
from sources.constants import *
import random
import pygame
class Area:
""" Area on the map. has an index in each dimension: x and y"""
def __init__(self, x, y, genre):
... |
#Create a window with required number of buttons
from tkinter import*
import math
root=Tk()
root.geometry("275x330")
root.title('Calculator')
display =None
class Calc():
def __init__(self):
self.current_value = 0
self.operation_pending = True
self.total_value =0
self.new_num=Tr... |
# A3 - Ask the user for a password, if they enter the password "qwerty123", print "You have successfully logged in".
# If they get it wrong, print "Password failure"
password = "qwerty123"
user_guess = input("What is your password?\n")
if user_guess == password:
print("You have successfully logged in.")
else:
... |
# C1 - Create the following list of items: Apples, Cherries, Pears, Pineapples, Peaches, Mangoes
fruits = ["Apples", "Cherries", "Pears", "Pineapples", "Peaches", "Mangoes"]
# C2 - Add "Grapes" to the list
fruits.append("Grapes")
# C3 - Change "Pears" to "Strawberries"
fruits[2] = "Strawberries"
# C4 - Remove "Apple... |
# D3 - Print all odd numbers from 1 to 100
for x in range(1, 101, 2):
print(x)
|
import math
#shared variables
invalid = "INVALID KEY PLEASE TRY AGAIN."
variables = ["Enter the length of the", "Enter the height of the", "Enter the base of the","Enter the radius of the", "Enter the width of the", ]
def area_calc():
#area specific variables
area_message = "The area of the"
#a... |
# -*- coding: utf-8 -*-
# @Author: Admin
# @Date: 2020-01-10 00:58:05
# @Last Modified by: Jingyuexing
# @Last Modified time: 2020-01-11 14:21:04
class Rank(object):
"""排序算法"""
def insert(self,data=[]):
if isinstance(data,list):
for i in range(2,len(data)):
key = data[i]
... |
"""Given a non-empty string s, you may delete at most one character. Judge whether you can make it a palindrome."""
# greedy solution: when see a missmatch, compare the two scenario of whether next char matched
class Solution(object):
def validPalindrome(self, s):
"""
:type s: str
:rtype: bo... |
arr_ = [2,34,52,1,7,82,1234,8472,22,245,138]
def bubbleSort(arr):
sorted_ = False
while not sorted_:
sorted_ = True
for i in range(1,len(arr)):
tmp = arr[i-1]
if arr[i-1] > arr[i]:
arr[i-1] = arr[i]
arr[i] = tmp
sorted_ = False
return arr
print(bubbleSort(arr_)) |
# Program to print BFS traversal from a given source
# vertex. BFS(int s) traverses vertices reachable
# from s.
from collections import defaultdict
# This class represents a directed graph using adjacency
# list representation
class Graph:
# Constructor
def __init__(self):
# default dictionary to st... |
"""
Given a sequence of integers, return the length of the longest subsequence that is a wiggle sequence.
A subsequence is obtained by deleting some number of elements (eventually, also zero) from the original sequence,
leaving the remaining elements in their original order.
"""
class Solution(object):
# This solution ... |
class DoYouKnowRecursion:
def __init__(self,recursion_learned):
self.recursion_learned = True
def learn_recursion(self):
try:
assert self.recursion_learned == False
print 'You are an idiot'
return self.learn_recursion()
except AssertionError:
... |
arr_ = [2,34,52,1,7,82,1234,8472,22,245,138]
def insertionSort(arr):
for i in range(1,len(arr)):
tmp = arr[i]
j = i - 1
while j >= 0 and tmp < arr[j]:
arr[j+1] = arr[j]
j-=1
arr[j+1] = tmp
return arr
print(insertionSort(arr_)) |
pahbet = list("abcdefghijklmnopqrstuvwxyz")
def checkifword():
for i in list(times):
for e in pahbet:
if i == e:
return True
return False
times = "bruh"
#key = list("@,=/}^~+%{>#.?$&)(!_-<*|:;")
while checkifword():
times = input("How many words to decrypt? ")
#password... |
import os,shutil
path = './files/'
ext = input('Digite a extensão dos arquivos que deseja copiar (ex: .txt) :')
new_path = './copias/'
for folderName, subfolders , filenames in os.walk(path):
for file in filenames:
if (file.endswith(ext)):
shutil.copy(folderName+'/' + file,
... |
import random
def noop():
pass
class Game:
congratulation_message = "Congratulations, you won! :)"
separator = "---------------------------------------------------------"
def start(self):
finished = False
while not finished:
finished = self.__play_round()
def __play... |
ingreso=int(input("ingrese su sueldo mensual: "))
mes=int(input("Ingrese la cantidad de meses trabajados: "))
gratificacion=int(input("Cantidad de gratificaciones recibidas: "))
UIT=4300
afiliacion=int(input("Estas afiliado a: \n1)ESSALUD - 1 \n2)ESP - 2 \n3)Ninguno - 3 \nIngrese un número: "))
if afiliacion... |
# 문제1.
# 다음 세 개의 리스트가 있을 때,
# subs = [‘I’, ‘You’]
# verbs = [‘Play’, ‘Love’]
# objs = [‘Hockey’, ‘Football’]
#
# 3형식 문장을 모두 출력해 보세요. 반드시 comprehension을 사용합니다.
subs = ["I", "You"]
verbs = ["Play", "Love"]
objs = ["Hockey", "Football"]
[print(subs[a], verbs[b], objs[c]) for a in range(0, len(subs)) for b in range(0, l... |
# 문제9.
# 주어진 if 문을 dict를 사용해서 수정하세요.
menu = input('메뉴: ')
dict = {'오뎅': 300, '순대': 400, '만두': 500}
print('가격: {0}'.format(dict.get(menu) if dict.get(menu) != None else 0))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.