text stringlengths 37 1.41M |
|---|
import math
def running_median(stream):
# Fill this in.
# Define accumulator
acc = []
# Iterate over the stream
for n in stream:
# Push and sort accumulator
acc.append(n)
acc.sort()
# Find median element index
size = len(acc)
if size % 2 == 1:
# Odd size is just the number i... |
class calculate:
def __init__(self,num):
self.result = num
def plus(self, num):
self.result += num
return self.result
def minus(self, num):
self.result -= num
return self.result
def multi(self, num):
self.result = self.result * num
return self.r... |
# The program demonstrates an environment to perform an analysis of the frequencies of a two-channel wave audio source. For this step,
# DTFT (Discrete Time Fourier Transform) of the wave audio source (a wave file) is performed.
# Assuming that the necessary analysis is performed, next step is to "sew back" the origi... |
# -*- coding: utf-8 -*-
"""
Created on Thu Feb 25 18:51:48 2021
@author: R005
"""
#Leer una tabla de multiplicar e imprimir dicha tabla desde el 1 hasta el 20
#y sumar sus resultados. Usar para la solución ciclo While
#Declarar variables
tabla=0
resultado=0
sumaresultados=0
conrepciclo=1
multiplicad... |
# -*- coding: utf-8 -*-
"""
Created on Mon Mar 22 20:30:45 2021
@author: R005
Se realiza la carga de 10 valores enteros por teclado. Se desea conocer:
a) La cantidad de valores ingresados negativos.
b) La cantidad de valores ingresados positivos.
c) La cantidad de múltiplos de 15.
d) El valor acumulado de l... |
# -*- coding: utf-8 -*-
"""
Created on Mon Mar 22 14:02:21 2021
@author: Sebastian Marulanda Correa
Ejercicio 13 curso. funciones Python
Definir por asignación una lista de enteros en el bloque principal del
programa. Elaborar tres funciones, la primera recibe la lista y retorna la
suma de todos sus elemen... |
# -*- coding: utf-8 -*-
"""
Created on Mon Mar 22 14:42:45 2021
@author: Sebastian Marulanda Correa
Ejercicio 17 curso. funciones Python
Definir una lista de enteros por asignación en el bloque principal. Llamar a
una función que reciba la lista y nos retorne el producto de todos sus
elementos. Mostrar dic... |
# -*- coding: utf-8 -*-
"""
Created on Thu Feb 18 19:44:26 2021
@author: SEBASTIAN MARULANDA CORREA
"""
#solicita al usuario ingresar por teclado 3 números diferentes
print("ingrese 3 numeros enteros diferenetes")
#Variable denominada e tipo entero, para solicitar al usuario que ingrese 1 o 2 según el orden
#... |
# -*- coding: utf-8 -*-
"""
Created on Mon Mar 22 20:21:25 2021
@author: R005
Desarrollar un programa que muestre la tabla de multiplicar del 5 (del 5 al 50)
"""
for f in range(5,51,5):
print(f)
|
# -*- coding: utf-8 -*-
"""
Created on Thu Feb 18 15:50:51 2021
@author: R005
"""
#Escribir un programa que solicite ingresar 10 notas
#de alumnos y nos informe cuántos tienen notas mayores o iguales a 7 y cuántos menores.
altas=0
bajas=0
x=1
while x<=10:
nota=int(input("ingrese las notas:"))
... |
# -*- coding: utf-8 -*-
"""
Created on Tue Mar 9 18:36:56 2021
@author: SEBASTIAN MARULANDA CORREA
Leer N, generar aleatrorios y calcular suma y promedio de:
números aleatorios, números positivos, números negativos
Mostrar los números aleatorios
Mostrar cantidad total de números
Mostrar cantidad ... |
# -*- coding: utf-8 -*-
"""
Created on Tue May 4 18:23:46 2021
@author: R005
"""
import pandas as pd
notafundamentos=pd.DataFrame ({'Nombres':['andres','sebastian','laura','camila'],'semestre':[2,3,3,2]}) #notafundamentos es el dataframe
print(notafundamentos)
print()
notafundamentos.insert(2,'ciudad'... |
# -*- coding: utf-8 -*-
"""
Created on Thu Apr 22 18:41:51 2021
@author: R005
"""
#Métodos de ordenamiento
#Crear lista y darle valores
listabase=[34,12,45,2,60,34,8]
print("Lista base desordenada: ",listabase)
#Ordenar la lista con una función de python de manera ascendente
listabase.sort() #Sin na... |
# -*- coding: utf-8 -*-
"""
Created on Mon Mar 22 10:07:44 2021
@author: Sebastian Marulanda Correa
Ejercicio 1 curso. funciones Python
Confeccionar una aplicación que muestre una presentación en pantalla del programa.
Solicite la carga de dos valores y nos muestre la suma. Mostrar finalmente un mensaje de ... |
# -*- coding: utf-8 -*-
"""
Created on Mon Mar 22 13:09:05 2021
@author: Sebastian Marulanda Correa
Ejercicio 8 curso. funciones Python
Confeccionar una función que le enviemos como parámetro un string y
nos retorne la cantidad de caracteres que tiene. En el bloque
principal solicitar la carga de dos nombr... |
# -*- coding: utf-8 -*-
"""
Created on Mon Mar 1 17:57:08 2021
@author: SEBASTIAN MARULANDA CORREA
"""
#Sumar los números enteros de 1 a 100
suma=0
for i in range (1,101):
suma=suma+(i)
print(i)
print("la suma es:",suma) |
# Написать fizzbuzz для 20 троек чисел, которые записаны в файл. Читаете из файла первую строку,
# берете из нее числа, считаете для них fizzbuzz, выводите.
f = open("fizz.txt", "r")
for i in f:
line = list(map(int, i.split()))
line1 = int(line[0])
line2 = int(line[1])
line3 = int(line[2])
s = ... |
radius = int(input("Введите радиус: "))
if radius >= 0:
print("Длина окружности = ", 2 * 3.14 * radius)
print("Площадь = ", 3.14 * radius ** 2)
else:
print("Пожалуйста, введите положительное число") |
n1=int(input('Me diga sua primeira nota:'))
n2=int(input('Me diga sua segunda nota:'))
n3=int(input('Me diga sua terceira nota:'))
m = (n1+n2+n3)/3
print('Sua média é {:.2f}'.format(m))
|
numero = int(input('Me diga um número:'))
unidade = (numero // 1 % 10) % 2 #Se o resto da divisão da unidade for igual a 0, então ele é par
if unidade == 0:
print('Seu número é par.')
else:
print('Seu número é impar.') |
cidade = str(input('Digite o nome de uma cidade:')).strip()
## o nome da cidade começa com Santo?
cidade = cidade.capitalize()
print('Santo' in cidade) |
salario = float(input('Qual o valor do seu salário? R$'))
if salario > 1250:
print('Você recebeu um aumento, e seu novo salário é R${:.2f}.'.format((salario * 10 / 100) + salario))
else:
print('Você recebeu um aumento, e seu novo salário é R${:.2f}'.format((salario * 15/100) + salario)) |
a = int(input('Escreva o primeiro número:'))
b = int(input('Escreva o segundo valor:'))
c = int(input('Escreva o terceiro valor:'))
# O menor
menor = a
if b<a and b<c:
menor = b
if c<a and c<b:
menor = c
# O maior
maior = a
if b>a and b>c:
maior = b
if c>a and c>b:
maior = c
print('O menor valor foi {}.... |
num = 0
while (num < 10):
num += 1
print(str(num))
|
import random
my_random_number = random.randint(1, 10)
print("I am thinking of a number between 1 and 10.")
number = input("What's the number? ")
guess = 5
while int(number) != my_random_number and guess > 0:
print ("Nope, try again.")
print ("You have " + str(guess) + " guesses left.")
guess = guess - 1
... |
class Vehicle:
def __init__(self, make, model, year):
self.make = make
self.model = model
self.year = year
def print_info(self):
print(self.make + " " + self.model + " " + self.year)
class Person:
def __init__(self, name, email, phone):
self.name = name
sel... |
import random
class Character:
def __init__(self, health, power, name, mult, value, dead, weapon):
self.health = health
self.power = power
self.name = name
self.mult = mult
self.value = value
self.dead = True
self.weapon = weapon
def super_tonic(self):
self... |
import random
import sys
import math
import pickle
DEBUG = True
class TicTacToePlayer:
TYPES = ["HUMAN", "COMPUTER"]
def __init__(self, player, player_type):
self.player = player
self.player_type = player_type
def reset(self):
pass
def feed_reward(self, reward):
pass... |
PUZZLE1 = '''
glkutqyu
onnkjoaq
uaacdcne
gidiaayu
urznnpaf
ebnnairb
xkybnick
ujvaynak
'''
PUZZLE2 = '''
fgbkizpyjohwsunxqafy
hvanyacknssdlmziwjom
xcvfhsrriasdvexlgrng
lcimqnyichwkmizfujqm
ctsersavkaynxvumoaoe
ciuridromuzojjefsnzw
bmjtuuwgxsdfrrdaiaan
fwrtqtuzoxykwekbtdyb
wmyzglfolqmvafehktdz
shyot... |
from copy import deepcopy
from math import sqrt
class Configuration:
"""
Configuration of the puzzle
"""
def __init__(self, matrix):
self.__matrix = deepcopy(matrix)
def getLength(self):
return len(self.__matrix[1])
def getValues(self):
return deepcopy(self.__matrix... |
def add(x, y):
return x + y
def sub(x, y):
return x - y
def prod(x, y):
return x * y
def do(func, x, y):
return func(x, y)
print(do(add, 12, 4)) # 'add' as arg
print(do(sub, 12, 4)) # 'sub' as arg
print(do(prod, 12, 4)) # 'prod' as arg
|
# Type your code here
def de_ascii(n):
return(ord(n))
n=input("enter a char")
print(de_ascii(n))
|
# Type your code here
def asterick(n):
for i in range(n):
print('*'*n)
n=int(input("Enter an integer: "))
asterick(n)
|
class Point:
def __init__(self,x,y,z):
self.x=x
self.y=y
self.z=z
def __str__(self):
my_str="point: ({0},{1},{2})".format(self.x,self.y,self.z)
return my_str
p1=Point(4,2,1)
print(p1)
|
# coding:utf8
'''
Created on 2018年1月30日
@author: XuXianda
'''
#划分数据集:按照最优特征划分数据集
#@dataSet:待划分的数据集
#@axis:划分数据集的特征
#@value:特征的取值
def splitDataSet(dataSet,axis,value):
#需要说明的是,python语言传递参数列表时,传递的是列表的引用
#如果在函数内部对列表对象进行修改,将会导致列表发生变化,为了
#不修改原始数据集,创建一个新的列表对象进行操作
retDataSet=[]
#提取数据集的每一行的特征向量
for fea... |
days = int(raw_input("Enter days: "))
months = days / 30
days = days % 30
print "months = %d Days = %d" % (months, days)
import math
a = int(raw_input("Enter value of a: "))
b = int(raw_input("Enter value of b: "))
c = int(raw input("Enter value of c: "))
d = b * b - 4 * a * c
if d < 0:
print "ROOTS are imaginary"
el... |
"""Homework 2 - needs to be presented before exam day"""
# 20P
# 1) Prove that "and" operation takes precedence over "or" operation by setting
# parentheses in the following expression (False or False and True or True)
# 40P
# 2) Get from input two different times in the format dd:hh:mm:ss and print the difference be... |
from modul3.app1 import primes
import random
def select_primes(num,limita) :
i = 0
fin_list = []
my_list = primes(limita)
y = len(my_list)
for _ in range(num):
x = random.randint(0,y - 1)
fin_list.append(my_list.pop(x))
y -= 1
print(fin_list)
my_primes = primes(100)
pr... |
# to import another python file just same folder and type the python file name
import app
import csv
import sqlite3
#connect to database
connection = sqlite3.connect("new.db")
cursor = connection.cursor()
# read file appointment
with open('appointments.csv', 'r') as file:
for row in file:
cursor.execute("... |
"""
driver.py
Includes main functions to run the boggle word finder using DFS on an input board (storing a dictionary of valid words as a Trie).
@author: Sanjana Marce
"""
import vocab
import trie
import argparse
"""
get_neighbors: returns a list of tuples corresponding to the (r, c) coordinates
of those cells wi... |
####heapsort######
class Heap:
def __init__(self, arr):
self.arr = arr
def heapify(self, arr, n, i):
largest = i
left = 2*i + 1
right = 2*i + 2
if left <n and arr[largest] < arr[left]:
largest = left
if right < n and arr[largest] < arr[right]:
... |
#!/usr/bin/python3
"""File storage class"""
import json
import os
import datetime
class FileStorage:
"""
Serializes instances to a JSON file and
deserializes Json file to instances
"""
__file_path = "file.json"
__objects = {}
def all(self):
"""Returns the dictionary __objects"""
... |
#!/usr/bin/env python
# ECE 2524 Homework 3 Problem 1
# Thomas Elliott
import argparse
import sys
parser = argparse.ArgumentParser(description='Multiply some integers.')
args = parser.parse_args()
product = 1
for data in iter(sys.stdin.readline, ''):
try:
if data == '\n':
print product
... |
import pandas as pd
import numpy as np
if __name__ == "__main__":
'''
Traditional way of running a linear regression: OLS method (ordinary least squares) 最小二乘法
Model deployment --- Score new data
So, should we plug the original data of new file into the selected model directly?
No, we should standa... |
"""
TicTacToeParser
Copyright(C) Simon Raichl 2018
MIT License
"""
from core import Core
again = None
while again is None or again == "y":
print(Core().get_board())
again = input("Again? Y/N\n").lower()
|
#Return most-common number in list.
def most_common(my_list):
counter = 0 #initialize counter
#loop through to get frequency of each element
for number in my_list:
frequency = my_list.count(number)
#if current frequency is > than counter, update our counter with the new frequency
if fre... |
#Return new list of tripled nums for those nums divisible by 4.
def tripled_nums(nums):
return [num**3 for num in nums if num%4 == 0] |
# Is phrase a palindrome?
def is_palindrome(phrase):
converted_phrase = phrase.lower()
reversed_word = converted_phrase[::-1]
if converted_phrase == reversed_word:
return "Is palindrome"
else:
return "Not palindrome"
print(is_palindrome("Pop")) # Is palindrome
print(is_palindrome("c... |
import random
import sys
file1=open("Result3.txt","a+")
class Game:
def _init_(self):
print("class initialised")
def startgame(self):
score=0
ques1=["Which was India’s first-ever tactical missile?"," Which type of coal is difficult to light in the open air?","Which industry was st... |
name=input("enter the name:")
if name>"a"and name<"z":
surname=input("enter the surname")
id=input("enter your email address or phone number")
if id>"a"and id<"z"or id>"0" and id<"9"or id=="@":
password=input("enter the password")
if password>"a"and password <"z"or password<"9"or password=="... |
# a=300-123
# num=int(input("enter the number"))
# if a==num:
# print("equal")
# else:
# print("not equal")
|
# a=int(input("enter the triangle"))
# b=int(input("enter the triangle"))
# c=int(input("enter the triangle"))
# if a+b+c==180:
# print("it is valid")
# else:
# print("not valid")
|
#이 클래스는 shipclass와 유사하다.
import pygame
from pygame.sprite import Sprite
import random
class Fish(Sprite):
"""첫번째 물고기 하나를 표현하는 클래스"""
def __init__(self, screen,p):
"""물고기를 초기화하고 시작 위치를 지정한다"""
super(Fish, self).__init__()
self.screen = screen
#물고기 이미지를 불러오고 이 이... |
mylist=[89,39,90,62,77,56]
print('elements in the list',mylist)
listsum=sum(mylist)
print('sum of elements in the list is:: ',listsum)
|
# This is going to be a really crappily designed idle game tbh
# Modules
import random
from time import sleep
from os import system, name
#global vars
gold = 1
max_health = 10
curr_health = 10
attack = 3
max_mana = 10
curr_mana = 10
level = 1
intel = 3
luck = 1
speed = 3
crit_chance = 1
crit_strike... |
s1 = int(raw_input("enter side 1 length "))
s2 = int(raw_input("enter side 2 length "))
s3 = int(raw_input("enter side 3 length "))
if #YOUR CODE HERE:
print("can make a triangle")
else:
print("can't make a triangle")
# Try lengths:
# s1 = 5, s2 = 6, s3 = 7 -> can make
# s1 = 1, s2 = 2, s3= 6 -> can't make
# ... |
produto = input('digite o nome do produto: ')
categoria = int(input('digite a categoria do produto: 1- Alcoolico 2- Não Alcoolico'))
if categoria == 1:
print(f'\nProduto: {produto}\nCategoria: Alcoolico')
else:
print(f'\nProduto: {produto}\nCategoria: Não Alcoolico') |
lista = []
lista2 = ['Marcela', 'Nicole', '*Matheus', 10]
lista3 = [1, 2, 3, 5]
print(lista)
print(lista2)
print(lista3)
lista.append(lista2)
lista.append(lista3)
print(lista)
lista_perguntas = [input('Digite seu artista favorito'), input('Digite seu guitarrista favorito')]
print(lista_perguntas)
posicao = int(i... |
from sys import argv
script, file = argv
#used to move the file on
def advance():
global currentLine
currentLine = source.readline()
#determines what type of comman is on that line
def commandType(currentLine):
if currentLine[0] == '(':
return 'L'
elif currentLine[0] == '@':
... |
#攝氏('C')轉換成華氏('F')程式
cels = input('請輸入攝氏溫度: ')
cels = float(cels)
fahr = float(cels * (9 / 5) + 32)
print('攝氏轉換成華氏:%3.1f ', fahr)
print('攝氏轉換成華氏:%.2f '%fahr)
|
#! /usr/bin/python
# coding:utf-8
def do_sort():
# 冒泡排序要排序n个数,由于每遍历一趟只排好一个数字,
# 则需要遍历n-1趟,所以最外层循环是要循环n-1次,而
# 每趟遍历中需要比较每归位的数字,则要在n-1次比较
# 中减去已排好的第i位数字,即每趟循环要遍历是n-1-i次
lst = [1, 4, 3, 5, 2]
for i in range(len(lst)-1):
for j in range(len(lst)-1-i):
if lst[j] < lst[j+1]:
... |
def count_games(file_name):
with open(file_name, 'r') as source_file:
return sum(1 for line in source_file)
def decide(file_name, year):
if str(year) in open(file_name).read():
return True
else:
return False
def list_from_file(file_name, place, type):
data = []
with open(... |
##################################################################
# 해당 소스파일의 저작권은 없습니다.
# 필요하신 분들은 언제나 사용하시길 바라며, 해당 소스코드의 부족한 부분에 대해서는
# whcl303@hanmail.net으로 언제든지 피드백 주시길 바랍니다.
# 소스설명 : 데이터 읽기 함수로 EDA 등 데이터분석이 끝난 데이터를 읽어오는 함수입니다.
# 포함함수 : csv 파일 읽기, excel 파일 읽기
####################################################... |
# Linguagem de estimacao escolhida: Python
from socket import *
type = raw_input("HTTP, FTP ou SMTP?\n")
while (not type.upper() in ['HTTP', 'FTP', 'SMTP']):
type = raw_input("Por favor, coloque um protocolo valido (HTTP, FTP ou STMP)\n")
# Codigo caso a requisicao seja valida
if (type.upper() == "HTTP" or type.uppe... |
import random
def jogar_forca():
print("Bem vindo ao jogo de forca!")
palavra_secreta = carrega_palavra()
letras_acertadas = ininializa_letras_acertadas(palavra_secreta)
enforcou = False
acertou = False
erros = 0
print(letras_acertadas)
while (not enforcou and not acertou):
... |
import random
import pygame
pygame.init()
class Circle:
def __init__(self, x, y, radius):
self.x = x
self.y = y
self.radius = radius
self.color = [255, 0, 0]
self.direction = "up"
def draw(self, window):
pygame.draw.circle(window, self.color, (self.x, self.y)... |
from tkinter import *
from math import sqrt
def distance(x1, y1, x2, y2):
"distance séparant les points x1,y1 et x2,y2"
d = sqrt((x2-x1)**2 + (y2-y1)**2) # théorème de Pythagore
return d
def forceG(m1, m2, di):
"force de gravitation s'exerçant entre m1 et m2 pour une distance di"
return ... |
"""
===> Programa: Interface
===> Função: Criar GUI
===> Descrição: Criar Widgets dinamicamente para uso da GUI
===> Criador: Adenisio Pereira de Freitas
===> Ano Criação: 2018
"""
#importando classe tkinter
from tkinter import *
class Interface(object):
def __init__(self, instanciaTK): #ins... |
#coding:utf8
# staticmethod 不会收到默认的第一个参数 cls。
# staticmethod 类似于Java中的 静态方法
# classmethod 可以说是 静态方法的一个变种,多出来的第一个参数,有时会有神奇的作用。
class A(object):
@staticmethod
def f(arg1, arg2):
print arg1,arg2
# 静态方法 可以用 类名,或者 实例来调用
A.f(1,3)
A().f(3,4)
|
velocidade = float(input('Qual a velocidade do seu carro? Km/h _'))
if velocidade > 80:
excesso = velocidade - 80
print(f'Você excedeu em {excesso:.2f} Km/h o limite de velocidade e a sua multa é de {excesso*7:.2f} MZN')
print('Continuação de boa viagem')
|
pauta = []
templis = []
contador = 0
while True:
pauta.append(templis[:])
nome = input("Nome: ")
nota1 = float(input("Nota 1: "))
nota2 = float(input("Nota 2: "))
stop = input("Quer continuar? (s/n)").upper()
pauta[contador].append(nome)
pauta[contador].append(nota1)
pauta[contador].app... |
import sys
DIGIT_MAP = {
'zero': '0',
'um': '1',
'dois': '2',
'três': '3',
'quatro': '4',
'cinco': '5',
'seis': '6',
'sete': '7',
'oito': '8',
'nove': '9',
}
'''
primeira forma de tratar excepções
def converter(s):
try:
number = ''
for token in s:
number += DIGIT_MAP[token]
... |
lista = list()
lista_par = list()
lista_impar = list()
while True:
lista.append(int(input("Introduza um nr: ")))
continuar = input("Deseja continuar? (S/N) _").strip().upper()[0]
if continuar == "N":
break
for c in lista:
if c % 2 == 0:
lista_par.append(c)
else:
lista_impar.append(c)
pri... |
from time import sleep
def contador(inicio, fim, intervalo):
if intervalo < 0:
intervalo *= -1
if intervalo == 0:
intervalo = 1
print('-='*25)
print(f'Contagem de {inicio} até {fim} de {intervalo} em {intervalo}')
conta = inicio
if inicio < fim:
while conta <= fim:
print(conta, end=' ', flush=True)... |
lista = list()
limite = int(input("Quantos nrs queres digitar? "))
for c in range(0,limite):
x = int(input("Digite um nr: "))
if x not in lista:
lista.append(x)
else:
print(f"O valor {x} já existe na lista")
print(lista)
print(sorted(lista)) |
casa = float(input('Qual o valor da sua casa? MZN_'))
salario = float(input('Qual o seu salário mensal líquido? MZN_'))
anos = int(input('Em quantos anos pretendes pagar o empréstimo? '))
valor_prestacao = casa/(anos*12)
if valor_prestacao >= salario*0.3:
print('Emprestimo negado')
else:
print(f'Emprestimo aceite, ... |
l1 = float(input('Medida do 1º lado: '))
l2 = float(input('Medida do 2º lado: '))
l3 = float(input('Medida do 3º lado: '))
if l1 < l2 + l3 and l2 < l1 + l3 and l3 < l1 + l2:
print('Os segmentos podem formar um triangulo', end=": ")
if l1 == l2 == l3:
print('Equilatero')
elif l1 != l2 != l3:
... |
pauta = {}
pauta['nome'] = input("Nome: ")
pauta['media'] = float(input("Media: "))
print('-='*20)
if pauta['media'] >= 14:
pauta['situacao'] = 'Aprovado'
elif pauta['media'] < 8:
pauta['situacao'] = 'Reprovado'
else:
pauta['situacao'] = 'Recuperacao'
for k,v in pauta.items():
print(f" - {k} é igual a ... |
lista_par = list()
lista_impar = list()
lista = [lista_par,lista_impar]
for c in range(0,7):
x = int(input(f"Digite o {c+1}o numero: "))
if x % 2 == 0:
lista_par.append(x)
else:
lista_impar.append(x)
print(f"Os numeros pares digitados foram: {sorted(lista_par)}")
print(f"Os numeros impares digitados foram: {so... |
try:
temp_C =float(input('Please enter temperature in Celsius:'))
temp_F = temp_C*1.8+32
print('The temperature in', temp_C , 'Celsius is equal to', temp_F , 'in Fahrenheit')
except:
print('Please enter number only.')
|
import matplotlib
count = 0
total = 0
while True:
line = input('Enter a number:')
if line == 'done':
break
try:
itervar = float(line)
total = total + itervar
count = count + 1
except:
print('Bad data')
continue
print('total=', total, 'count... |
fname = input("Enter a file name:")
fhand = open(fname)
for line in fhand:
if line.startswith('From'):
words = line.split()
print(words[1])
else:
continue
|
from square import Square
class Grid:
def __init__(self):
self.grid = [[]] * 9
self.build_grid()
def build_grid(self):
self.grid = [[Square(), Square(), Square(),
Square(), Square(), Square(),
Square(), Square(), Square()
... |
import sqlite3
mainpath = __file__[:-13] + "client_chat\\"
path = mainpath
print(path)
def create_table():
conn = sqlite3.connect(path)
c = conn.cursor()
try:
c.execute("""CREATE TABLE chat(
username text,
conversation text
)""")
... |
# Define function to reverse string
def reverse_string(str):
return str[::-1]
# Import regular expressions module
import re
# Input text
text_input = input("Input some text: ")
# Remove non-alphabetic characters from string, then make it lowercase
text_input = re.sub(r'[^A-Za-z]', '', text_input)
text_input = te... |
"""
The n-queens puzzle is the problem of placing n queens on an n×n chessboard such that no two queens attack each other.
Given an integer n, return all distinct solutions to the n-queens puzzle.
Each solution contains a distinct board configuration of the n-queens' placement, where 'Q' and '.' both indicate a quee... |
import sys
def getox(num):
"""获得十六进制"""
if num == 0:
return [0]
ret = []
while num:
cur = num % 16
ret.append(cur)
num = num // 16
return ret
def isPanlindrome(nums):
"""验证是否为回文串"""
if nums == nums[::-1]:
return 1
return 0
def solver(num):
... |
# coding:utf-8
# 股票最大利润,只能买卖一次
def solver(nums):
minNum = nums[0]
maxProfit = 0
for n in nums:
maxProfit = max(maxProfit, n - minNum)
if n < minNum:
minNum = n
return maxProfit
def test():
nums = [7,1,5,3,6,4]
ret = solver(nums)
print(ret)
if __name__ == '__ma... |
# 2018-8-7
# read data from file
class ReadData(object):
"""
Usage:
test = ReadData(filename)
test.getKcol(2, force=True) to get K column data ingore string
test.getKAvg(2, force=True) to get the average of k column data ingore string or other type
"""
def __init__(self, filename,):
self.file = filename
s... |
'''
Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M.
Symbol Value
I 1
V 5
X 10
L 50
C 100
D 500
M 1000
For example, two is written as II in Roman numeral, just two one's added together. Twelve is... |
'''
Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.
Example:
Input:
[
1->4->5,
1->3->4,
2->6
]
Output: 1->1->2->3->4->4->5->6
'''
# 2018-6-18
# Merge k Sorted Lists
# 超出内存限制
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
... |
"""
Given two binary trees, write a function to check if they are the same or not.
Two binary trees are considered the same if they are structurally identical and the nodes have the same value.
Example 1:
Input: 1 1
/ \ / \
2 3 2 3
[1,2,3], [1,2,3]
Output: tru... |
"""
Given an array of non-negative integers, you are initially positioned at the first index of the array.
Each element in the array represents your maximum jump length at that position.
Determine if you are able to reach the last index.
Example 1:
Input: [2,3,1,1,4]
Output: true
Explanation: Jump 1 step from index... |
# 2018-8-21
# 单源最短路径
# Dijkstra算法
# 算法导论 P383
# 数据结构与算法分析 P224
class graphNode(object):
def __init__(self):
self.known = False
self.dist = INF
self.p = None
self.adj = []
def dijkstra(G):
"""
每次取出最小dist并且属性known为False的节点v,对v的邻节点进行松弛操作, 直到G中的known属性为False的节点为0。
"""
while len(G) != 0:
v = smallestUnknow... |
# 2018-8-16
# greedy algorithm
# example
def change(money, values, count):
lens = len(values)
res = [0] * lens
c = 0
for i in range(lens):
if money <= 0:
break
c = min(money // values[i], count[i])
res[i] = c
money -= c * values[i]
return res
count = [ 3, 1, 2, 1, 1, 3, 5 ]
values = [1,2,5,10,20,50,... |
# coding:utf-8
# 数组循环右移 将一个长度为n的数组A的元素循环右移k位,
# 比如 数组 1, 2, 3, 4, 5 循环右移3位之后变成 3, 4, 5, 1, 2
def solver(nums, k):
lenNums = len(nums)
if k > lenNums:
k = k % lenNums
left = lenNums - k
numsL = nums[:left][::-1]
# print(numsL)
numsR = nums[left:][::-1]
numsL.extend(numsR)
return numsL[::-1]
def test():
n... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
'''
Welcome to vivo !
'''
def solution(total_disk,total_memory,app_list):
# TODO Write your code here
ret = 0
que = [[total_disk, total_memory, 0]] # 初始15磁盘, 10内存,0个用户
while len(que) != 0:
curSize = len(que)
tmp = []
for i in range(cur... |
# Definition for singly-linked list.
class ListNode(object):
def __init__(self):
self.val = None
self.next = None
class ListNode_handle:
def __init__(self):
self.cur_node = None
def add(self, data):
# add a new node pointed to previous node
nod... |
#OS模块遍历文件
#date(2018-4-15)
import os
dirpath = input("请输入要遍历的文件夹:")
def getdir(dirpath,level=0):
level += 2
if not dirpath:
dirpath = os.getcwd()
mylist = os.listdir(dirpath) #写到if条件外面
for name in mylist:
print('-'*level+'|'+name)
name = ... |
# 2018-8-21
# 拓扑排序
# 算法导论 P335
# 数据结构与算法分析 P219
class Vertex(object):
def __init__(self, name=None, degree=None, p=[], c=[]):
self.name = name
self.degree = degree # 入度
self.p = None # 前驱
self.c = None
self.sortNum = None
def topSort(G):
"""
使用BFS实现拓扑排序。
每次找到入度为0的节点放入列队,遍历与入度为0的点相邻的节点,并将度数减少1,如果度数变为0则... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.