text stringlengths 37 1.41M |
|---|
"""Contains an representation of a question."""
class Question:
"""Representation of question."""
def __init__(self, relation):
"""
Create a question.
:type relation: app.types.relation.Relation
"""
self.relation = relation
def __eq__(self, other):
"""Equa... |
import os
import sys
import time
from to_do_list import *
def clear():
"""Clear the display"""
os.system("cls" if os.name == "nt" else "clear")
def main():
menu_choices = """
(1) Create an item
(2) Display item list
(3) Display item details
(4) Modify item details
(5) Delete item fro... |
# Autor: Elena Itzel Ramírez Tovar
# Descripcion: Calcular porcentaje de alumnos por sexo
# Escribe tu programa después de esta línea.
m=int(input("Ingrese el número de estudiantes de sexo masculino: "))
f=int(input("Ingrese el número de estudiantes de sexo femenino: "))
t=m+f
pm=float((m*100)/t)
pf=float((f*100)/t)
p... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# 04. 元素記号
# "Hi He Lied Because Boron Could Not Oxidize Fluorine. New Nations Might Also Sign Peace Security Clause. Arthur King Can."
# という文を単語に分解し,1, 5, 6, 7, 8, 9, 15, 16, 19番目の単語は先頭の1文字,それ以外の単語は先頭に2文字を取り出し,
# 取り出した文字列から単語の位置(先頭から何番目の単語か)への連想配列(辞書型もしくはマップ型)を作成せよ.
sent... |
# coding: UTF-8
# 18. 各行を3コラム目の数値の降順にソート
# 各行を3コラム目の数値の逆順で整列せよ(注意: 各行の内容は変更せずに並び替えよ).
# 確認にはsortコマンドを用いよ(この問題はコマンドで実行した時の結果と合わなくてもよい).
f = open('../data/hightemp.txt')
lines = f.readlines()
f.close()
for i in range(0, len(lines)):
for j in range(0, len(lines)-1-i):
if lines[j].split('\t')[2] < lines[j+1... |
# coding: UTF-8
# 24. ファイル参照の抽出
# 記事から参照されているメディアファイルをすべて抜き出せ.
import re
pattern = r"(File:([^|]*))|(ファイル:([^|]*))"
repattern = re.compile(pattern)
for line in open("../data/jawiki-country-uk.txt"):
match = repattern.search(line)
if match:
print match.group(1) if match.group(3) is None else match.grou... |
import sys
import random
class Model(object):
def __init__(
self,
_config = dict()):
self.config = _config
self.filepath = self.config["filepath"] if "filepath" in self.config else sys.exit("Filename not given")
self.load_words()
#self.fetch_words()
def load_words(
self):
self.lines =... |
#Libs necessarias para fazer o banco
#Especifico
import sqlite3
#Geral
import pandas
#Import de funcoes
import funcoes_gerais
#variaveis globais
global banco
global quebrador_csv
banco = "teste.db"
quebrador_csv = ";"
"""
Criando o banco
"""
#Conectar o banco
def contactar_banco():
#garantir que vai abrir o b... |
class Node(object):
def __init__(self, data):
self.data = data;
self.leftChild = None;
self.rightChild = None;
def insert(self, data):
if data < self.data:
if not self.leftChild:
self.leftChild = Node(data);
else:
self.left... |
from string import ascii_letters
class Trie_Node(object):
def __init__(self):
self.isWord = False
self.s = {c: None for c in ascii_letters}
def add(T, w, i=0):
if T is None:
T = Trie_Node()
if i == len(w):
T.isWord = True
else:
T.s[w[i]] = add(T.s[w[i]], w, i + ... |
'''
Menu example
'''
import sys
import random
import pygame
# Constants
FPS = 60
SCREEN_WIDTH = 1200
SCREEN_HEIGHT = 800
BTN_PADDING = 10 # How much padding are we going to put around a button?
BTN_MARGIN = 10 # How much space do we want around button text?
# Colors
WHITE = [255, 255, 255]
GREY = [175, 175, 1... |
# https://github.com/denisbalyko/checkio-solution/blob/master/friendly-number.py
def friendly_number(number, base=1000, decimals=0, suffix='',
powers=['', 'k', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y']):
"""
Format a number as friendly text, using common suffixes.
"""
index, pow = enumerate... |
import numpy as np
from math import ceil
import itertools
BLACK_COLOR = "black"
WHITE_COLOR = "white"
# strings identifying move and boom actions
MOVE_ACTION = "MOVE"
BOOM_ACTION = "BOOM"
# the x/y length of the board
BOARD_SIZE = 8
# explosion radius
ER = 1
# the starting board in a flattened byte array when posi... |
#!/usr/bin/env python3
"""Planets.py: Description of how planets in solar system move.
__author__ = "Liu Yuxin"
__pkuid__ = "1800011832"
__email__ = "1800011832@pku.edu.cn"
"""
import turtle
wn = turtle.Screen()
turtle.screensize(800, 600)
wn.delay(0)
def initialization(t, r, a, c, colors):
# t standing for pl... |
class Garden:
plant_dict = {
'V': 'Violets',
'G': 'Grass',
'C': 'Clover',
'R': 'Radishes',
}
def __init__(self, garden, students=None):
if students is None:
students = [
'Alice', 'Bob', 'Charlie', 'David', 'Eve', 'Fred',
'G... |
Python 3.6.3 (default, Oct 3 2017, 21:45:48)
[GCC 7.2.0] on linux
Type "copyright", "credits" or "license()" for more information.
>>> set={1,9,5,4,3}
>>> print(set)
{1, 3, 4, 5, 9}
>>> tuple=(1,4,5,6,7)
>>> print(tuple)
(1, 4, 5, 6, 7)
>>> list=[1,2,3,4,7]
>>> print(list)
[1, 2, 3, 4, 7]
>>> dictionary={6:"muskan","... |
# Modules
import os
import csv
# Set path for budget file
csvpath = os.path.join('Resources', 'budget_data.csv')
# Use total to calculate the Profit/Loss
# Use months to count the number of months in the dataset
total = 0
months = 0
sum_change = 0
previous = 0
change_values = []
# Open the CSV
with ... |
#!/usr/bin/env python
# coding: utf-8
# In[2]:
df4=pd.read_csv('https://raw.githubusercontent.com/akhil12028/Bank-Marketing-data-set-analysis/master/bank-additional-full.csv',sep=';')
df4
# In[6]:
#1:read data from below ur
#https://raw.githubusercontent.com/akhil12028/Bank-Marketing-data-set-analysis/master/ban... |
#!usr/bin/python
# Write a Python program that accepts a string and calculate the number of digits and letters
# Sample Data : "Python 3.2"
# Expected Output :
# Letters 6
# Digits 2
q=raw_input("enter your string \n")
we=q.replace(" ","")
print q
count1=0
count2=0
count3=0
for i in q:
if(i.isdigit()) :
count1+... |
def mergeArray(nums1,nums2):
nums3=nums1+nums2
nums3.sort()
print nums3
nums1 = [1,2,3,0,0,0]
nums2 = [2,5,6]
mergeArray(nums1,nums2) |
class queue(object):
def __init__(self):
self.items=[]
def isEmpty(self):
return self.items==[]
def firstIn(self,newElement):
return self.items.insert(0,newElement)
def firstOut(self):
return self.items.pop()
x=queue()
print x.isEmp... |
def groupAnagrams(arr):
dict={}
result=[]
for word in arr:
sortedword ="".join(sorted(word))
dict.setdefault(sortedword,[])
if sortedword not in dict:
dict["sortedword"] = word
else:
dict[sortedword].append(word)
for item in dict.values()... |
#!usr/bin/python
count =False
def is_Sublist(a,b):
a.sort()
b.sort()
for i in range(len(a)):
for j in range(len(b)):
if a[i]==b[j]:
count=True
else:
count=False
if count == True:
print "Its a sublist"
else:
print "Its not a sublist"
a=[2,4,3,5,7]
b=[4,7,3,1]
is_Sublist(a,b)
|
def longestPalindromicSubstring(string):
# Write your code here
longest=""
for i in range(len(string)):
for j in range(i,len(string)):
substring=string[i:j+1]
if len(substring)>len(longest) and isPalindrome(substring):
longest=substring
return longest
... |
#!/usr/bin/python
# Generate a random number between 1 and 9 (including 1 and 9).
# Ask the user to guess the number, then tell them whether they guessed too low, too high, or exactly right.
import random
try:
n1=input("enter the number you want to guess \n")
n2=input("enter the range of the random number \n")
p... |
def climbing_stairs(n):
a = b = 1
for i in range(n-1):
a, b = a + b, a
return a
'''for i in range(2,n+2):
ways[i]=ways[i-2]+ways[i-1]
n=n+2
return ways[n]
'''
print climbing_stairs(4)
|
import tkinter
from tkinter.constants import*
from tkinter import*
import math
from tkinter import messagebox
#<----------Factors\\\Dont forget----------->
tk = tkinter.Tk()
tk.title('Quadratic Equation')
tk.maxsize(width = 550, height = 275)
tk.minsize(width = 460, height = 200)
frame = tkinter.Frame(t... |
#this will ask for user input
import sys
print("What is your name")
name = sys.stdin.readline()
print("Hello, " + name)
print("Well that's cool, what did you eat")
eat = sys.stdin.readline();
e = eat;
if (e == "bread and beans"):
print("gafsabhdgnde")
else:
print("nothing")
|
import re, tkinter, math
from tkinter.constants import*
from tkinter import*
from tkinter import messagebox
#<----------Factors\\\Dont forget----------->
tk = tkinter.Tk()
tk.title('MATRICE(3x3) SOLVER')
tk.maxsize(width = 585, height = 300)
tk.minsize(width = 475, height = 215)
frame = tkinter.Frame(tk,... |
import datetime, winsound, time
#alarm_hour = input('HOUR: ')
#alarm_minute = input('MINUTE: ')
#alarm_second = input('SECOND: ')
sound_file = "C:\\Users\\Sambou\\Desktop\\W3SCHOOLS\\gggg\\www.w3schools.com\\jsref\\horse.wav"
def alarm():
for i in range(0, 10):#while(True):
... |
#----------------------------------------Solving Logical Questions---------------------------------------#
import re
print("\t\t\tThis Interface Solves logical Questions\n\t\t\tIf you wish to Exit, Just Type 'Quit'")
class Solver():
def __init__(self,num_one, num_two):
self.num_one = num_one
... |
# Program to display file pointer after reading two lines
# Created by: Siddhartha
# Created on: 1st April 2020
fileName = "files/story.txt"
# open file in read mode
Fn = open(fileName, 'r')
# read two lines one by one
for iter in range(2):
Fn.readline()
# print the position of pointer
print("Position of point... |
# Program to count no. of you and me in a text file
# Created by: Siddhartha
# Created on: 1st April 2020
# Function to count me
def Me(file):
count = 0
for line in file.readlines():
# removing escape seq. and converting to lower case
line = line.lower().strip().split(" ")
# Counting n... |
fim = int( input( "digite seu número aqui: "))
x = 3
while x <= fim:
print (x)
x = x + 3
|
print( "Olá, seja bem vindo")
print( "Digite dois numeros inteiros e saiba sua soma!")
numero1 = int(input("digite o primeiro número:"))
numero2 = int(input("digite o segundo número:"))
soma = ( numero1 + numero2)
print (" o resultado da soma é: ", soma)
|
print(" Saiba se você tomou multa ou não!!")
velocidade = int( input( "Digite a sua velocidade aqui: "))
if velocidade > 80:
print (" Você tomou uma multa de R$5,00! ")
else:
print (" Você não tomou multa!") |
print("Digite o preço de uma mercadoria e seu desconto para saber quanto você irá pagar!")
mercadoria = int( input( "Digite o preço da mercadoria aqui: "))
percentual = int (input(" Digite o percentual do desconto aqui: "))
desconto = mercadoria * percentual /100
precoFinal = mercadoria - desconto
print( "Você vai pag... |
print ( ' Saiba quantos dias de vida um fumante perde!!')
cigarros = int(input(' Digite o numero de cigarros fumados por dia: '))
anos = int(input(' Agora digite a qantidade de anos fumados: '))
dias = anos * 365
diasCigarro = cigarros * 10 / 1440
diasPerdidos = dias * diasCigarro
print ( ' O numero de dias perdidos po... |
idade = int( input( "Digite a idade do seu carro aqui: "))
if idade <= 3:
print ("Seu carro é novo!!")
else:
print (" Seu carro é velho!!") |
"""
* Author :Ravindra
* Date :12-11-2020
* Time :15:30
* Package:BasicCorePrograms
* Statement:Computes the prime factorization of N using brute force.
"""
class PrimeFactors:
number=0
def __init__(self,number):
"""Constructor Definition """
self.number=number
def calculatePrimeFactors(sel... |
"""
* Author :Ravindra
* Date :18-11-2020
* Time :19:10
* Package:Functional Programs
* Statement:A library for reading in 2D arrays of integers, doubles, or booleans from standard input and printing them out to standard output.
"""
class TwoDArray:
def inputArrayParameters(self):
""" Method Defin... |
# filter(func, iterable)
def has_o(string):
return 'o' in string.lower()
words = ['One', 'two', 'three', '23Fkjsf']
filtered_list = list(filter(has_o, words))
print('filtered_list:', filtered_list)
lambda_filtered_list = list(filter(lambda string: 'o' in string.lower(), words))
print('lambda_filtered_list:', la... |
def Ceacar_encrypt(P,offset):
C = ""
for i in range(len(P)):
if not P[i].isalpha():
C += " "
C += chr(ord(P[i])+offset)
return C
def Ceacar_decrypt(C, offset):
P = ""
for i in range(len(C)):
if not C[i].isalpha():
P += " "
P += chr(ord(C[i])-... |
h = int(input("введиет часы: "))
m = int(input("введите минуты: "))
s = int(input("введте секунды: "))
print("суммарное число секунд: " ,str(h * 3600 + m * 60 + s))
|
#!/usr/bin/python3
import sys
class Parser:
def __init__(self, file_path):
with open(file_path, "r") as f:
self.file = f.readlines()
self.current_command = None
self.index = -1
def hasMoreCommands(self):
return (self.index + 1) in range(len(self.file))
def adv... |
if {}: print "hi"
d = {"maggie": "uk", "ronnie": "usa"}
d.items() #items returns [('maggie', 'uk'), ('ronnie', 'usa')] i.e. the contents of the dictionary in their paired tuples
d.keys() #keys returns ['maggie', 'ronnie']
d.values() #values returns ['uk', 'usa']
d.get("maggie", "nowhere") #returns uk
d.get("ringo", "... |
forward = []
backward = []
values = ["a", "b", "c"]
for item in values:
forward.append(item)
backward.insert(0, item)
print "forward is:", forward
print "backward is:", backward
forward.reverse()
print forward ==backward |
a = set([0, 1, 2, 3, 4, 5])
b = set([2, 4, 6, 8])
print a.union(b) #union means show all the elements in both sets as one list but each element appears only once
print a.intersection(b) #intersection shows which elements appear in both sets |
s = 'I love to write Python'
split_s = s.split() #unless told otherwise it assumes split by spaces, if want to split commans then need x.split(',')
print split_s
for word in split_s:
if word.find("i") > -1: #if not there gives -1, here we're saying if it's more than -1 then it's true it's there
print "I f... |
class Word_Pair:
def __init__(self, german_word, english_word):
assert (type(german_word) == str and type(english_word) == str)
self.german = german_word
self.english = english_word
def __str__(self):
return ("Word_Pair(\'" + self.german + "\', \'" + self.english +... |
import turtle
turtle.setup(800,600) # Set the width and height be 800 x 600
number_of_divisions = 8 # The number of subdivisions around the centre
turtle_width = 3 # The width of the turtles
# Don't show the animation
turtle.tracer(False)
# Draw the background lines
backgroundTurtle = turtle.Turtle()... |
import matplotlib.pyplot as plt
import pandas as pd
# from PIL import Image
# age = [5,10,15,20,25,30]
# height = [30, 45, 100, 120,150,180]
# plt.plot(age,height, color='red', alpha=0.5)
# plt.xlabel('age')
# plt.ylabel('height')
# plt.title('My Growth')
# plt.show()
# Puppy behavior thoroughout the day
# pup_pic =... |
"""
结果一定在S中,因此我们没有必要把S展开再求。而且这样做(当测试样例"y959q969u3hb22odq595")会出现内存溢出的现象。因此可以想办法在原始S中求第K为,1.算出展开S的长度为N,2所求位置为k%S。因此倒序遍历S,遇见数字d,N=N/d,遇见字母N=N-1;直到K%N==0。输出此处字符
"""
class Solution:
def decodeAtIndex(self, S, K):
"""
:type S: str
:type K: int
:rtype: str
"""
length = 0
... |
import queue
class Solution:
def slidingPuzzle(self, board):
"""
:type board: List[List[int]]
:rtype: int
"""
goal = "123450"
start = ""
for i in range(0, len(board)):
for j in range(0, len(board[0])):
start += str(board[i][j])
... |
import os
import csv
from typing import Text
#paths to csv
os.chdir(os.path.dirname(os.path.realpath(__file__)))
bank_data_cvs= os.path.join("Resources", "budget_data.csv")
#reads csv
with open(bank_data_cvs, 'r') as csvfile:
csvreader = csv.reader(csvfile, delimiter=",")
header = next(csvreader)
file = open(b... |
"""
函数是组织好的,可重复使用的,用来实现单一,或相关联功能的代码段。
函数能提高应用的模块性,和代码的重复利用率。
python 内置:
print函数 type函数 input函数 open函数
函数的分类:
参数 返回值
有参 有返回值
有参 无返回值
无参 有返回值
无参 无返回值
函数的定义:
def 函数名(参数,参数1,参数2=默认值):
函数代码块
[return]
"""
# 求和 有参有返回值
def add(a,b):
return a+b
# 求和 有参无返回值
def printAdd(a... |
import os
import sqlite3
import pandas as pd
# Save the filepath for the DB to a variable
DB_FILEPATH = os.path.join(os.path.dirname(__file__), "rpg_db.sqlite3")
# Intanstiate the connection
connection = sqlite3.connect(DB_FILEPATH)
# print("CONNECTION:", connection)
# Instantiate the cursor
cursor = connection.curs... |
import itertools
from typing import Iterable, Iterator, List, Optional, Tuple, TypeVar
T = TypeVar('T')
def window(iterator: Iterable[T], behind: int = 0, ahead: int = 0) -> Iterator[Tuple[Optional[T], ...]]:
"""
Sliding window for an iterator.
Example:
>>> for prev, i, nxt in window(range(10), ... |
# Run this script and enter 3 numbers separated by space
# example input '5 5 5'
a,b,c=map(int,raw_input().split())
for i in range(b+c+1):print(' '*(c-i)+((' /|'[(i>c)+(i>0)]+'_'*4)*(a+1))[:-4]+('|'*(b+c-i))[:b]+'/')[:5*a+c+1]
|
"""
7.4 – Ingredientes para uma pizza: Escreva um laço que peça ao usuário para
fornecer uma série de ingredientes para uma pizza até que o valor 'quit' seja
fornecido. À medida que cada ingrediente é especificado, apresente uma
mensagem informando que você acrescentará esse ingrediente à pizza.
"""
while True:
in... |
"""
8.13 – Perfil do usuário: Comece com uma cópia de user_profile.py, da página
210. Crie um perfil seu chamando build_profile(), usando seu primeiro nome
e o sobrenome, além de três outros pares chave-valor que o descrevam.
"""
def build_profile(first_name, last_name, **user_info):
"""Constrói um dicionário con... |
"""
4.12 – Mais laços: Todas as versões de foods.py nesta seção evitaram usar laços for para fazer exibições a fim de economizar espaço. Escolha uma versão de foods.py e escreva dois laços for para exibir cada lista de comidas
"""
my_foods = ['pizza', 'falafel', 'carrot cake']
friend_foods = my_foods[:]
my_foods.app... |
"""
5.3 – Cores de alienígenas #1: Suponha que um alienígena acabou de ser atingido em um jogo. Crie uma variável chamada alien_color e atribua-lhe um
alor igual a 'green', 'yellow' ou 'red'.
• Escreva uma instrução if para testar se a cor do alienígena é verde. Se for, mostre uma mensagem informando que o jogador aca... |
"""
6.4 – Glossário 2: Agora que você já sabe como percorrer um dicionário com um laço, limpe o código do Exercício 6.3 (página 148), substituindo sua sequência de instruções print por um laço que percorra as chaves e os valores do dicionário. Quando tiver certeza de que seu laço funciona, acrescente mais cinco termos ... |
"""
7.10 – Férias dos sonhos: Escreva um programa que faça uma enquete sobre as
férias dos sonhos dos usuários. Escreva um prompt semelhante a este: Se
pudesse visitar um lugar do mundo, para onde você iria? Inclua um bloco de
código que apresente os resultados da enquete.
"""
enquete = {}
participantes = 0
while True:... |
"""
8.11 – Mágicos inalterados: Comece com o trabalho feito no Exercício 8.10.
Chame a função make_great() com uma cópia da lista de nomes de mágicos.
Como a lista original não será alterada, devolva a nova lista e armazene-a em
uma lista separada. Chame show_magicians() com cada lista para mostrar que
você tem uma lis... |
"""
5.9 – Sem usuários: Acrescente um teste if em hello_admin.py para garantir que a lista de usuários não esteja vazia.
• Se a lista estiver vazia, mostre a mensagem Precisamos encontrar alguns usuários!
• Remova todos os nomes de usuário de sua lista e certifique-se de que a mensagem correta seja exibida.
"""
users ... |
"""
4.10 – Fatias: Usando um dos programas que você escreveu neste capítulo, acrescente várias linhas no final do programa que façam o seguinte:
• Exiba a mensagem Os três primeiros itens da lista são: Em seguida, use uma fatia para exibir os três primeiros itens da lista desse programa.
• Exiba a mensagem Três itens ... |
"""
10.1 – Aprendendo Python: Abra um arquivo em branco em seu editor de texto e
escreva algumas linhas que sintetizem o que você aprendeu sobre Python até
agora. Comece cada linha com a expressão Em Python podemos.... Salve o
arquivo como learning_python.txt no mesmo diretório em que estão seus
exercícios deste capítu... |
"""
10.13 – Verificando se é o usuário correto: A última listagem de
remember_me.py supõe que o usuário já forneceu seu nome ou que o programa
está executando pela primeira vez. Devemos modificá-lo para o caso de o
usuário atual não ser a pessoa que usou o programa pela última vez.
Antes de exibir uma mensagem de boas-... |
"""
6.8 – Animais de estimação: Crie vários dicionários, em que o nome de cada dicionário seja o nome de um animal de estimação. Em cada dicionário, inclua o tipo do animal e o nome do dono. Armazene esses dicionários em uma lista chamada pets. Em seguida, percorra sua lista com um laço e, à medida que fizer isso, apre... |
"""
10.8 – Gatos e cachorros: Crie dois arquivos, cats.txt e dogs.txt. Armazene pelo
menos três nomes de gatos no primeiro arquivo e três nomes de cachorro no
segundo arquivo. Escreva um programa que tente ler esses arquivos e mostre o
conteúdo do arquivo na tela. Coloque seu código em um bloco try-except
para capturar... |
"""
BirdsEyeTransformation.py
This program converts the input video into a “bird’s eye” output video.
It converts a frame into the bird’s eye transformation, so that the road is rectangular
Give path to directory with images as input after running the program
@author: Anushree Das (ad1707)
"""
import cv2 as cv
from... |
#!/usr/bin/env python
# Module import sys
import sys
def celsius_to_fahr(temp_c):
temp_f=temp_c* (9.0/5.0) +32
return temp_f
def main()
try:
cels=float(sys.argv[1])
print(celsious_to_fahr(cels))
except:
print("First argument must ne a number! if _name_ ="_main_")
print('hello')
print('These are the argume... |
y = 1
num = int(input('Enter you number--'))
for x in range(1,num+1):
y=y*x
print('factorial of '+ str(num) +' is ='+ str(y)) |
# Importing libraries
import cv2
# Deffining a function for detecting motion
def imageDifference(x,y,z):
# Taking difference between frames
image1=cv2.absdiff(x,y)
image2=cv2.absdiff(y,z)
# Calculating differences in two frames
finalDifference=cv2.bitwise_and(image1,image2)
# Retur... |
names = ['zhangyang','guyun','guozi','helloworld']
print(names)
# 查
print(names[0])
print(names[1])
print(names[2])
print(names[1:3]) # 顾头不顾尾 切片
print(names[0:4]) # 顾头不顾尾 切片
print(names[:4]) # 顾头不顾尾 切片
names.append('leihaidong')
print(names[-3:-1])
print(names[-3:])
print(names)
# 增
names.insert(1,'insert')
print(... |
reply = int(input())
if reply % 3 == 0 and reply % 5 == 0:
print("FizzBuzz")
elif reply % 3 == 0:
print("Fizz")
elif reply % 5 == 0:
print("Buzz")
else:
print("") |
class Time:
# Конструктор, принимающий четыре целых числа: часы, минуты, секунды и миллисекунды.
# В случае, если передан отрицательный параметр, вызвать исключение ValueError.
# После конструирования, значения параметров времени должны быть корректными:
# 0 <= GetHour() <= 23
# 0 <= GetMinute() <= ... |
import pandas as pd
import numpy as np
def get_catecorials(data, drop_features=None):
"""Get categorical data from a dataset
Input
=====
"""
features = np.setdiff1d(data.columns.tolist(), drop_features).tolist()
# Which one are objects types
data_objects = data[features].loc[:, data.dtypes == ... |
# Function to calculate the minimum
# number of elements to be removed
# satisfying the conditions
def minimumDeletions(arr, N):
# Stores the final answer
ans = 0
# Map to store frequency
# of each element
mp = {}
# Traverse the array arr[]
for i in arr:
mp[i] = mp.... |
f = open('archivo.txt', 'w')
lines = []
op = ''
while op != 'T':
if op == 'A':
line = input('Ingrese el texto: ')
lines.append(line + '\n')
op = input('¿Deseas añadir una línea al archivo (A) o terminar (T)?')
f.writelines(lines)
f.close()
f = open('archivo.txt', 'r')
for line in f:
print(l... |
from picoh import picoh
# Reset Picoh
picoh.reset()
'''
The picoh.move() function needs at least 2 arguments: movement name and desired position.
picoh.HEADTURN
picoh.HEADNOD
picoh.EYETURN
picoh.EYETILT
picoh.BOTTOMLIP
picoh.LIDBLINK
position can be any number 0-10.
'''
# Move the HEADTURN motor to 2.
picoh.move(... |
#PROGRAM TO FIND AREA AND PERIMETER OF RECTANGLE
l=int(input("Enter the length "))
b=int(input("Enter the breadth "))
area=l*b
perimeter=2*(l+b)
print("The area is",area)
print("The perimeter is",perimeter)
|
# https://programmers.co.kr/learn/courses/30/lessons/12937
# Difficulty : Level 1
1) First Solution
def solution(num):
ans=["Even","Odd"]
return ans[num%2]
# Example :
# solution(3) ==> "Odd"
# solution(4) ==> "Even"
|
# Funciones lambda (funciones anonimas), abreviar la sintaxis. Consiste en resumir una funcion en python por una funcion lambda.
# Python 3.7
# Jr2r
#
#Funcion tradicional
'''def area_triangulo(base, altura):
return (base*altura)/2
print(area_triangulo(5, 7))'''
#Funcion reducida con lambda, toma arg... |
# Python 3.7
#jr2r
# Counting Valleys
l = ""
c = 0
myRe = []
#Path list to iterate
path = list("DDUUDDUDUUUD")
for i in path:
if l == "":
l = i
c += 1
else:
if l == i:
c += 1
else:
if c >= 3:
myRe.append(c)
... |
# Function to estimate insurance cost:
def estimate_insurance_cost(name, age, sex, bmi, num_of_children, smoker):
estimated_cost = 250*age - 128*sex + 370*bmi + 425*num_of_children + 24000*smoker - 12500
print(name + "'s Estimated Insurance Cost: " + str(estimated_cost) + " dollars.")
return estimated_cost
# Es... |
# Simple Linear Regression
# importing libraries
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
# importing datasets
dataset = pd.read_csv("Salary_Data.csv")
X=dataset.iloc[:,:-1].values
y=dataset.iloc[:,1].values
# splitting dataset into traing and testing
from sklearn.cross_v... |
__author__ = 'trunghieu11'
import random
def sumOfDegit(x):
answer = 0
for c in str(x):
answer += int(ord(c) - ord('0'))
return answer if answer < 10 else sumOfDegit(answer)
def bruteForce(begin, distance, left, right):
answer = 0
left -= 1
for i in range(0, right):
if i >= le... |
class ValueOfString:
def findValue(self, strx):
sumx=0
for i in strx:
t = 0
for j in strx:
if j <= i:
t += 1
sumx += (ord(i)-96)*t
return (sumx)
##########################
# BEGIN TEST #
###################... |
__author__ = 'trunghieu11'
def gcd(a, b):
a, b = abs(a), abs(b)
while b != 0:
a, b = b, a % b
return a
class GCDGraph:
def possible(self, n, k, x, y):
lstFrom = []
lstTo = []
for i in range(k + 1, x + 1):
if x % i == 0:
lstFrom.append(i)
... |
__author__ = 'trunghieu11'
def check(first, second):
if first == second:
return True
if len(first) % 2 == 1:
return False
half = len(first) / 2
return (check(first[:half], second[half:]) and check(first[half:], second[:half])) or (check(first[:half], second[:half]) and check(first[half... |
__author__ = 'trunghieu11'
def solve(hexagon):
answer = hexagon[0] + hexagon[1] + hexagon[2]
answer = answer * answer - hexagon[0] * hexagon[0] * 3
return answer
if __name__ == '__main__':
hexagon = list(map(int, raw_input().split(" ")))
print solve(hexagon) |
# age=int(input("Enter your age"))
# if age==18:
# print("Wait for some days")
# elif age>18:
# print("You are able to drive.")
# else:
# print("You are not able to drive") |
# Strings
"""
7. Write a Python program to get a string from a given string where all occurrences of
the last character have been changed to ‘*’, except the last character itself.
"""
st="GREATER"
length=len(st)
ch=st[length-1]
st=st.replace(ch,"*")
ch=st[length-1]
print(st)
|
# List
"""
8. Write a Python program to find the maximum of a list of numbers.
"""
lis=[1,2,3,4,5,6,7,8,100]
a=max(lis)
print("THE MAXIMUM NUMBER OF THIS LIST IS ",a) |
# 股票买卖的最大利润
# 一次买入卖出:双指针,找股票最低点买入
prices = [1,2,3,0,2]
def oneMaxProfit(prices):
res = 0
minp = prices[0]
for p in prices:
if p<minp:
minp = p
elif p-minp>res:
res = p-minp
return res
# 多次买入卖出:赚差价:只要前一天价格比后一天低,就买入卖出
def moreMaxProfit(prices):
res = 0
for... |
import figures
figuresList = []
for i in range(3):
choice = input("Круг(к), прямоугольник(п) или треугольник(т): ")
if choice == 'к':
figure = figures.Circle(float(input("Радиус: ")))
elif choice == 'п':
l = float(input("Длина: "))
w = float(input("Ширина: "))
... |
#Grading a multiple choice exam is easy.
# But how much do multiple choice exams tell us about what a student really knows?
# Dr. Dirac is administering a statistics midterm exam and wants to use Bayes’ Theorem to help him understand the following:
# - Given that a student answered a question correctly, what is th... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.