text stringlengths 37 1.41M |
|---|
def bubblesort(a):
j = 0
while j != (len(a)-1):
j = 0
for i in range(0, (len(a)-1)):
first = a[i]
second = a[i+1]
if first > second:
a[i] = second
a[i+1] = first
else:
j = j+1
print (a)
return a
a = [9,2,7,1,6,3,7,8]
bubblesort(a) |
class Road():
def __init__(self, length=1000, curve=0):
self.length = length
self.curve = curve
def road_loop(self, car_list, car, next_car):
if next_car.position[0] - 5 < 6:
car.position[0] = 1000
car.speed = 0
else:
car.position[0] -= 1000
car_list.insert(0, car_list.pop())
car.collision_che... |
import os
import random
def clear_output():
if os.name == 'nt':
os.system('cls')
else:
os.system('clear')
suits = ('Hearts', 'Diamonds', 'Spades', 'Clubs')
ranks = ('Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight', 'Nine', 'Ten', 'Jack', 'Queen', 'King', 'Ace')
values = {'Two':2, '... |
# -*- encoding: utf-8 -*-
'''
@File : 定长数组实现队列.py
@Time : 2020/06/08 17:47:40
@Author : windmzx
@Version : 1.0
@Desc : For leetcode template
'''
# here put the import lib
from typing import List
class MyQueue:
def __init__(self, size):
super().__init__()
self.head = 0
... |
# -*- encoding: utf-8 -*-
'''
@File : 面试题59 - II. 队列的最大值.py
@Time : 2020/05/09 11:41:43
@Author : windmzx
@Version : 1.0
@Desc : For leetcode template
'''
# here put the import lib
from typing import List
import queue
import queue
class MaxQueue:
def __init__(self):
self.maxqueue =... |
# -*- encoding: utf-8 -*-
'''
@File : 面试题12. 矩阵中的路径.py
@Time : 2020/06/07 14:44:02
@Author : windmzx
@Version : 1.0
@Desc : For leetcode template
'''
# here put the import lib
from typing import List
class Solution:
def exist(self, board: List[List[str]], word: str) -> bool:
m = len(... |
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def hasCycle(self, head: ListNode) -> bool:
if head is None:
return False
p1=head
p2=p1.next
while p2!=p1:
if p1.next... |
# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
res = 0
def diameterOfBinaryTree(self, root: TreeNode) -> int:
def helper(root):
if root is None:
return ... |
# -*- encoding: utf-8 -*-
'''
@File : 110. 平衡二叉树.py
@Time : 2020/04/27 21:12:31
@Author : windmzx
@Version : 1.0
@Desc : For leetcode template
'''
# here put the import lib
from typing import List
# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = ... |
from typing import List
class Solution:
def largestRectangleArea(self, heights: List[int]) -> int:
maxarea=0
heights=[0]+heights+[0]
stack=[]
for i in range(len(heights)):
# 栈顶元素大于当前元素
while stack and heights[stack[-1]] > heights[i]:
temp=stac... |
# -*- encoding: utf-8 -*-
'''
@File : 88. 合并两个有序数组.py
@Time : 2020/04/23 09:24:45
@Author : windmzx
@Version : 1.0
@Desc : For leetcode template
'''
# here put the import lib
from typing import List
class Solution:
def merge(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None:
... |
class Solution:
def isAdditiveNumber(self, num: str) -> bool:
length=len(num)
def isactive(num1,num2,k):
num3=num1+num2
index=k+1
while index<=length:
if str(int(num[k:index]))==num[k:index] and int(num[k:index])==num3:
num1=... |
from typing import List
class Solution:
def reconstructQueue(self, people: List[List[int]]) -> List[List[int]]:
flag=True
while flag:
flag=False
for i in range(1,len(people)):
a1=people[i-1]
a2=people[i]
if a1[0]<a2[0]:
... |
from typing import List
class Solution:
def isValidSudoku(self, board: List[List[str]]) -> bool:
def check(row, col):
com = board[row][col]
for i in range(row//3*3, row//3*3+3):
for j in range(col//3*3, col//3*3+3):
if i == row and j == col:
... |
from typing import List
class Solution:
def removeInvalidParentheses(self, s: str) -> List[str]:
def isvaild(s:str):
count=0
for i in s:
if i=='(':
count+=1
elif i==')':
count-=1
if count<0:
... |
help(open) #справка по работе функции open()
f = open("files/Толстой.txt", mode="rb") #открыть файл Толстой.txt, лежащий в папке files, лежащей в одной папке с питоновским файлом
f.read(20) #считать первые 20 байт
data = open("files/Толстой.txt", mode="rb").read() #считать файл
print(ty... |
import numpy as np
# -------------------
# SELECTION OPERATORS
# -------------------
class Selection_Proportionate:
'''
Proportionate selection operator
***WARNING***: This operator will NOT give the expected
results cases where fitness values can be negative.
Another operator must be used in this... |
import unittest
from morse_translator.translator import Translator, TranslationException
from morse_translator.dictionary import Dictionary
class TranslatorTests(unittest.TestCase):
def setUp(self):
self.translator = Translator()
def test_constructor(self):
"""
Ensure the constructor... |
#!/usr/bin/env python3
# Created by: Lily Liu
# Created on: Oct 2021
# This program will convert °C to °F
def fahrenheit():
# This function will convert °C to °F
# input
user_temp = input("Enter a temperature (°C) : ")
# process & output
try:
user_temp = int(user_temp)
f_temp = ro... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Jan 10 12:21:55 2020
@author: nmbice
"""
from fol_syntax_semantics import parse, tokenize, evaluate, Model
import re
import string
#model = Model({1,2,3})
#model.interp = {'L': {(1,2), (2,1), (3,1)}, 'E': {2}, 'P': {}, 'G': {(2,1), (3,1), (3,2)}, '=':... |
"""
Script for importing students by course in Canvas.
"""
from security import canvas_key
import csv
import requests
from datetime import datetime
def course_students(course_id: int):
"""
Takes in a course's ID, and returns a list of students in the course, containing dictionaries with their n... |
import numpy as np
import math
# import functools
class Geometry:
@staticmethod
def distance(point): # shape=(2, ) 支持非ndarray
return np.hypot(*point)
@staticmethod
def distances(points): # shape=(n, 2) or (2, ) 必须为ndarray
return np.hypot(*points.T)
@classmet... |
# Crie um pacote chamado utilidadesCeV que tenha dois módulos internos chamados moeda e dado
# Transfira todas as funções utilizadas nos DESAFIOS 107, 108 e 109 para o primeiro pacote e mantenha tudo funcionando
from utilitiescev import currency
price = float(input('Digite o preço: R$ '))
rateOfIncrease = int(input('... |
# Escreva um programa que pergunte o salário de um funcionário e calcule o valor de seu aumento
# Para salários superiores a R$ 1.250,00, calcule um aumento de 10%
# Para os inferiores ou iguais o aumento é de R$ 15%
currentSalary = float(input('Qual é o salário do funcionário? R$ '))
if currentSalary > 1250:
per... |
# Faça um programa que ajude um jogador da MEGA SENA a criar palpites
# O programa vai perguntar quantos jogos serão gerados e vai sortear 6 números entre 1 e 60 para cada jogo, cadastrando tudo em uma lista composta
# Resolução proposta pelo professor
# from random import randint
# from time import sleep
#
# list = [... |
def increase(value, rate):
increased = value + (value * rate / 100)
return increased
def decrease(value, rate):
decreased = value - (value * rate / 100)
return decreased
def double(value):
doubled = value * 2
return doubled
def half(value):
halved = value / 2
return halved
|
# Crie um programa que vai ler vários números e colocar em uma lista
# Depois disso, crie duas listas extras que vão conter apenas os valores pares e o valores ímpares digitados, respectivamente
# Ao final, mostre o conteúdo das três listas geradas
listFull = []
listPairs = []
listOdd = []
while True:
proceed = '... |
# Elabore um programa que calcule o valor a ser pago por um produto, considerando o seu preço normal e condição de pagamento:
# - À vista dinheiro/cheque: 10% de desconto
# - À vista no cartão: 5% de desconto
# - Em até 2x no cartão: preço normal
# - 3x ou mais no cartão: 20% de juros
from sys import exit
colors = {
... |
# Crie um programa que leia o nome e o preço de vários produtos
# O programa deverá perguntar se o usuário vai continuar
# No final, mostre:
# A) Qual é o total gasto na compra
# B) Quantos produtos custam mais de R$ 1000
# C) Qual é o nome do produto mais barato
colors = {
'clear': '\033[m',
'txtGreenNormal':... |
# Desenvolva um programa que leia o nome, idade e sexo de 4 pessoas
# No final do programa, mostre:
# A média de idade do grupo
# Qual é o nome do homem mais velho
# Quantas mulheres tem menos de 20 anos
from sys import exit
counterAge = 0
olderManAge = 0
counterWoman = 0
for i in range(1, 5):
print('\n----- {}ª... |
# Refaça o DESAFIO 035 dos triângulos, acrescentando o recurso de mostrar que tipo de triângulo será formado:
# - Equilátero: todos os lados iguais
# - Isósceles: dois lados iguais
# - Escaleno: todos os lados diferentes
print('-=' * 12)
print('Analisador de Triângulos')
print('-=' * 12)
n1 = float(input('Primeiro seg... |
# Faça um programa que leia uma frase pelo teclado e mostre:
# Quantas vezes aparece a letra "A"
# Em que posição ela aparece a primeira vez
# Em que posição ela aparece a última vez
phrase = str(input('Digite uma frase: ')).strip()
print('Na frase digitada, a letra "A" aparece {} vezes' .format(phrase.upper().count('... |
# Refaça o DESAFIO 009, mostrando a tabuada de um número que o usuário escolher, só que agora utilizando um laço for
n = int(input('Digite um número para ver sua tabuada: '))
print('\nTABUADA DE {}' .format(n))
for i in range(1, 11):
print('{} x {:>2} = {}' .format(n, i, (n * i)))
|
# Modifique as funções que foram criadas no DESAFIO 107 para que elas aceitem um parâmetro a mais, informando se o valor
# retornado por elas vai ser ou não formatado pela função moeda(), desenvolvida no DESAFIO 108
import currency
price = float(input('\nDigite o preço: R$ '))
print(f'A metade de {currency.currency... |
# Faça um programa que tenha uma função chamada área(), que receba as dimensões de um terreno retangular (largura e
# comprimento) e mostre a área do terreno
def area(width, length):
print(f'A área de um terreno {width}m x {length}m é de {width * length:.1f}m²')
print(' Controle de Terrenos')
print('-' * 22)
w =... |
# Crie um programa que faça o computador jogar Jokenpô com você
from sys import exit
from time import sleep
from random import randint
options = ('PEDRA', 'PAPEL', 'TESOURA')
# Jogada do computador
numberRandom = randint(0, 2)
computerChoice = options[numberRandom]
# Jogada do jogador
print('''Suas opções:
[ 0 ] PE... |
def sum_mul(choice, *args):
if choice == "sum":
result = 0
for i in args:
result=result+i
elif choice =="sub":
result = args[0]
for i in args[1:]:
result=result-i
elif choice == "mul":
result =1
for i in args:
result = resul... |
"""
PROBLEM
Check Permutation:
* Given two strings,write a method to decide if one is a permutation of the
other.
"""
"""
Notes:
* Bit manipulation trick: If all characters in s1 have a corresponding match in s2,
then they are a permutaion of each other
* Base case should be communicated with the inteviewer clearl... |
"""
PROBLEM
Palindrome Permutation:
* Given a string, write a function to check if it is a permutation of a palindrome.
* A palindrome is a word or phrase that is the same forwards and backwards.
* A permutation is a rearrangement of letters.
* The palindrome does not need to be limited to just dictionary words.
... |
"""
PROBLEM
Stack of Plates:
* Imagine a (literal) stack of plates. If the stack gets too high, it might topple.
* Therefore, in real life, we would likely start a new stack when the previous stack exceeds some threshold.
* Implement a data structure SetOfStacks that mimics this. SetOfStacks should be composed of ... |
"""
PROBLEM
Animal Shelter:
* An animal shelter, which holds only dogs and cats, operates on a strictly "first in, first out" basis.
* People must adopt either the "oldest" (based on arrival time) of all animals at the shelter,
or they can select whether they would prefer a dog or a cat (and will receive the oldes... |
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def mergeKLists(self, lists):
"""
:type lists: List[ListNode]
:rtype: ListNode
"""
if not lists:
... |
# In Python3, addition can be done very easily with numbers and strings
7 + 2
# By writing 7+2 it directly gives the addition output
# Strings :-
'Hello' + 'World'
# Above code will merge 2 strings and gives output HelloWorld
|
"""
Created by: Gavin Ng
Read README for more information about python-turnip in general and its associated files
"""
# File Imports
import trends
import printer
# Setup for Cycles
cycleconverter = ["Monday AM","Monday PM","Tuesday AM","Tuesday PM","Wednesday AM","Wednesday PM","Thursday AM","Thursday PM","Friday AM"... |
class Atividade09():
def input(self, string, numRep):
print(string * numRep)
validator = Atividade09()
string = input("Digite a palavra que deseja repetir")
numRep = int(input("Digite a quantidade de repetições que deseja"))
validator.input(string,numRep)
|
def hashFunc(piece):
words = piece.split(" ") #splitting string into words
colour = words[0]
shape = words[1]
poleNum = 0
for i in range(0, 3):
poleNum += ord(colour[i]) - 96
poleNum += ord(shape[i]) - 96
return poleNum
|
# Numbers - Tax Calculator (WIP)
"""
1) User inputs amount.
2) User inputs whether service charge is included. Default 10%.
3) Returns full price.
4) Optional: Splitting of bill by number of people.
5) Optional: Rounding of split bill to nearest dollar.
"""
# Imports
import subprocess
# Sets default ... |
#Text - Pig latin (Sentence)
#Current solution was is to add 'ay' to the end of each word, shift the first letter back, then add the '-'.
#Further reading has revealed that pig latin is not as simple as it looks.
#Both consonants and consonant clusters at the start of words are shifted back.
#Vowels are not shifted ba... |
#
# Complete the 'print_full_name' function below.
#
# The function is expected to return a STRING.
# The function accepts following parameters:
# 1. STRING first
# 2. STRING last
#
from string import Template
def getStringFromTemplate(templateObj,varDict):
return templateObj.substitute(varDict)
FULLNAME_TEMPL... |
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution(object):
def rightSideView(self, root):
"""
:type root: TreeNode
:rtype: List... |
if __name__ == '__main__':
x = int(raw_input())
y = int(raw_input())
z = int(raw_input())
n = int(raw_input())
list3d = [[a,b,c] for a in range(0,x+1) for b in range(0,y+1) for c in range(0,z+1)]
def checkForSum(arr):
if (arr[0]+arr[1]+arr[2])==n:
return False
... |
from zoo import Zoo
from animal import Animal
class SimulateZoo:
DAYS_IN_WEEK = 7
DAYS_IN_MONTH = 30
DAYS_IN_YEAR = 365
def __init__(self, zoo):
self.zoo = zoo
def simulate(self, command):
command[1] = int(command[1])
if command[2] == "years":
days = command[1... |
from datetime import datetime
from functools import reduce
from util import contains, write_to_file
def generate_output(key, value_tuple):
date_str = value_tuple[1].strftime("%Y-%m-%d %H:%M:%S")
return "{}\t{}\t{}\n".format(key, date_str, str(value_tuple[0]))
def calculate_busiest_time(key_values_dict, key_va... |
#!/usr/bin/env python3
import itertools
# encrypted key1, key2 and flag (from scrambledeggs.txt)
ekey1 = 'xtfsyhhlizoiyx'
ekey2 = 'eudlqgluduggdluqmocgyukhbqkx'
eflag = 'lvvrafwgtocdrdzfdqotiwvrcqnd'
scramble_map = ['v', 'r', 't', 'p', 'w', 'g', 'n', 'c', 'o', 'b', 'a', 'f', 'm', 'i', 'l', 'u', 'h', 'z', 'd', 'q', 'j... |
# -*- coding: utf-8 -*-
def steffensen(f, x0, tol):
if tol <= 0:
print("illegal value for tolerance")
return
for i in range(1, 1000):
y0 = f(x0)
x = x0 - y0 * y0 / (f(x0 + y0) - y0)
if abs(x - x0) < tol:
print("found root", x, "in", i, "iteration(s)")
... |
#using machine and utime Micropython libraries
import machine
import utime
buzzer = machine.Pin(2,machine.Pin.OUT) #The buzzer is attached to pin D4 on the NodeMCU
motor = machine.PWM(machine.Pin(14), freq = 50) #The motor driver is attached to pin D5 on the NodeMCU
#time parameters defined as empty arrays
first_rel... |
############################ dAY 7 ########################
############################ hANGMAN pROJECT ##################
#Step 1
import random
stages = ['''
+---+
| |
O |
/|\ |
/ \ |
|
=========
''', '''
+---+
| |
O |
/|\ |
/ |
|
=========
''', '''
+---+
| |
... |
# Python 3 - Polling radio buttons tkinter program
# Author: J.Smith
# Import tkinter library
from tkinter import *
import tkinter.messagebox as box
# A window
window = Tk()
window.title('Radio Button Example')
# Frame to contain widgets
frame = Frame(window)
# String variable to store a selection
book = StringVar(... |
x= int(input("Digite el primer numero: "))
y= int(input("Digite el segundo numero: "))
def resta(x,y,):
return x-y
def multiplicacion(x,y):
return x*y
def division(x,y):
return x//y
def divisionres(x,y):
return x%y
print("La resta de tus dos numero es: ", resta (x,y))
print("La multiplicacion de ... |
numero1= int(input("En que numero comienza la lista: "))
numero2= int(input("En que numero termina la lista: "))
lista=list(range(numero1,numero2+1))
for n in lista:
inverso_n=int(str(n)[::-1])
suma=inverso_n+n
inverso_checa=int(str(suma)[::-1])
if n==inverso_n:
print(n,"es palindromo"... |
import random
contador=0
respuesta=0
n=random.randint(0,101)
while respuesta!=n:
respuesta=0
respuesta = int(input("Intente adivinar el numero: "))
if respuesta>n:
contador=contador+1
print(respuesta," es mayor, intenta con otro numero mas pequeño")
elif respuesta<n:
conta... |
def adding_natural():
sum_of=0
for x in range(1,number+1):
sum_of+=x
sum_of=sum_of**(2)
return sum_of
def mult_natural():
multi=0
for x in range(1,number+1):
multi= multi + (x**(2))
return multi
try:
print("Choose your number")
number=eval(input())
print(adding_n... |
import numpy as np
class Perceptron(object):
# constructor for creating object of class perceptron
def __init__(self, no_of_inputs, epoch=20, learning_rate=0.01):
# epoch determines, how many times each training example would pass through perceptron
self.epoch = epoch
# learnin... |
koniec_przedzialu = int(input("Podaj koniec przedzialu: "))
lista = []
lista_new = []
def stworzliste(koniec_przedzialu):
for i in range (2,koniec_przedzialu+1):
minimum = min(i,koniec_przedzialu)
lista.append(minimum)
stworzliste(koniec_przedzialu)
print ("Podany przedzial zawiera liczby:")
print... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Questão 1
Modele o problema do Restaurante (mencionado no capítulo 18 do livro texto)
para ser resolvido por meio de árvore de decisão e por meio de KNN (com k = 1 e com k = 5).
Este código trata só de arvores de devisão
"""
import pandas as pd
from sklearn.preproc... |
# The script intends to read data from the excel file
def read():
import requests
from requests.exceptions import MissingSchema
import xlrd
#stores the name of the sites from the excel as a list
sites=[]
# Hardcode the location of the excel file here
file_location=r'C:\Users\panka... |
import tkinter as tk
from tkinter import *
import math
class paceCalculator:
#**def clear_search(event):
#self.entTime.delete(0, END)
#***def clear_search2(event):
#self.entDS.delete(0, END)
def __init__(self):
self.root = tk.Tk()
self.root.configure(background = "navy")
self.root.geometry('400x400... |
#!/usr/bin/python
import csv
from twython import Twython
from twython import TwythonStreamer
class TwitterStream(TwythonStreamer):
'''
Implements twitter api using the TwythonStreamer subclass.
'''
def on_success(self, data):
'''
required 'TwythonStreamer' method called when twi... |
# coding: utf-8
# # Project for Neural Networks lecture
#
# ## Deep Learning
#
# ## Project: Build a CIFAR10 Recognition Classifier
# 
# Source: Yan LeCun
#
# In this project, I will use deep neural networks and convolutional neural networks to classify CIFAR10 dataset from [http:/... |
from keras.layers import Input, Dense, Flatten
from keras.models import Model
def model(input_shape=(150,150,3)):
# Input layer
inputs = Input(shape=input_shape)
# Hidden & output layers
x = Dense(32, activation='relu')(inputs)
x = Dense(32, activation='relu')(x)
x = Flatten()(x)
predictio... |
unos=int(raw_input("Unesi broj izmedu 1 i 100:"))
for unos in range(1,unos+1):
if unos%15==0:
print "FizzBuzz"
elif unos%5==0:
print "Buzz"
elif unos%3==0:
print "Fizz"
else:
print unos
|
#!/usr/bin/env python3
import sys
def main(args):
print("Hello world!")
pos=(0,0)
x=0
up=(0,1)
down=(0,-1)
left=(1,0)
right=(-1,0)
dir=[up,left,down,right]
for i in argv[1]:
if (i=='L'):
x+=1
elif (i=='R'):
x-=1
if (x==4):
... |
import csv, os
# Function to grab the CSV files and prep them for the CSV Reader.
def filelist(*files):
for f in files:
global fname
fname = os.path.basename(f) # Assign the file names to the fname variable.
with open(f) as fobj:
next(fobj)
for line in fobj:
yield line... |
# -*- coding: utf-8 -*-
"""
Created on Mon Mar 15 10:22:11 2021
@author: Jarrod Daniels
"""
import string
### takes a single integer as input and returns the sum of the integers from zero to the input parameter.
def add_it_up(int):
total = 0
num_list = list(range(1, int+1))
for num in num_list:
t... |
#
# Script to generate puzzles based on Raymond Smullyan's
# 'Alice in the Forest of Forgetfulness' puzzles from
# 'What is the Name of this Book?'
#
# first we define the days of the week
daysOfWeek = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']
# if we say one of several days was... |
# Problem Set 4A
# Name: <your name here>
# Collaborators:
# Time Spent: x:xx
def get_permutations_count(n):
if n==1:
return 1
else:
return n*get_permutations_count(n-1)
def permutation(lst):
# If lst is empty then there are no permutations
if len(lst) == 0:
return []
... |
# def build_shift_dict(self, shift):
# shift_dict={}
# alphabeth=['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z','a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x... |
import pandas as pd
import csv
#MINIMUM_YEAR = 5
MINIMUM_YEAR = 6
#MINIMUM_YEAR = 7
def load_wine_dataset_sheet(wine_data_set_file):
"""
Returns the wine dataset workbook file.
Parameter:
wine_data_set_file: The excel file containing the wine dataset.
Returns:
workbook_fi... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Sep 18 13:28:49 2018
@author: paul
"""
import copy
class Solution:
def __init__(self, places, graph):
"""
places: a list containing the indices of attractions to visit
p1 = places[0]
pm = places[-1]
"""
... |
import re
rex = '[0-9]+'
pattern = re.compile(rex)
s = 'John was born in 1970, he joined SEAL force at the age of 30. John was killed in action in 2016.'
print(pattern.findall(s)) |
"""
作者:徐飞
时间:2019
版本:04
功能:汇率转换
"""
def main():
"""
主函数
"""
ratio = eval(input('请输入汇率值:'))
money = input("请输入带单位的货币金额:")
money_unite = money[-3:]
money_value = eval(money[:-3])
if money_unite == 'CNY':
exchange_rate = 1 / ratio
elif money_unite == 'USD':... |
"""
作者:徐飞
时间:2019
版本:02
功能:汇率转换
"""
money = input("请输入带单位的货币金额:")
money_unite = money[-3:]
money_value = eval(money[:-3])
ratio = eval(input("请输入汇率:"))
if money_unite == 'CNY':
usd = money_value / ratio
print("所得美元金额:", usd)
elif money_unite == 'USD':
rmb = money_value * ratio
print("所得... |
from tkinter import *
import ReadThread
import Paddle
import Ball
import math
import random
class PongGame():
def __init__(self):
#Start the reader thread
self.readerThread = ReadThread.MyThread(10)
self.readerThread.setName("Reader")
self.readerThread.start()
#Fram... |
"""
6. Faça um Programa que peça o raio de um círculo, calcule e mostre sua área.
"""
from math import pi
raio_circulo = float(input("Digite o raio do círculo: "))
area_circulo = pi * (raio_circulo ** 2)
print(f"A área do círculo é: {area_circulo:.2f} m2") |
"""
Faça um Programa que pergunte quanto você ganha por hora e o número de horas trabalhadas no mês.
Calcule e mostre o total do seu salário no referido mês.
"""
valor_hora = float(input("Quanto você recebe por hora? R$ "))
numero_horas_mes = float(input("Quantas horas você trabalha por mês? "))
salario = valor_hora *... |
def exchange(money):
return money* 9.912
if __name__ == "__main__":
money = float(input('请输入要转化的人民币,退出输入0:'))
while money:
print('{0}元人民币={1}俄罗斯卢布'.format(money,exchange(money)))
money = float(input('请输入要转化的人民币,退出输入0:')) |
edad = int(input("cuantos años tienes?\n"))
eleccion = input("a que quieres cambiar tu edad?\ndias horas segundos\n")
if eleccion == "dias":
dias = edad * 365
print("tienes" , dias , "dias de edad")
elif eleccion == "horas":
horas = (edad * 365) * 24
print("tienes" , horas , "horas de edad")
elif eleccion == "segun... |
#Program that does left factoring on production rules
#Function to accept rules
def accept_rules():
rules = {}
non_terminals = []
y = 'y'
while (y == 'y'):
string = input("Enter production rule : ")
for i in range(len(string)):
if string[i] == '=':
anteceden... |
game_board = []
n = 3
end_game = False
player1 = True
def create_game_board():
for i in range(n):
tmp = []
for j in range(n):
tmp.append(" ")
game_board.append(tmp[:])
def print_game_board():
for i in range(0, 3):
print(" {0} | {1} | {2}".format(game_board[i]... |
name = raw_input("Enter Name:")
for i in range(1,11):
print i
print "Hello, "+ name |
# Given two arrays write a function to find out if two arrays have the
# same frequency of digits
# Examples
one = [[1,2,3,4], [1,2,3,4]]
# [1,2,3,4], [1,4,5,6] = two
# [1,2,3,4], [1,4,4,2] = three
# [1,2,3,4], [1,4,3,2] = four
# [1,2,3,4,5], [1,2,3,4] = five
# Create frequency dictionary for first array
# loop thro... |
#!/usr/bin/env python
#coding:utf8
################################################################
# function: this script provides functions for other programs
# history : 2019.07.25 V1.0
# author : gaoyuanyong
###############################################################
import numpy as np
import csv
import mat... |
password = "mulualem03"
trials = 0
while password != "password":
# if the values of the two operands are not equal
if trials == 5:
print("Terminate")
break;
else:
password = input("Enter password: ")
trials += 1
if password == "password":
print("Welcome In")
|
class Times:
def __init__(self, nome, estado):
self.nome = nome
self.estado = estado
class Pilha(object):
def __init__(self):
self.dados = []
def empilha(self, elemento):
self.dados.append(elemento)
def desempilha(self):
if not self.vazia():
retur... |
'''
Created on Feb 16, 2016
@author: sumkuma2
'''
"""
Python Identity Operators:
Identity operators compare the memory locations of two objects. There are two Identity operators explained below:
Operator | Description
------------------------------------------------------
1) Is | Evaluates to true if t... |
list1= ['phusics','mathemetics',2341,9876]
list2= [1,2,3,4,5,6,7]
print "\n Before modification",list1
print "Value at index position 2 before insertion: ",list1[2]
list1[2]='chemestry'
print "Value at index position 2 after insertion: ",list1[2]
print "\n After modification",list1
print "lenght of list2",le... |
#import exceptions #its a module under which All Exceptions class are defined
#print dir(exceptions)
#print help(exceptions)
# User defined Exceptions class
class ShortInput(Exception):
'''Short input exception class '''
def __init__(self,length,atleast):
'''Initializing ShortInput Calss'''
... |
import re
#use of (r) raw string and boudary character
s=''' Mobile 9844816548 email sumit@gmail.com 8861733377
skr@gmail.com,sumit_skr@gmail.com'''
print re.findall('\\b\d{10}\\b',s) #
print re.findall(r'\b\d{10}\b',s) # r is to escape all special symbol in the string
s=''' Mobile 9844816548 \n\t email su... |
'''
Created on Feb 16, 2016
@author: sumkuma2
'''
# Sample for loop using a List
## define a list
shuttles = ['columbia', 'endeavour', 'challenger', 'discovery', 'atlantis', 'enterprise', 'pathfinder' ]
## Read shuttles list and store the value of each element into var shuttle and display on screen
for... |
'''
Created on Feb 14, 2016
@author: sumkuma2
'''
'''
Accessing Command Line Arguments:
The Python sys module provides access to any command-line arguments via the sys.argv. This serves two
purpose:
sys.argv is the list of command-line arguments.
len(sys.argv) is the number of command-line arguments.
Here... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.