text stringlengths 37 1.41M |
|---|
# Faça um programa que leia duas listas e gere
# uma terceira com das duas primeiras
lista_1 = [1, 2, 3]
lista_2 = ["a", "b", "c"]
tam = len(lista_1)
x = 0
while x < tam:
pos = lista_1[x]
lista_2.append(pos)
x+=1
listao = lista_2
print(listao)
|
# Escreva uma expressão que será utilizada para decidir se uma aluna foi ou não aprovada.
# Para ser aprovada, todas as médias da aluna devem ser maiores que 7.
# Considere que a aluna cursa apenas três matérias,
# e que a nota de cada uma está armazenada nas seguintes variáveis: materia1, materia2 e materia3.
mater... |
# Faça um programa que solicite o preço de uma mercadoria e
# o percentual de desconto. Exiba o valor do desconto e o preço a pagar.
preco = float(input("Preço da mercadoria: "))
desconto = float(input("Desconto na mercadoria: "))
porcentagem_desconto = (preco * desconto) / 100
preco_final = preco - porcentagem_desco... |
# Modifique o programa da listagem 6.6 para
# ler 7 notas em vez de 5.
notas=[0, 0, 0, 0, 0, 0, 0]
soma=0
x=0
while x<7:
notas[x]=float(input("Nota %d:" % x))
soma += notas[x]
x+=1
x=0
while x<7:
print("Nota %d: %6.2f" % (x, notas[x]))
x+=1
print("Média: %5.2f" % (soma/x)) |
#define 'greet()'
def greet():
print ("Hey there!")
name = raw_input("Please type your name: ")
print ("Nice to meet you " + name)
country = raw_input("So where are you from? ")
print ("Interesting, so you're from " + country)
print ("I'd love to visit there someday! :)")
choice = raw_i... |
# Take a list of numbers
my_list = [12,65,54,39,102,339,221,]
# use anonymous function to filter
result = list(filter(lambda x: (x%13==0),my_list))
# display the result
print('Numbers divisible by 13 are',result) |
# Multiplication table (from 1 to 10) in Python
num = 12
# To take input from the user
# num = int(input('Display multiplication table of? '))
#Iterate 10 times from i = 1 to 10
for i in range(1,11):
print(num,'x',i,'=',num*i) |
name = 'Benedict'
# Learning indexning
print('LEARNING INDEXING')
print(name[0])
print(name[1])
print(name[-1])
# String Slicing
print(name[:4])
#String Method
full_name = 'Uwazie, Benedict'
string1 = full_name.split()
string2 = full_name.split(',')
print(string1)
print(string2)
# Length of a string
sentence = ' H... |
#!/usr/bin/env python3
import sys
if len(sys.argv)<2:
print("""
Please supply a filename when you run this file
For example:
python3 {0} input.txt
python3 {0} nums.txt
""".format(sys.argv[0]))
sys.exit(1)
filename = sys.argv[1]
with open("nums.txt","r") as infile:
linecount = 0
for line i... |
import pandas as pd
import matplotlib.pyplot as plt
#import sys
import click
"""input at console: python csv_parser.py display_columns oktoberfestgesamt19852016.csv """
@click.group()
def cli():
"""can display and plot csv files."""
pass
@cli.command()
@click.argument('filename')
def display(filename):
... |
#!/usr/bin/env python
# -*- coding: utf-8; -*-
from pyPdf import PdfFileWriter, PdfFileReader
import os, os.path
import sys
def rotate(_filename):
print "Rotate all page of PDF:", _filename
input_filename = _filename.replace(".pdf", ".pdf.bak")
output_filename = _filename
rotated... |
running = True
while running:
calificacion = int(input('Muestra calificacion : '))
cal = float(calificacion)
if cal >= 7:
print('Has Aprobado, Felicidades')
# this causes the while loop to stop
running = False
elif cal < 7:
print('Reprobado, Suerte para la proxima')
... |
# Descripcion: Programa que permite a un usuario jugar a Piedra, papel o tijera con un jugador virtual PC
# Entrada: Seleccion entre piedra, papel o tijera hecha por el usuario
# Salida: Felicitaciones al usuario ganador
# Autor: EALCALA
# Fecha: 03.05.2017
# Version: 1.0
#Plataforma: Python v3.6
import sys
w = in... |
# Descripcion: Programa que, de una lista precargada [1, 4, 9, 16, 25, 36, 49, 64, 81, 100], escoge los numeros pares y los imprime de salida en una lista al usuario en una sola linea
# Entrada: Lista [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
# Salida: Una lista que contiene los numeros pares de la lista [1, 4, 9, 16, 25... |
class Guess:
def __init__(self, word):
## 단어를 secretword에,
self.secretWord = word
self.guessedChars = []
self.numTries = 0
self.currentStatus = '_' * len(self.secretWord)
def display(self):
print('Current : ' + self.currentStatus)
print('Tries : ' + str... |
def revers(n):
t=n[::-1]
if (n==t):
print("YES")
else:
print("NO")
n=input()
revers(n)
|
#!/usr/bin/env python3
# -*- coding:utf-8 -*-
from sys import stdin
import unicodedata
def removecjk(input):
output = []
for i in unicodedata.normalize('NFKC', input):
uc = unicodedata.name(i, "NOPE")
if ("HIRAGANA" not in uc and "FULLWIDTH" not in uc and "KATAKANA" not in uc and "CJK" not in uc and "IDEOGRAPHI... |
def countdown_recursion(n: int) -> None:
if n >= 0:
print(n)
countdown_recursion(n - 1)
# While loop
def countdown_while(n: int) -> None:
while n >= 0:
print(n)
n = n - 1
print("Begin recursoin")
countdown_recursion(5)
print("Begin while")
countdown_while(5)
|
from Player import Player
from Option import Option
# A room is a collection of options with an id and a description to show the user.
# It includes methods create a list of option objects and interact with them.
# Should check if the requirements for an option are met before asking option to display itself.
class Roo... |
class Solution:
def isAnagram(self, s: str, t: str) -> bool:
if len(s) < 1 or len(t) >= 5 * pow(10, 4) or len(s) != len(t):
return False
return sorted(s) == sorted(t)
if __name__ == "__main__":
s = Solution()
print(s.isAnagram(s = "anagram", t = "nagaram"))
print(s.isAnag... |
import Repositorio
# Funciones
# funcion hash simple, recibe un string y retorna un string
def hashSimple(num):
binario_decimal = int(num, 2) # convierte la cadena en entero, de binario a decimal (en base 2)
mod = (binario_decimal * 7) % 13 # se realiza el modulo (a * 7) mod 13
resul = bin(mod)[2:... |
# Cria tabuleiro com "-" dentro
# null -> list
def novo_tabuleiro():
tabuleiro = list()
for i in range(3):
# Adiciona linha na matriz
tabuleiro.append([])
# Adiciona "-" nas linhas da matriz
for x in range(3):
tabuleiro[i].append("-")
return tabuleiro
# Mostra ... |
"""Faça um programa que leia um numero inteiro N e depois imprima os N primeiros naturais impares"""
n = int(input('Insira N:'))
for i in range(1, n+1):
print(2*i-1)
|
"""
Escreva um programa que:
a) Crie/abra um arquivo texto de nome arq.txt
b) Permita que o usuário grave diversos caracteres nesse arquivo, até que o usuário entre com o caractere 0
c) Feche o arquivo
Agora, abra e leia o arquivo, caractere por caractere, e escreva na tela todos os caracteres armazenados.
"""
with o... |
"""
Faça uma função que receba como parametro o valor de um angulo em graus e calcule o valor do cosseno desse angulo
usando a série de Taylor (truncar em n=5). Use pi = 3.141593
"""
pi = 3.141593
def fatorial(numero):
"""Retorna o fatorial do número passado como parâmetro"""
resultado = 1
for i in range... |
"""
Faça um programa para ler 10 números diferentes a serem armazenados em um vetor. Os dados deverão ser armazenados na
ordem que forem sendo lidos, sendo que caso o usuário digite um numero ja digitado, o programa deve pedir que digite
outro. Exibir na tela o vetor final que foi digitado.
"""
lista = []
while len(l... |
"""
Crie uma classe Televisão e uma classe ControleRemoto que pode controlar o volume e trocar os canais da Televisao.
O controle de colume permite aumentar ou diminuir uma unidade de cada vez
O controle de canal permite aumentar e diminuir uma unidade ou trocar para canal indicado
Criar metodos para consultar valor do... |
"""
Make a function that encrypts a given input with these steps:
Input: "apple"
Step 1: Reverse the input: "elppa"
Step 2: Replace all vowels using the following chart:
a => 0 e => 1 i => 2 o => 2 u => 3
# "1lpp0"
Step 3: Add "aca" to the end of the word: "1lpp0aca"
Output: "1lpp0aca"
Examples
encrypt("banana") ➞ "0n... |
"""
Create a function that takes two numbers as arguments (num, length) and returns a list of multiples of num up to length.
list_of_multiples(7, 5) ➞ [7, 14, 21, 28, 35]
list_of_multiples(12, 10) ➞ [12, 24, 36, 48, 60, 72, 84, 96, 108, 120]
list_of_multiples(17, 6) ➞ [17, 34, 51, 68, 85, 102]
"""
def list_of_multipl... |
def mc91(n):
if n > 100:
return n - 10
else:
return mc91(mc91(n + 11))
def mc91_no_recursive(n):
loop = 1
while loop:
if n > 100:
n -= 10
loop -= 1
else:
n += 11
loop += 1
return n
for i in range(80, 120):
print(i,... |
# doubly linked list
class Frob(object):
def __init__(self, name):
self.name = name
self.before = None
self.after = None
def setBefore(self, before):
self.before = before
def setAfter(self, after):
self.after = after
def getBefore(self):
return self.befor... |
# Sudoku [http://en.wikipedia.org/wiki/Sudoku]
# is a logic puzzle where a game
# is defined by a partially filled
# 9 x 9 square of digits where each square
# contains one of the digits 1,2,3,4,5,6,7,8,9.
# For this question we will generalize
# and simplify the game.
# Define a procedure, check_sudoku,
# that takes ... |
# complexity O(len(L)) # linear
def search(L, e):
for i in range(len(L)):
if L[i] == e:
return True
return False
a = [1, 2, 3, 4, 0]
b = [3, 0, 2, 4, 1]
c = [3, 2, 4, 1, 5]
def foo(L):
val = L[0]
while (True):
val = L[val]
foo(c) |
# recursion
# 1. RECURSIVE step: ridurre un problema alla sua versione piu semplice
# 2. BASE case_ continua a ridurre fino a quando raggiungi il caso piu semplice che puo essere ridotto direttamente
def recurMul(a, b):
'''
moltiplica a*b, utilizzando l'addizione e la ricorsione
(senza moltiplicar... |
# -*- coding: cp1252 -*-
# Recursive Definition
# 1. Base case: the starting point (not defined in terms if itelf)
# es.: smallest imput already know
# 2. Recursive case (defined in terms of smallest version of itelf)
# "does the recursive case modify my arguments in such a way that each
# recursion brings it one ste... |
# From Lecture 4, How Environments Separate Variable Bindings
def square(x):
return x * x
def twoPower(x, n):
while n > 1:
x = square(x)
n = n / 2
return x
|
import subprocess
# We use subprocess to run system commands in python
# Shows the date
# subprocess.run(["date"])
# Keeps the interpreter idle for 2 seconds
# subprocess.run(["sleep", "2"], shell=True)
# This type of run commands is only useful if we wanna figure out if the command is successful or not
# To obtai... |
#!/usr/bin/env python
# coding: utf-8
#this program converts image to .mif (black & white)
# Autores MI Elizabeth Fonseca Chávez- MI Mario Alfredo Ibarra Carrillo
#
import sys
from PIL import Image
import numpy
def convertirImagen(modo):
#checking the origin's file forma
origin=Image.open("cora.png")
#Opening the ... |
#encoding: UTF-8
# Autor: Alejandro Chávez Campos, A01374974
# Descripcion: Mi programa es de dar como resultado coordenadas polares, a partir de coordenas cartesianas.
#A partir de aquí escribe tu programa
import math
coordenadaX=float(input("Dame el valor de la coordenada en x: "))
coordenadaY=float(input("Dame el... |
users = ['Alice','Bob','Claire','Dan', 'Emma', 'George', 'Harry']
while True:
print('Hi! My name is Sarah')
name = input('What is your name?: ').strip().capitalize()
if name in users:
print('Hello, {}!'.format(name))
remove = input('Would you like to be removed from the database? y/n :... |
# -*- coding: utf-8 -*-
import sys
"""
Created on Sat Jun 5 16:46:30 2021
@author: Zeliha
"""
def checkSpecialTurkishChar(i):
if((i=='ü') or (i=='Ü') or (i=='ö') or (i=='Ö') or (i=='ç') or (i=='Ç') or (i=='ğ') or (i=='Ğ') or (i=='ş') or (i=='Ş')):
return 1
else:
return 0
def ... |
print('name')
name=input()
print('age')
age=input()
hunnit=100-int(age)
year=2017+hunnit
print('you will be 100 in the year',year,'which is', hunnit,'years')
|
# Uses python3
import sys
def get_majority_element(arr, left, right):
if left == right:
return -1
def majority_element(lo, hi):
if lo == hi:
return arr[lo]
mid = lo + (hi - lo) // 2
leftSide = majority_element(lo, mid)
rightSide = majority_element(mid + 1,... |
import unittest
import wordcounter
class testWordCounter(unittest.TestCase):
def test_space(self):
#Pass Test
self.assertEqual(wordcounter.determineWordCount("The cow is black and white"), 6)
#Fail Test
#self.assertEqual(wordcounter.determineWordCount("The cow is black and white"), ... |
# this function is provided by you
def delete_item(shopping_list):
number=int(input("Which number to delete: "))
if number<1 or number>len(shopping_list):
print("Invalid number\n")
else:
item=shopping_list.pop(number-1)
print(item," was deleted\n")
print()
# append neww item to ... |
def pattern(n):
if n == 0:
return
# given algorith
else:
pattern(n-1)
print(n,'******'*n)
pattern(n-1)
try:
# take input and convert it into integer
n = int(input("Enter the number of branches: "))
# if number is pisitive
if n > 0:
pattern(n)
# if number is negative
else:
print("Only positive numb... |
from abc import ABC
class AbstractEstado(ABC):
def __init__(self, is_objetivo, custo_transicao=lambda s,a,st: 1):
self.isObjetivo = is_objetivo
self.custoTransicao = custo_transicao
@abstractmethod
def acoesPossiveis(self):
""" AbstractEstado -> (AbstractAcao)
... |
'''The new "Avengers" movie has just been released!
There are a lot of people at the cinema box office standing in a huge line.
Each of them has a single 100, 50 or 25 dollars bill.
A "Avengers" ticket costs 25 dollars.
A clerk wants to sell a ticket to every single person in this line.
Can he/sh... |
list=['fisika','kimia',1993,2017]
print("Nilai ada pada index 2:",list[2])
list[2]=2001
print("Nilai baru ada pada index 2:",list[2])
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Nov 11 15:42:42 2020
@author: Nicholas Vieira
@differencing.py
Functions which are called by Q3_advection.py and Q4_diffusion_advection.py.
Functions perform various steps of finite differencing, including:
- Forward-Time Central-Space method, for ... |
'''Crea una funcion llamada get_list que reciba el nombre de un fichero de palabras y devuelva
un diccionario donde la clave de cada elemento sea un numero 1, 2, 3 y el valor sea una lista
con las palabras del fichero que tienen esa longitud. Si una palabra aparece repetida, solo se
tendra en cuenta una. En cada lınea... |
"""
Bubble sort is a simple sorting algo that sorts data in worst case O(n^2). It compares two pieces of data in a list and swaps them if they are out of order.
"""
def bubble_sort(l):
if len(l) == 0:
return None
for iteration in range(len(l)):
for index in range(1, len(l)):
... |
import sys
import queue
class Tree_Node(object):
def __init__(self, value=None):
self.value = value
self.left = None
self.right = None
def get_value(self):
return self.value
def set_value(self, new_val):
self.value = new_val
de... |
#1
with open('my_work.txt', 'w') as f:
number_words = 0
while number_words != 3:
word = input('Введите текст: ')
f.write(f'{word}\n')
number_words += 1
#2
with open('my_work.txt', 'r') as f:
content = f.readlines()
print(f'Количество строк: {len(content)}')
count = 1
f... |
import matplotlib.pyplot as plt
import datetime
import nltk
from nltk.corpus import stopwords
def is_number(s):
try:
float(s)
return True
except ValueError:
return False
def word_frequency_analysis(all_words_person1, all_words_person2, stopwords):
word_count_dict_person1 = {}
... |
# print(users)
# del users[0]
# # print(users)
# for user in users:
# if user[1] == 'This':
# print(user)
# print('End')
# break
# else:
# pass
'''
Dictionary Comprehension
# '''
users = [
(0, 'Me', "mypassword"),
(1, 'You', "yourpassword"),
(2, 'This', "... |
# import sys
# import random
# while True:
# print(' Type exit to exit.')
# response = input()
# if response == 'e' or response == 'E':
# sys.exit()
# print(' You typed ' + response + '.')
|
from os import system
from time import sleep
class User():
def __init__(self, first_name, last_name, sex, email, password):
"""initialize the properties of a user"""
self.first_name = first_name
self.last_name = last_name
self.sex = sex
self.email = email
self.passw... |
print("HELLO, PLS GIVE US YOUR FEEDBACK ON THIS TUTORIAL\n")
names = []
flag = True
count = 0
while flag:
name = input("Enter your name: ")
feedback = input("your feedback: ")
count += 1
names.append(name)
with open('t_folder\\user_feed.txt', 'a') as fil:
fil.write("\n\n({})".format(count))
fil.write("\nNAME... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
__author__ = 'Michael Lockwood'
__github__ = 'mlockwood'
__email__ = 'lockwm@uw.edu'
def find_skew(genome):
"""
Find the skew of a genome.
:param genome: genome string
:return: space delimited skew string
"""
skew = [0]
for base in genome:
... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import sys
from constants import *
from generic import *
__author__ = 'Michael Lockwood'
__github__ = 'mlockwood'
__email__ = 'lockwm@uw.edu'
def transcribe_dna_to_rna(dna):
"""
Take a DNA string and convert it to its corresponding RNA string.
:param dna:... |
class Cube:
def __init__(self, height, width, length):
self.height = height
self.width = width
self.length = length
def sorted_list(self):
dim_tuple = (self.height, self.width, self.length)
dim_list = list(dim_tuple).copy()
dim_list.sort()
return dim_list
def __le__(self, other):
self_dim = s... |
# filename:perform_mp.py
# funcion: performance test comparison between sequential and multiprocessing
#
import time
import multiprocessing
def count(n):
while n > 0:
n -= 1
starting = time.time()
print ("\nstarting time %s: " %time.ctime(time.time()))
count(5000000)
count(5000000)
ending = time.ti... |
#filename:list_nest.py
#function: List ,It is possible to nest lists
# it menas list can create lists containing other lists
mem_list_USA_UK = ['adeile', 'Madonld', 'Elton John']
mem_list_TWN = ['fiev may','A-mei','five hundred']
global_singer = [mem_list_USA_UK,mem_list_TWN]
print("\nGlobal singer: ",global_singer )... |
#filename:list_create.py
#function:list creation
#Creat list using []
newList = []
print("newLIst=", newList)
for i in range(0, 5):
newList.append(i*2)
print("newlist after using append()=",newList)
#create list using list()
outputlist=list()
print("Outputlist=",outputlist)
for x in newList:
if x%2 == 0:
... |
#filename: primary_key.py
#function: create table using primay key and select two table such as orders and customers
import sqlite3
#create a Database
def db_connect(db):
try:
conn = sqlite3.connect(db)
print("conn=",conn)
return conn
except Error as err:
print(err)
... |
#filename:TCP-socket-12-2.py
#function:create an TCP IP using AF_INET, SOCK_STREAM socket
#AF_INET is Internet Protocol
#SOCK_STREAM is TCP
#connect to server: s.connect((ip , port))
import socket #for sockets
import sys #for exit
#Step1: create the socket
TCP_or_UDP=1
TCPorUDP=["UDP","TCP"]
try:
if TCP_or... |
#filename: fun-para.py in chap2
#function: parameters maybe no, more, or arbitary parameters
def fun_return_data(a,b):
c = a + b
return c
def adding(*paras):
total = 0
for data in paras:
total += data
return total
print("\nplease input two data to Function")
data1=input()
data2=input()
da... |
#filename:ex6-3.py
#funcion: annual party game
listresult = []
for basis in [10,30,50]:
for times in [2,3]:
listresult.append(basis*times)
print(listresult)
listresult=[]
listresult=[basis*times for basis in [10,30,50] for times in [2,3]]
print(listresult)
|
#filename:exam1-1.py
#function while loop (in chap1)
message_text = 'coap protocol for some IoT projects'
count = 0
max=len(message_text)
while (count < max):
count = count + 1
print("count=", count)
print ('The char is:', message_text[count-1])
print ("vvvvv Good boy vvvvv!")
|
#filename:employee_count.py
#function: create database and create table, insert value to table
import sqlite3
dbfile= "D:/BOOK/CHAP13/employee.DB"
connection = sqlite3.connect(dbfile)
cursor = connection.cursor()
# delete the table first
cursor.execute("""DROP TABLE employee;""")
sql_CREATE_TABLE = """
CREATE TABL... |
#filename: shutil_copy.py
#function: mkdir using OS method os.mkdir(….)
#need import sys for sys.stdout.write(...)
"""1.os.getcwd(): this method displays the current working directory.
Return a string representing the current working directory.
1. Dirctory: is a file whose data is a sequence of entries, each consists o... |
#filename:adding.py
#function: add the data by starting and ending data
def adding_func(para1=0,para2=50):
total = 0
i = para1
while i <= para2:
print(i," ",para2)
total += i
i += 1
return total
#the function call using the arguments data such as argument1,argument2
print... |
#filename:file_obj_attr.py
#function file object atribute
fileo = open("employee.txt", "r")
print ("Name of the file: ", fileo.name)
print ("file Closed? : ", fileo.closed)
if fileo.mode =='r':
print ("Opening mode is %s "%fileo.mode,"you have no right to Write")
import sys
sys.exit
elif fileo.mode =='w':
... |
#filename:sqlite_CreateDB_Table.py
#function: Python program using Sqlite
#Step1: Create user DB name using Sqlite3.connect("DB name)
#step2: Create Table using CREATE TABLE Table_name
#step3: insert Data value using INSERT INTO invest VALUES
import sqlite3
conndb = sqlite3.connect('chap13_DB.db')
curr = conndb.cursor... |
def nonConstructibleChange(coins):
if len(coins) == 0:
return 1
coins.sort()
change = 0
for coin in coins:
if coin > change + 1:
return change + 1
change += coin
return change + 1
if __name__ == "__main__":
coins = [5, 7, 1, 1, 2, 3, 22]
print(nonCon... |
def flip_and_invert_image(A):
for i in range(len(A)):
reversed_row = A[i][::-1]
for j in range(len(reversed_row)):
reversed_row[j] = reversed_row[j] ^ 1
A[i] = reversed_row
return A
print(flip_and_invert_image([[1,1,0],[1,0,1],[0,0,0]])) |
def majority_element(nums):
majority = 0
countMap = {}
for i in range(len(nums)):
if countMap.get(nums[i]):
countMap[nums[i]] += 1
else:
countMap[nums[i]] = 1
temp = 0
for key in countMap.keys():
if countMap[key] > temp:
temp = countMap[... |
class BinaryTree:
def __init__(self, value, left=None, right=None):
self.value = value
self.left = left
self.right = right
class TreeInfo:
def __init__(self, height, is_balanced):
self.height = height
self.is_balanced = is_balanced
def heightBalancedBinaryTree(tree):
... |
def find_factorial(number):
if number == 0:
return 1
return number * find_factorial(number - 1)
print(find_factorial(5)) |
senhas = [ input("1° - Usuario Cadastre sua primeira senha: "),
input("2° - Usuario Cadastre sua segunda senha: "),
input("3° - Usuario Cadastre sua terceira senha: "),
input("4° - Usuario Cadastre sua quarta senha: ")]
input("=============LOGIN==============")
login1 =... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Oct 28 17:24:33 2018
@author: kefei
"""
class Stack:
def __init__(self):
self.items = [] # data structure
def is_empty(self):
return self.items == []
def push(self, item):
self.items.append(item)
... |
#!/usr/bin/python
'''
This was written for Python 3.1
Stephen Mayhew
Nov. 17, 2010
'''
import sys
from math import sqrt,floor
# Here follow some hard-coded game rules
# form: {<boardsize> : {<word length>:<score>, ...} ... }
gameScoring = {4 : {3:1, 4:1, 5:2, 6:3, 7:5, 8:11, "large":lambda n: 11},
5 :... |
class BoardDrawer():
def __init__(self, board):
self.board = board
#self.update()
def update(self, currentplayer = None):
print(chr(27) + "[2J")
#print("Draw pile has: {} cards".format(len(self.board.drawpile)))
print("Draw pile (top card): {}".format(self.board.drawp... |
#!/usr/bin/python
# Collatz
# again, we memoize...
def collatz(n, mem):
''' get the collatz sequence for n '''
if n in mem:
return mem[n]
# base case
if n == 1:
# no need for memoization here
return [1]
l = [n]
if (n%2 == 0):
l.extend(collatz(n/2, ... |
"""Module with implementation of Weighted Graph."""
from queue import Queue
from stack import Stack
from collections import OrderedDict
import sys
class Graph(object):
"""Implementation of Graph Traversal."""
def __init__(self):
"""."""
self.node_dict = {}
def nodes(self):
"""Ret... |
import math
def quad_func():
# Intro
print("Quadtic equation formula: ")
print("ax^2 + bx + c = 0")
print("If any of variables doesn't exist, set it to 0 \n")
a = input("a = ")
b = input("b = ")
c = input("c = ")
try:
a = float(a)
b = float(b)
... |
'''
Given a singly linked list, determine if it is a palindrome.
Follow up:
Could you do it in O(n) time and O(1) space?
'''
#三种方法 最简单的是o(n)时间复杂度和o(n)的空间复杂度 定义一个list 一步一步往里面append
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
#o(... |
"""Module to train n-gram model.
Vectorizes training and validation texts into n-grams and uses that for
training a n-gram model - a simple multi-layer perceptron model. We use n-gram
model for text classification when the ratio of number of samples to number of
words per sample for the given dataset is very smal... |
# Importing required libraries
import cv2
import streamlit as st
import numpy as np
from PIL import Image
# Function for converting Color image to Pencil Sketch and other cartoon filters
def img_to_cartoon_filter(img,cartoon):
#converting colored image to grayscale using cv2 cvtColor function
gray = cv... |
# def distance(strand_a, strand_b):
# calculate = 0
# for ch1, ch2 in zip(strand_a, strand_b):
# if ch1 != ch2 and len(strand_a) == len(strand_b):
# calculate += 1
# if len(strand_a) != len(strand_b):
# raise ValueError("DNA strands not the same length!")
# return calculate
def distance(strand_a, strand_b):
if le... |
#!/bin/python
from math import sqrt
def factorize(n):
factors = []
stop = int(sqrt(n))
current_factor = 2
factor_multiplicity = 0
while current_factor <= stop:
while (n % current_factor) == 0:
factor_multiplicity += 1
n //= current_factor
if factor_multiplic... |
# read the contents of a file
# and print all lns in UpperCase
# ask the user for a file
fname = raw_input("path to file >")
# validate file
try:
fh = open(fname)
except:
print("Invalid path")
exit
# pt all lines
for line in fh:
print(line.upper().strip()) |
#!/usr/bin/python3
"""
Append to a file
"""
def append_write(filename="", text=""):
"""appends a string at the end of a text file
Args:
filename (str): the file
text (str): text that will be appended to the file
Returns: number of characters added
"""
with open(filename... |
#!/usr/bin/python3
"""
Matrix multiplication
"""
def matrix_mul(m_a, m_b):
"""function that multiplies 2 matrices
Args:
m_a: matrix a
m_b: matrix b
Returns: new matrix.
"""
if type(m_a) is not list:
raise TypeError("m_a must be a list")
if type(m_b) is not lis... |
#!/usr/bin/python3
def add_tuple(tuple_a=(), tuple_b=()):
tuple_c = (0, 0)
x = list(tuple_a)
y = list(tuple_b)
if len(x) == 0:
x = (0, 0)
if len(y) == 0:
y = (0, 0)
if len(x) == 1:
x = (x[0], 0)
if len(y) == 1:
y = (y[0], 0)
tuple_c = (x[0] + y[0], x[1] ... |
# Comparison Operators
print(2 == 2);
print(2 == 3);
#Notice capitalization counts with comparing strings.
print('Fred' == 'fred')
# Python will also take data types into account.
print('2' == 2)
# Floating point values are the same as integer
print(2.0 == 2)
# Not equals (!=)
print( 4 != 5 )
print( 6 != 6 )
# Gr... |
mylist = [1,2,3,4,5]
#Using the range function! Range function is a generator function. It creates data dynamically instead of taking up memory space like traditional variables.
for num in range(3,10,2): # Print starting at 3 up to but no including 10. Inclding a stepsize of 2. So print only the odd numbers between t... |
"""
Ask the user for a number and determine whether the number is prime or not. You can (and should!) use your answer to Exercise 4 to help you. XTake this opportunity to practice using functions, described below.X
"""
#A prime number (or a prime) is a natural number greater than 1 that has no positive divisors other t... |
"""
Write a program that takes a list of numbers (for example, a = [5, 10, 15, 20, 25]) and makes a new list of only the first and last elements of the given list. XFor practice, write this code inside a function.X
"""
a = [5, 10, 15, 20, 25]
new = []
"""
list.pop([i])
Remove the item at the given position in the lis... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.