text stringlengths 37 1.41M |
|---|
# Definition for a binary tree node
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
import collections
class Solution:
"""
@see https://oj.leetcode.com/problems/symmetric-tree/
"""
# @param root, a tree node
... |
class Solution:
"""
@see https://oj.leetcode.com/problems/spiral-matrix/
"""
# @param matrix, a list of lists of integers
# @return a list of integers
def spiralOrder(self, matrix):
m = len(matrix)
n = 0 if m==0 else len(matrix[0])
l = 0
res = []
... |
class Solution:
"""
@see https://oj.leetcode.com/problems/implement-strstr/
"""
# @param haystack, a string
# @param needle, a string
# @return an integer
def strStr(self, haystack, needle):
n1 = len(haystack)
n2 = len(needle)
if n2 == 0:
retu... |
import math
class Solution:
"""
@see https://oj.leetcode.com/problems/permutation-sequence/
"""
# @return a string
def getPermutation(self, n, k):
fct = 1
nums = [str(i) for i in range(1, n+1)]
for i in range(1, n+1):
fct *= i
res = []
... |
"""
CSSE1001 Assignment 2
Semester 2, 2020
"""
from a2_support import *
# Fill these in with your details
__author__ = "{{Gunit Singh}} ({{s4642570}})"
__email__ = "gunit.singh@uqconnect.edu.au"
__date__ = "27/09/2020"
# Write your code here
class GameLogic:
""" Initialises the Game Logic class. """
def __in... |
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import sys
from sklearn.model_selection import train_test_split
from sklearn.pipeline import make_pipeline
from sklearn.naive_bayes import GaussianNB
from sklearn.neighbors import KNeighborsClassifier
from sklearn.tree import DecisionTreeClassifier
... |
import csv
import statistics
from collections import defaultdict as dd
def parse_data(filename):
#initialize list of valid years and months to use for checking
valid_years = ["2010", "2011", "2012", "2013", "2014"]
valid_months = ["JAN", "FEB", "MAR", "APR", "MAY", "JUN",
"JUL", "... |
""""
Implementation of simulated annealing.
temp_space is an array of temperatures, you can pass e.i. np.logspace(4,-1,100000)
path must be a class implementing methods: swap_random or swap_neighbour, reswap, and must have an energy array
"""
import numpy as np
import random
def choose_state(T, energy_prev, energy_a... |
def invert(dic):
for key,value in dic.items():
del dic[key]
dic[value]=key
print dic
invert({'r':4,'t':2,'u':5})
|
#Improve the above program to print the words in the descending order of the number of occurrences.
import sys
def wordcountsort(filename):
f=open(filename,'r')
dict1={}
text=(f.read()).split()
for i in text:
if i not in dict1:
dict1[i]=1
else:
dict1[i]=dict1[i]+1
print dict1
for i in sorted... |
def triple(x):
return [(a,b,c) for a in range(1,x) for b in range(a,x) for c in range(1,x) if a+b==c]
print triple(6)
|
def treemap(a,b,):
lis=[]
for i in b:
if isinstance(i,list):
lis.append(treemap(a,i))
else:
lis.append(a(i))
return lis
fl=treemap(lambda x: x*x, [1, 2, [3, 4, [5]]])
print fl
|
import math
class Solution:
def divide(self, dividend: int, divisor: int) -> int:
isNeg = False
if dividend < 0 or divisor < 0:
isNeg = True
if dividend < 0 and divisor < 0:
isNeg = False
c = 0
dividend = abs(dividend)
... |
# Autor: Gerson Loaiza Vásquez
# Carné: 2020207712
# Objetivo: Función que busca si un número tiene ceros
# E: Un número entero
# S: True si tiene ceros, False de lo contrario
# R: Solo números enteros
def tieneCeros (numero):
if isinstance (numero, int):
return tieneCeros_aux (numero)
elif n... |
# Autor: Gerson Loaiza Vásquez
# Carné: 2020207712
# Objetivo: Determinar si todos los dígitos de un número ingresado son pares
# E: Un número
# S: True si todos los dígitos son pares, de lo contrario, False
# R: Los números deben ser enteros positivos
def sonPares (numero):
if isinstance (numero, int) and... |
# import csv file
import csv
def readFile(fileName):
Voter_Id=[]
County=[]
Candidates=[]
#row_count
with open(fileName) as csv_file:
next(csv_file)
csv_reader = csv.reader(csv_file, delimiter=',')
for row in csv_reader:
Voter_Id.append(row[0... |
# -*- coding: utf-8 -*-
"""
Created on Wed Nov 13 09:45:07 2019
@author: pNser
定义函数countchar()按字母表顺序统计字符串中所有出现的字母的个数
(允许输入大写字符,并且计数时不区分大小写)。
"""
def countchar(string):
lst = ['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']
count_alpha = [0] *... |
n = 1
if n == 1:
print('yes')
n +=1
if n:
print('yes again')
|
while True:
try:
q = int(input('pls input the quantity: '))
p = int(input('pls input the price:'))
print('pay: %d' % (q * p))
break
except Exception as e:
print(e)
print('pls input valid number')
|
a=input("enter the number")
if (a% 2) == 0:
print("Even")
else:
print("odd")
|
N,M=raw_input().split(' ')
N1=int(N)
M1=int(M)
s=N1+M1
if s%2==0:
print "even"
else:
print "odd"
|
#5:28
class Node():
def __init__(self):
self._data = None
self._leftPtr = -1
self._rightPtr = -1
def setData(self, x):
self._data = x
def setRightPtr(self,x):
self._rightPtr = x
def setLeftPtr(self,x):
self._leftPtr = x
def getData(self):
ret... |
p1 = input("Player1? ")
p2 = input("Player2? ")
def assigning_no(choice):
if choice == "rock":
return 0
elif choice == "spock":
return 1
elif choice == "paper":
return 2
elif choice == "lizard":
return 3
elif choice == "scissors":
return 4
p1 = assigning_no(... |
n = int(input("Enter the first number: "))
m = int(input("Enter the second number "))
file = open("perfect_square.txt","a")
for x in range(n,n+m):
file.write(str(x)+"\n")
file.close()
|
global queue, size, head, tail
size = 5
queue = [None for i in range(5)]
head = 0
tail = 0
def isEmpty():
global head, tail, queue
if head == tail and queue[head] == None:
return True
return False
def isFull():
global head, tail, queue
if head == tail and queue[head] != None:
retur... |
#1:51 - 2:20
class Node():
def __init__(self, data):
self._data = data
self._next = None
self._prev = None
def getdata(self):
return self._data
def getnext(self):
return self._next
def getprev(self):
return self._prev
def setnext(self, x):
se... |
n = int(input("Enter a number: "))
file = open("primenumbers.txt","r")
prime = []
for i in file:
if i != "\n":
prime.append(int(i))
#if n is divisible by any prime untill its square root its not a composite
def prime_check(n,prime):
for i in prime:
if int(i) > int(pow(n,.5)):
break... |
price,coin= map(int,input().split(" "))
num=1
while True:
cost= price * num
cost=str(cost)
left=int(cost[-1])117 3
if left==coin or left==0:
break
num += 1
print (num)
|
numbers = list(input("Enter the numbers: ").split(" "))
print(numbers)
def sum_iter(n):
total = 0
for i in n:
total += int(i)
print(total)
def sum_recur(n):
if len(n) == 0:
return 0
return sum_recur(n[1:]) + int(n[0])
print("Iteratively: ")
sum_iter(numbers)
print("Recursively: ")... |
#9.54 - 10.11 = 17
class Node():
def __init__(self):
self.data = None
self.next = None
class LL():
def __init__(self):
self.head = None
def newnode(self,data):
newnode = Node()
newnode.data = data
return newnode
def insertfront(self, data):
newn... |
# This program upon execution will take your command to play music randomly.
import pyttsx3 #pip install pyttsx3
import speech_recognition as sr #pip install SpeechRecognition
import os
import datetime
import random
engine = pyttsx3.init('sapi5')
voices = engine.getProperty('voices')
engine.setProperty('voice... |
def apply_async(func, args, *, callback):
# callback need to record the used number of func.
result = func(*args)
callback(result)
class Counter:
def __init__(self):
self.count = 0
def __call__(self, x):
self.count += 1
print("The result is {}, \
The functio... |
def parse(*args):
new_word = ""
for i in args:
for j in range(len(i)):
if(i[j]=="?" or i[j]=='.' ):
break
else:
new_word += i[j]
new_sentence= new_word.lower()
return new_sentence
def name_parse(name):
initials = []
for i in name.split(" "):
initials.append(i[0])
new_name = ''.join(initials)... |
#!/usr/bin/env python3
# -*- coding:utf8 -*-
from functools import wraps
from inspect import signature
from time import sleep
def _make_key(func, *args, **kwargs):
sig = signature(func)
bd = sig.bind(*args, **kwargs)
return bd.args
def memorize(func):
def _inner(func):
cache = {}
make_key = _make_ke... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Module: day10.py
Author: zlamberty
Created: 2015-12-09
Description:
Usage:
<usage>
"""
import os
import re
# ----------------------------- #
# Module Constants #
# ----------------------------- #
ALPH = 'abcdefghijklmnopqrstuvwxyz'
INPUT = 'hep... |
# coding: utf-8
# In[17]:
print('hello world!')
# In[18]:
from time import gmtime as the_time
# In[19]:
print(the_time())
# In[20]:
#Dot notation for objects
this_second = the_time().tm_sec
print(this_second)
# In[21]:
# if statement
if this_second%3 == 0:
print('Divisible by 3!')
elif this_secon... |
#!/usr/bin/python3
# -*- coding: utf-8 -*-
"""
:mod:`minesweeper` module
:author: Nollet Antoine
:date: 04/10/2019
This module provides functions and a class for minesweeper's game's management.
"""
import random
from enum import Enum
from cell import Cell
################################################
# Typ... |
# -*- coding: utf-8 -*-
"""
Created on Thu Jun 13 15:29:20 2019
@author: pvelarde
"""
a, b = 20, 0
def division(x, y):
return x/y
def imprime_resultado(x, y):
resultado = division(x, y)
print("La division de {} entre {} es {}".format(resultado))
imprime_resultado(a, b) |
#Maria Jose Castro 181202
#Roberto Figueroa 18306
#Diana de Leon 18607
#Ejercicio 1
#paquetes necesarios
import math
import itertools
def genElements(n):
return list(range(n))
mensaje = "1.Orden-Sin reemplazo\n2.Orden-Con remplazo\n3.Sin orden-sin remplazo\n4.Sin orden-con remplazo\n5.Salir"
o... |
# Nagy János, 2020-12-17, esti szoft1
print("Nagy János, 2020-12-17, esti szoft1")
print("Két dolgozat pontszámait kéri be")
dolgozat1 = []
dolgozat2 = []
def beker():
dolgozat = []
pontszam = -2
while pontszam != -1:
pontszam = int(input('Pontszám: '))
if pontszam != -1:
dol... |
"""Homework file for my students to have fun with some algorithms! """
def find_greatest_number(incoming_list):
return max(incoming_list)
pass
def find_least_number(incoming_list):
return min(incoming_list)
pass
def add_list_numbers(incoming_list):
return sum(incoming_list)
pass
def lon... |
class Tile (object):
""" This is the abstract representation of Tiles, the building blocks of the world."""
def __init__ (self, stage, x, y):
self.stage = stage
self.x = x
self.y = y
"initializes the tile with a random type from the types list"
self.tile_type = self.st... |
'''Between the following two commented lines is code to help you access
the API. There is only ONE part that you need to change, avoid changing
if possible.
-------------------------------------------'''
import io
import os
import random
# Imports the Google Cloud client library
from google.cloud import vision
from go... |
class AssignWorkers:
def __init__(self, testcase, num_workers):
"""AssignWorkers helps to split the dataframe to a designated number of wokers"""
self.testcase = testcase
self.num_workers = self._validate_workers(num_workers)
def _validate_workers(self, num_workers):
"""return t... |
"""
Este modulo contiene el codigo para la construccion de la GUI
"""
from tkinter import *
from tkinter import ttk
from tkinter import messagebox
import numpy as np
import sympy as sy
class GUI():
def __init__(self):
pass
def Interfaz(self):
#Crear la interfaz grafica de usuario
self.Win... |
"""A fairly basic set of tools for data processing.
As of now, there is only one fuction in the module -
`remove_outliers`.
`remove_outliers` is meant to remove outliers from your
inputted data, where outliers are defined to be so many
standard deviations way from the mean.
"""
import numpy as np
def remove_out... |
class Solution:
def calculate(self, s: str) -> int:
ans = 0
operators = []
flag = [1]
operator = ""
for char in s:
if char == " ":
continue
elif char == "+" and operator != "":
flag.append(1)
operators.ap... |
# Reference: https://leetcode.com/problems/find-and-replace-in-string/
# To some string S, we will perform some replacement operations that replace groups of letters with new ones (not necessarily the same size).
# Each replacement operation has 3 parameters: a starting index i, a source word x and a target word y. Th... |
from EnemyCircular import *
class EnemyLinear(pygame.sprite.Sprite):
"""
Enemy that travels in a linear path
Attributes
----------
game : Game
The game this enemy is in
groups : sprite group
All sprite groups this sprite belongs in
size : int
The diameter of the cir... |
def findMinAndMax(L):
if L==[]:
return (None, None)
else:
max1=L[0]
min1=L[0]
for i in L:
if i>=max1:
max1=i
elif i<=min1:
min1=i
return (min1,max1)
# 测试
if findMinAndMax([]) != (None, None):
print('测试失... |
#1. Принимаю от пользователя дату
#2. Составляю расписание раз в 2 дня (через день)
#3. На 30 дней ДД ММ ГГ и день недели
#4. Если это воскресенье, то перенести на понеделтник и опять через день
import datetime
#прошу у пользователся дату
date_entry = input("Введите дату в формате ДД, ММ, ГГГГ ")
#перевожу в формат д... |
# R-1.1
# Write a short Python function, is multiple(n, m), that takes two integer values and returns True if n is a multiple of m, that is, n = mi
# for some integer i, and False otherwise.
# is_multiple function
def is_multiple(n,m):
if(n % m == 0):
return True
else:
return False
# R-1.2
#... |
def binary_search(data, target, low, high):
"""Return True if target is found in indicated portion of a Python list.
The search only considers the portion from data[low] to data[high] inclusive.
"""
if low > high:
return False
else:
mid = (low + high) // 2
if target == data[... |
import datetime
import pytz
"""
This class is a node in a double linked list.
It is defined by a key, data and an expiry date in the form of a datetime object
"""
class Node:
def __init__(self, key=None, data=None, expiryDate=None, next=None, prev=None):
self.key = key
self.data = data
se... |
# 홍길동 씨의 과목별 점수는 다음과 같다. 홍길동 씨의 평균 점수를 구해 보자.
# 과목 점수
# 국어 80
# 영어 75
# 수학 55
## 방법0: 그냥 계산
print((80+75+55)/3)
## 방법1: 변수 이용
a = 80
b = 75
c = 55
e = (a+b+c)/3
print(e)
## 함수 이용
a, b, c = 80, 75, 55
def average(a, b, c):
"""
a: 국어 점수
b: 영어 점수
c: 수학 점수
"""
return (a+b+c)/3
print(average(... |
# INF 120-004
# Project 5
# Casey York
# November 15, 2016
from time import sleep
def flipbook():
# setting folder path for pictures, making empty list to contain files
path = setMediaPath()
frameList = []
# requesting info for building file path
fileNum1 = requestIntegerInRange("Frame numbering begin... |
# alerts when over 100 F
temp = float(input("Enter the reading in Celsius: "));
temp = temp*1.8 + 32;
if temp>100:
print("Red Alert!");
|
from turtle import *;
# draw a circle given the radius
# x, y: CENTER of the circle
# radius: in pixels
def drawCircle(x, y, radius):
speed(1000);
penup();
goto(x, y-radius);
setheading(0);
pendown();
circle(radius);
return 1;
# draw a rectangle.
# x, y: the coordinates of the CENTER of the rectangle
# penColo... |
cube = lambda x: x ** 3
def fibonacci(n):
fibo = [0, 1]
for i in range(2, n):
add = fibo[i - 1] + fibo[i - 2]
fibo.append(add)
return fibo
if __name__ == '__main__':
n = int(input())
print(list(map(cube, fibonacci(n))))
|
# finding the greatest file or folder inside a specified folder
import os
greatest = -1
for folders, subfolders, files in os.walk('c:\\python27\\project euler'):
if folders == 'c:\python27\project euler':
continue
total = 0
for file in files:
temp = os.path.join(folders, file)
total += os.stat(temp).st_si... |
n = int(input())
result = []
for i in range(n):
word = input()
if len(word) <= 10:
result.append(word)
else:
result.append(word[0] + '{}'.format(len(word[1:len(word)-1])) + word[len(word)-1])
for i in result:
print(i) |
import math
class Point:
def __init__(self, x, y):
self._xCoord = x
self._yCoord = y
def getX(self):
return self._xCoord
def getY(self):
return self._yCoord
def shift(self, xInc, yInc):
self._xCoord += xInc
self._yCoord += yInc
def distance(self, otherPoint):
xDiff = self._xCoord - otherPoin... |
from datetime import datetime
class TimeDate:
def __init__(self, month = 0, day = 0, year = 0, hours = 0, minutes = 0, seconds = 0):
if month == 0:
month = datetime.now().date().month
if year == 0:
year = datetime.now().date().year
if day == 0:
day = datetime.now().date().day
if hours == 0:
hour... |
# Ambicable numbers
# Find the divisor of every numbers upto 10000 and sum it up
# Find the divisor of sum, then see if it is equal to the number
# If equal, add it to the result
result = 0
dict = {}
for i in range(1, 10000):
if i in dict:
result += i
continue
sum = 0
for j in range(1, i):
if i % j == 0:
... |
import sys
def cheese_and_crackers(cheese_count, boxes_of_crackers):
print "You have %d cheese!" % cheese_count
print "You have %d boxes of crackers!" % boxes_of_crackers
print "Man that's enough for a party!"
print "Get a blanket.\n"
print "We can just give the function numbers directly:"
cheese_and_crackers(2... |
import random
card_list = ['Ace', 'Two', 'Three', 'Four']
daily = random.sample(card_list, 3)
print()
print("First card is your past, second is now, third is your future:")
print()
print(daily)
print()
|
# collatz number in Python
my_no = input('Enter a positive integer: ')
my_number = int(my_no)
while (my_number != 1):
if my_number % 2 == 0:
my_number = my_number / 2
my_val = int(my_number)
print(my_val)
else:
my_number = (3 * my_number) + 1
my_val = int(my_number)
print(my_v... |
import random
def encode(correct, guess):
output_arr = [''] * len(correct)
for i, (correct_char, guess_char) in enumerate(zip(correct, guess)):
output_arr[i] = 'X' if guess_char == correct_char else 'O' if guess_char in correct else '-'
return ''.join(output_arr)
def safe_int_input(prompt, mi... |
class Cup:
def __init__(self, type, value, number, nextCup, captureCup):
self.type = type
self.value = value
self.nextCup = nextCup
self.captureCup = captureCup
self.number = number
def Sow(self):
self.value = self.value + 1
def Harvest(self):
self.v... |
# Importação de bibliotecas
from time import sleep
# Título do programa
print('\033[1;34;40mFUNÇÃO QUE DESCOBRE O MAIOR\033[m')
# Objetos
# Funções
def maior(*num):
m = qtd = 0
print('Analisando os valores passados...')
for n in num:
print(n, '', end='')
qtd += 1
if n > m:
... |
num = str(input('Digite um número inteiro com até 4 digitos: '))
num = num.rjust(4, ' ')
print('\033[1;34;41mUnidade:\033[m {}'.format(num[3]))
print('\033[1;34;42mDezena:\033[m {}'.format(num[2]))
print('\033[1;34;43mCentena:\033[m {}'.format(num[1]))
print('\033[1;33;44mMilhar:\033[m {}'.format(num[0]))
# Fazendo pe... |
# Importação de bibliotecas
# Título do programa
print('\033[1;34;40mVALORES ÚNICOS EM UMA LISTA\033[m')
# Objetos
valores = list()
# Lógica
while True:
n = int(input('\033[30mDigite um valor:\033[m '))
if n not in valores:
valores.append(n)
print('\033[1;34mValor adicionado com sucesso...\... |
# Funções padrões
def título(txt):
print(f'\033[1;34;40m{txt.upper()}\033[m')
def linha(tipo, cor, tamanho):
print(f'\033[{cor}m{tipo}\033[m' * tamanho)
# Importação de bibliotecas
from datetime import date
# Título do programa
título('funções para votação')
# Objetos
# Funções
def voto(nasc):
idade ... |
# Importação de bibliotecas
dados = list()
# Título do programa
print('\033[1;34;40mAPRIMORANDO OS DICIONÁRIOS\033[m')
# Objetos
while True:
jogador = {'Nome':str(input('Nome do Jogador: ')).strip().capitalize(), 'gols':[], 'total':0}
# Lógica
partidas = int(input(f'Quantas partidas {jogador["Nome"]} jog... |
# Importação de bibliotecas
# Título do programa
print('\033[1;34;40mESTATÍTSTICAS EM PRODUTOS\033[m')
# Objetos
gasto = 0
caros = 0
barato = 0
produtomaisbarato = ''
# Lógica
print('\033[34m-\033[m' * 50)
print(f'\033[1;33m{"LOJA SUPER BARATÃO":^50}\033[m')
print('\033[34m-\033[m' * 50)
while True:
produto = ... |
# Importação de bibliotecas
# Título do programa
print('\033[1;34;40mVERIFICAÇÃO DE NÚMERO PRIMO\033[m')
# Objetos
n = int(input('\033[30mDigite um número:\033[m '))
s = 0
# Lógica
for c in range(1, n + 1):
if n % c == 0:
print('\033[34m', end=' ')
s = s + 1
else:
print('\033[30m', e... |
nome = str(input('\033[33;44mDigite o nome de uma cidade:\033[m ')).strip().capitalize().split()
print('O nome da cidade começa com a palavras "Santo"?: {}'.format(nome[0] == 'Santo'))
# Forma como o Gustavo Guanabara resolveu, mas tem uma falha, se digitar "santos" ele considera True, pois
# o programa só está lendo ... |
print('\033[36;40mVamos calcular a quantidade necessária de tinta para pintar uma parede\033[m')
l = float(input('Digite a largura da parede em metros '))
a = float(input('Digite a altura da parede em metros '))
area = l*a
print('A área total da parede é {}m2, a quantidade total de tinta para pintar é {}l'.format(area,... |
# Importação de bibliotecas
# Título do programa
print('\033[1;34;40mCÁLCULO DO IMC DE UMA PESSOA\033[m')
# Objetos
peso = float(input('\033[30mDigite o peso em kg:\033[m '))
altura = float(input('\033[30mDigite a altura em m:\033[m '))
imc = peso / altura**2
abaixo = 18.5
ideal = 25
sobrepeso = 30
obesidade = 40
#... |
# Importação de bibliotecas
# Título do programa
print('\033[1;34;40mTABUADA V3.0\033[m')
# Objetos
num = 0
# Lógica
while True:
print('-' * 30)
num = int(input('\033[30mQuer ver a tabuada de qual valor?:\033[m '))
print('-' * 30)
if num < 0:
break
for c in range(0, 11):
print(f'... |
from math import trunc
print('Vamos verificar a condição de existência de um triângulo')
r1 = float(input('Digite o valor da primeira reta: '))
r2 = float(input('Digite o valor da segunfa reta: '))
r3 = float(input('Digite o valor da terceira reta: '))
if r1 + r2 > r3 and r1 + r3 > r2 and r2 + r3 > r1:
print('reta ... |
import time
class Clock(object):
def __init__(self, rate):
self.last_loop = time.time() * 1000
self.rate = 0
self.time_loop = 0
self.time_process = 0 # time spend to process all calcules
self.set_rate(rate)
def set_rate(self, rate):
"""
set the rate
... |
class Solution:
# @param version1, a string
# @param version2, a string
# @return an integer
def compareVersion(self, version1, version2):
num1 = version1.split('.')
num2 = version2.split('.')
while (len(num1) or len(num2)):
if (len(num1) == 0) : num1 = [0]
... |
#!/usr/bin/python
#
# Simple XML parser for JokesXML
# Jesus M. Gonzalez-Barahona
# jgb @ gsyc.es
# TSAI and SAT subjects (Universidad Rey Juan Carlos)
# September 2009
#
# Just prints the jokes in a JokesXML file
from xml.sax.handler import ContentHandler #Los elementos tienen el comportamiento que yo quiero
from x... |
from turtle import Turtle, mainloop, mode
import math
class Forme:
def __init__(self, x=0, y=0, width=480, height=320, fg="black", bg=""):
self.x = x
self.y = y
self.width = width
self.height = height
self.fg = fg
self.bg = bg
def dessiner(self):
... |
from random import randint
class Eleve:
def __init__(self, nom_prenom):
self.nom_prenom = nom_prenom
def __str__(self):
return f"{self.nom_prenom:32}"
def __repr__(self):
return f"Eleve(nom_prenom: {self.nom_prenom:45})"
class Devoir:
def __init__(self, devoi... |
# Default Imports
import numpy as np
def create_3d_array():
a = np.zeros(shape=(3,3,3))
#print a
array = np.size(a)
print array
array_number = np.arange(0,27)
print array_number
variable = np.reshape(array_number,newshape = (3,3,3))
return variable
print create_3d_array()
|
#
import sys
if __name__ == "__main__":
# 以下命令读取所有行
print('>>>>>>sys.stdin.read()函数开始读取<<<<<<')
print('>>>>>>请输入N行,输入完毕后用 ctrl + d 终止输入<<<<<<')
read_all_line = sys.stdin.read() # 输入完后用 ctrl + d 终止
print('>>>>>>输入结束<<<<<<')
print(read_all_line)
print('>>>>>>sys.stdin.read()函数读取结束<<<<<<... |
class AlgoritmoRep(object):
def calcularAreaCuadro(self):
lado = float(input("Ingrese el Lado del Cuadrado:"))
resulArea = lado * lado
print("El area del cuadrado es:", resulArea)
def calacularAreaTriangulo(self):
base = float(input("Ingrese la Base del triangulo:"))
alt... |
import random
import random
# Consider using the modules imported above.
class Hat:
def __init__(self,**balls):
self.contents = []
self.balls = balls
for k,v in balls.items():
for i in range(v):
self.contents.append(k)
def draw(self,balls_to_draw):
#... |
from ..geom.geometry import point as p
from math import sqrt, pi, sin, cos, fabs
class InvalidCircle(Exception):
def __init__(self, sites):
self.sites = sites
def __str__(self):
return repr([str(site) for site in self.sites])
class Bubble:
'''
rising bubble to merge delaunay candidat... |
import tkinter as tk #Import tkinter GUI Toolkit
#---This is a function. It's created by using the line (def name_of_function():) this is so we can call it and the code is on standby, and listening to when it's called
def log_win():
#--Global is use to allow diffrent bindings to travle out from the function ... |
import os
import path
import csv
csvpath = os.path.join('Resources', 'budget_data.csv')
total_months = 0
total_revenue =0
changes =[]
date_count = []
greatest_inc = 0
greatest_inc_month = 0
greatest_dec = 0
greatest_dec_month = 0
with open(csvpath, newline = '') as csvfile:
csvreader = csv.reader(csvfile, delimi... |
## Chapter 3 Notes
# change.py
##A program to calculate the value of some change in dollars
##def change_counter():
## print("Change Counter")
## print()
## print("Please enter the count of each coin type.")
##
## quarters = eval(input("Quarters: "))
## dimes = eval(input("Dimes: "))
## nickels = e... |
# utf-8
"""
__new__(cls) - настоящий конструктор
__init__(self) - конструктор (инициализация)
__del__(self) - деструктор
__int__
__float__
__bool__
__str__ (__unicode__) - (python 2)
"""
from pprint import pprint
class Product(object):
"""Атата, документация"""
def __init__(self, title, price):
sel... |
# using NLTK library, we can do lot of text pre-processing
import nltk
from nltk.tokenize import word_tokenize
from nltk.corpus import stopwords
from nltk.stem.porter import PorterStemmer
# function to split text into word
tokens = word_tokenize("The quick brown fox jumps over the lazy dog")
stop_words = set(stopwords... |
#!/usr/bin/python
# -*- coding:utf-8 -*-
'''
概念:不使用def这样的语句函数,使用lambda来创建匿名函数
特点:
1 lambda 是一个表达式,函数体比def简单
2 lambda 的主体是一个表达式。而不是代码块,仅仅只能在lambda表达式中封装简单的逻辑
3 lambd 函数有自己的命名空间,且不能访问自由参数列表之外的或则全局命名空间的参数
格式:lambda 参数1,参数2,...参数n:expression(表达式)
'''
sum =lambda num1,num2:num1+num2
print(sum(1,2)) |
#!/usr/bin/python
# -*- coding:utf-8 -*-
#90 = 2x3x3x5
'''
num = int(input())
i =2
while num != 1:
if num % i == 0:
print(i)
num //= i
else:
i +=1
'''
str = input("输入字符串:")
str1 = str.strip()
index = 0
count = 0
# tom is a good man
while index < len(str1):
while str1[index] != " ":... |
#!/usr/bin/python
# -*- coding:utf-8 -*-
'''
概念:是一个闭包,把一个函数当做参数返回一个代替版的函数,本质上就是一个返回函数的函数
'''
#简单的装饰器
def func1():
print("tom is a good man")
def outer(func):
def inner():
print("********")
func()
return inner
#f是函数func1的加强版本
f = outer(func1)
f()
|
#!/usr/bin/python
# -*- coding:utf-8 -*-
'''
num = int(input())
if num == 2:
print("是质数")
index= 2
while index <= num -1:
if num % index == 0:
print('不是质数')
index += 1
if index == num:
print("是质数")
'''
'''
str = input()
index = 0
sum = 0
while index < len(str):
if str[index] >= "0" and ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.