text stringlengths 37 1.41M |
|---|
# Update this text to match your story.
start = '''
You wake up in a world full of talking animals and you find yourself turned into
an oranage cat. You find a map underneath your bed and realize it leads to
treasure.
'''
print(start)
print("Type 'forest' to go to the forest or 'cave' to go to the cave.")
u... |
x,y=input().split()
a=[]
a.append(x)
a.append(y)
b=['R','P']
c=['P','R']
e=['R','S']
f=['R','S']
g=['P','S']
h=['S','P']
if a==b or a==c:
print('P')
elif a==e or a==f:
print('R')
elif a==g or a==h:
print('S')
else:
print('D')
|
S=input()
a=[]
for i in range(len(S)):
if S[i].islower():
a.append(S[i].upper())
else:
a.append(S[i].lower())
z=''
for i in range(len(a)):
z=z+a[i]
print(z)
|
#Function to check the answers and returns the number of correct answer
def checkAnswers(filename, answer_list):
num_correct = 0
correct_answers = getCorrectAnswers(filename)
for i in range(len(correct_answers)):
if correct_answers[i] == answer_list[i]:
num_correct += 1
return num_co... |
#part 1a
#ask user for salary, percent of salary saved, and total cost of home
annual_salary = float(input("Enter your annual salary: "))
portion_saved = float(input("Enter the percent of your salary to save, as a decimal: "))
total_cost = float(input("Enter the cost of your dream home: "))
#data from problem
portion... |
MELON_COST = 1.00
def print_payment_status(payment_data_filename):
"""Calculate cost of melons and determine who has underpaid."""
payment_data = open(payment_data_filename) # open the file
# Iterate over lines in file
for line in payment_data:
# Split line by '|' to get a list o... |
def is_pangram(sentence):
result = True
check = ['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']
for c in check:
if c in sentence.lower():
result = True
else:
result = False
return result
return ... |
import threading
threadLock = threading.Lock()
class BankAccount(object):
def __init__(self):
self.balance = 0
self.status = False
def get_balance(self):
if self.status == True:
return self.balance
else:
raise ValueError("That is not an open account.")
... |
# encoding=utf-8
## SOLVED 2015/01/04
## 425185
# In the 5 by 5 matrix below, the minimal path sum from the top left to the
# bottom right, by moving left, right, up, and down, is indicated in bold red
# and is equal to 2297.
# [example...]
# Find the minimal path sum, in matrix.txt (right click and "Save Link/Targe... |
#encoding=utf-8
## SOLVED 2014/05/07
## 249
# If we take 47, reverse and add, 47 + 74 = 121, which is palindromic.
# Not all numbers produce palindromes so quickly. For example,
# 349 + 943 = 1292,
# 1292 + 2921 = 4213
# 4213 + 3124 = 7337
# That is, 349 took three iterations to arrive at a palindrome.
# Although ... |
# encoding=utf-8
## SOLVED 2013/12/19
## 31875000
# A Pythagorean triplet is a set of three natural numbers, a < b < c, for which,
# a^2 + b^2 = c^2
# For example, 3^2 + 4^2 = 9 + 16 = 25 = 5^2.
# There exists exactly one Pythagorean triplet for which a + b + c = 1000.
# Find the product abc.
import math
TARGET = ... |
# encoding=utf-8
## SOLVED 2014/12/01
## 8319823
# Euler's Totient function, φ(n) [sometimes called the phi function], is used
# to determine the number of positive numbers less than or equal to n which are
# relatively prime to n. For example, as 1, 2, 4, 5, 7, and 8, are all less
# than nine and relatively prime to ... |
# encoding=utf-8
## SOLVED 26/12/14
## 161667
# It turns out that 12 cm is the smallest length of wire that can be bent to
# form an integer sided right angle triangle in exactly one way, but there are
# many more examples.
# 12 cm: (3,4,5)
# 24 cm: (6,8,10)
# 30 cm: (5,12,13)
# 36 cm: (9,12,15)
# 40 cm: (8,15,17)
# ... |
#encoding=utf-8
## SOLVED 2014/04/10
## 16695334890
# The number, 1406357289, is a 0 to 9 pandigital number because it is made up of
# each of the digits 0 to 9 in some order, but it also has a rather interesting
# sub-string divisibility property.
# Let d1 be the 1st digit, d2 be the 2nd digit, and so on. In this wa... |
#encoding=utf-8
## SOLVED 2014/04/10
## 5777
# It was proposed by Christian Goldbach that every odd composite number can be
# written as the sum of a prime and twice a square.
# 9 = 7 + 2×12
# 15 = 7 + 2×22
# 21 = 3 + 2×32
# 25 = 7 + 2×32
# 27 = 19 + 2×22
# 33 = 31 + 2×12
# It turns out that the conjecture was false... |
#encoding=utf-8
## SOLVED 2014/04/18
## 121313
# By replacing the 1st digit of the 2-digit number *3, it turns out that six of
# the nine possible values: 13, 23, 43, 53, 73, and 83, are all prime.
# By replacing the 3rd and 4th digits of 56**3 with the same digit, this
# 5-digit number is the first example having se... |
#encoding=utf-8
## SOLVED 2014/04/10
## 1533776805
# Triangle, pentagonal, and hexagonal numbers are generated by the following
# formulae:
# Triangle Tn=n(n+1)/2 1, 3, 6, 10, 15, ...
# Pentagonal Pn=n(3n−1)/2 1, 5, 12, 22, 35, ...
# Hexagonal Hn=n(2n−1) 1, 6, 15, 28, 45, ...
# ... |
# encoding=utf-8
## SOLVED 2013/12/23
## 2783915460
# A permutation is an ordered arrangement of objects. For example, 3124 is one
# possible permutation of the digits 1, 2, 3 and 4. If all of the permutations
# are listed numerically or alphabetically, we call it lexicographic order. The
# lexicographic permutations ... |
#!/usr/bin/env python
# coding: utf-8
# In[ ]:
#Problem
#A string is simply an ordered collection of symbols selected from some alphabet and formed into a word; the length of a string is the number of symbols that it contains.
#An example of a length 21 DNA string (whose alphabet contains the symbols 'A', 'C', 'G'... |
#!/usr/bin/env python
# coding: utf-8
# Problem
# Either strand of a DNA double helix can serve as the coding strand for RNA transcription. Hence, a given DNA string implies six total reading frames, or ways in which the same region of DNA can be translated into amino acids: three reading frames result from reading th... |
x = [int(i) for i in input().split()]
if x[0] % x[1] == 0 or x[1] % x[0] == 0:
print("Sao Multiplos")
else:
print("Nao sao Multiplos")
|
n = int(input())
str =''
m = 0
matrix = [[0 for i in range(n)] for j in range(n)]
for i in range(n):
for j in range(n):
matrix[j][i] = 2 ** i
for i in range(1,n):
for j in range(n):
matrix[i][j] = matrix[i-1][j]*2
cond = matrix[n-1][n-1]
while cond !=0:
m +=1
cond = cond//10
m -=1... |
import math
a = int(input())
year = math.floor(a / 365)
n = a % 365
month = math.floor(n/ 30)
day = n % 30
print("{0} ano(s)".format(year))
print("{0} mes(es)".format(month))
print("{0} dia(s)".format(day)) |
import math
I = 0
while I < 1.8:
for i in range(3):
if I % 1 == 0:
print("I={0} J={1}".format(math.floor(I), math.floor(1+i+I)))
else:
print("I={0:.1f} J={1:.1f}".format(I, 1+i+I))
I +=0.2
I +=0.2
for i in range(3):
print("I={0} J={1}".format(math.floor(I), math.floo... |
def TofH(disks, source, middle, target):
if disks == 1:
print('Move disk 1 from tower {} to tower {}.'.format(source, target))
return
TofH(disks - 1, source, target, middle)
print('Move disk {} from tower {} to tower {}.'.format(disks, source, target))
TofH(disks - 1, middle, source, t... |
#!/bin/usr/env python3
plainText = input("Enter a one-word, lowercase message to be encrypted: ")
distance = int(input("Enter the distance value: "))
code = ""
for ch in plainText:
ordValue = ord(ch)
cipherValue = ordValue + distance
if cipherValue > ord('z'):
cipherValue = ord('a') + distance - (o... |
#!/usr/bin/env python3
# Define Dictionary
info_Dict = {}
student = {}
#Create Dictionary with four keys and values
for any in range(0,3):
id = input('Enter Student I.D.: ')
#Populate the dictionary with student's information using input()
info_Dict['Name'] = input('Name: ')
info_Dict['Age'] =... |
decimal = int(input("Enter a integer: "))
if decimal == 0:
print(0)
else:
print("Quotient Remainder Binary")
bitString = ""
while decimal > 0:
remainder = decimal % 2
decimal = decimal // 2
bitString = str(remainder) + bitString
print("%5d%8d%12s" % (decimal, remainder, b... |
# https://stepik.org/lesson/24462/step/8?unit=6768
class ExtendedStack(list):
def popLastElems(self, num):
for i in range(num):
self.pop()
def sum(self):
tmp = self[-1] + self[-2]
self.popLastElems(2)
self.append(tmp)
def sub(self):
tmp = self[-1] - sel... |
from __future__ import print_function
word = ""
letter = ""
updatedSpaces = []
lives = 6
def initialize():
word = "earring"
print['_ _ _ _ _ _ _']
def getLetter():
print('Guess a letter.')
letter = raw_input()
global letter
def won():
if letter in word:
print('Yay, you won!!')
... |
import pygame
# stolen a little bit from http://pygame.org/wiki/TextWrap
def draw_text(screen, font, text, color, position, width=None):
text = str(text)
if not width:
width = font.size(text)[0]
line_spacing = 0
y = position[1]
font_height = font.size('Tg')[1]
while text:
i = 1... |
def word_count(s):
# Your code here
dict = {}
ignoreCharacters = '" : ; , . - + = / \ | [ ] { } ( ) * ^ &'.split()
lower_s = s.lower()
for i in ignoreCharacters:
lower_s = lower_s.replace(i, " ")
for x in lower_s.split():
if x not in dict:
dict[x] = 1
else:
... |
def add_time(start, duration, input_day=""):
start_minutes = convert_hour_to_minutes(convert_hour_to_24_h_time(start))
duration_minutes = convert_hour_to_minutes(duration)
sum_of_minutes = start_minutes + duration_minutes
raw_time, past_days = convert_minutes_to_hour(sum_of_minutes)
raw_time_converted = conve... |
"""Author - Maksim Sapunov msdir6199@gmail.com 02/01/2021"""
# task_4 . Программа принимает действительное положительное число x и целое отрицательное число y.
# Необходимо выполнить возведение числа x в степень y. Задание необходимо реализовать в виде функции my_func(x, y).
# При решении задания необходимо обойтись б... |
#!/usr/bin/env python3
"""mapper.py"""
import sys
for line in sys.stdin:
line = line.strip()
line = line.replace(" ", "")
def split(x):
return [char for char in x]
letters = split(line)
for letter in letters:
print('%s\t%s' % (letter, 1))
|
arr = [69, 10, 30, 2, 16, 8, 31, 22]
def quicksort(lo, hi):
if lo >= hi:
return
i, j = lo, hi
while i < j:
while i <= hi and arr[lo] >= arr[i]:
i += 1
while arr[lo] < arr[j]:
j-= 1
if i < j:
arr[i], arr[j] = arr[j], arr[i]
arr[lo]... |
def getLeft(a,b):
stck = []
while True:
a += 1
b -= 1
if 0 <= a < N and 0 <= b < N:
stck.append((a,b))
else:
break
return stck
def getRight(a,b):
stck = []
while True:
a += 1
b += 1
if 0 <= a < N and 0 <= b < N:
... |
def path(x,y,max):
if x == max or y == max or y < 0 or x < 0:
return 0
elif not visit[x][y] and base[x][y] != 1: #위, 왼, 오른, 아래 이 순서대로
visit[x][y] = 1
if base[x][y] == 3 or path(x-1, y, max)or path(x, y-1, max) or path(x, y+1, max) or ... |
def binary(a,b):
left = 1
count = 0
mid = (left+a)//2
while True:
count += 1
if mid == b:
return count
elif mid > b:
a = mid
mid = (left+a)//2
elif mid < b:
left = mid
mid = (left+a) // 2
for i in range(int(inp... |
def sequence():
source = [0, 1, 2, 3, 4, 5] # MARINE
destin = [1, 3, 2, 0, 5, 4] # AIRMEN
result = []
for i in range(len(source)):
if source[i] != destin[i]:
for j in range(i, len(source)):
if source[j] == destin[i]:
for k in range(j, i, -1):
... |
from turtle import *
shape ("turtle")
speed (-1)
color = ["red", "blue", "brown", "yellow", "green"]
i = 3
for i in range (3, 7):
for j in range (i):
fillcolor (color[i-3])
begin_fill()
forward (100)
left (360/i)
end_fill()
mainloop() |
numb = int(input("Enter a number: "))
a = 2
loop = True
while a < numb:
if numb % a == 0 :
loop = False
break
# print (" is a prime number")
a +=1
if loop == True:
print ("{0} is a prime number".format(numb))
else:
print ("{0} is not prime number".format(numb))
|
from turtle import *
shape = ("turtle")
speed (-1)
for j in range (50):
for i in range (4):
forward (100)
left (90)
left (9)
mainloop () |
from turtle import *
shape = ("turte")
speed (-1)
a = 100
left (135)
for i in range (30):
for j in range (4):
forward (a)
left (90)
right (8)
a = a + 5
mainloop ()
|
# 1) Escriba un programa que pida dos números enteros y que calcule su división, escribiendo si la división
# es exacta o no.
a=int(input("Introduzca numero 1 "))
b=int(input("Introduzca numero 2 "))
4
d=float(a / b)
e=a%b
print("El resultado es:", d)
if e > 0:
print("La division no es exacta")
else:
print("L... |
class Perro():
def __init__(self,nombre,edad,Duenio):
self.Nombre=nombre
self.edad=edad
self.Duenio=Duenio
def ladrar(self):
print("Wau Wau Wau")
def correr(self):
print("anda libre")
print("ingrese nombre, edad y dueño del perro")
Nombrep=input()
Anios=input... |
# 9)Se tiene registrado la producción (unidades) logradas por un operario a lo largo de la semana ( lunes a
# sábado. Elabore un algoritmo que nos muestre o nos diga si el operario recibirá incentivos sabiendo que
# el promedio de producción mínima es de 100 unidades.
contador = 0
promedio = 0
while True:
if ... |
from categoria import Categoria
from validacion import validator
def categorias():
formcate={}
formcate['nombrecate']=input('Nombre Categoria: ')
formcate['edit']="0"
if validator.validar_cate(formcate)=={}:
Cate=Categoria("",formcate['nombrecate'])
Cate.save()
print('Categoria... |
# 5- Emplear con diccionarios y array el ejercicio para obtener el promedio de nota de los alumnos
# del ejercicio 10 de bucles. Poner todas las notas y su nombre en una variable. Luego devolver un
# diccionario con el nombre de cada alumno y su promedio.
alumnos={}
for alumno in range(1):
alumnos['nombre']=input(... |
# 3) Definimos un diccionario con los barrios donde viven las siguientes personas:
# - Pedro: lugano
# - Ramiro: Boedo
# - Ricardo: Parque chas
# - Jazmín: Villa Urquiza
# - Andrea: San Cristóbal
# - Laura: Almagro
# Luego eliminar a Pedro y a Jazmín y agregar los siguientes:
# - Marcela: Boedo
# - Roberto: Agronomía
... |
# Crear una lista de enteros, inicializarlos segun valores aleatorios en el rango
# 1..20 y computar la media de los valores, el valor mas alto y el mas bajo
# (utilizando listas). Utilizar las funciones para generacion de numeros
# aleatorios de Python
import random
lista = []
for i in range(20):
lista.append(ra... |
# Ejercicios sencillos de aprendizaje de python
from math import pi
# Funcion que retorne el mayor de dos numeros o 0 si son iguales
def max_numeros(num1, num2):
"""
Devuelve el mayor de dos numeros x e y
:param num1: float
:param num2: float
:return: float
"""
if num1 > num2:
ret... |
# 9- Implementar una función que pone en mayúsculas todas las primeras letras de las palabras de
# una frase.
print("Ingrese un texto a Capitalizar")
text = str(input())
print(text.title())
|
# 10) Elabora un algoritmo para leer 3 números enteros diferentes entre si, y determinar el número mayor
# de los tres.
Contador=1
print("Ingrese 3 numeros enteros diferentes entre si")
print("Ingreso un numero",Contador)
a=int(input())
Contador=Contador+1
print("Ingreso un numero",Contador)
b=int(input())
Contador=Co... |
#!/usr/bin/python
# input from keyboard is a string, so it has to be converted w. the int() func
x=int(input("give me a number"))
if (x<=11):
print("too little")
elif (x>1 and x<10):
print("Just about right")
else:
print("Too high")
|
#Problem Link: https://www.codechef.com/problems/HOLES
for i in range(int(input())):
string=input()
ctr=0
for a in string:
if (a=='A' or a=='D' or a=='O' or a=='P' or a=='R'or a=='Q'):
ctr=ctr+1
elif (a=='B'):
ctr=ctr+2
else:
ctr=ctr+0
print(ct... |
number = int(input("enter number:"))
for x in range (1, 13):
print(number, "x", x, " = ", number*x)
|
"""
Faça um programa que peça uma nota, entre zero e dez.
Mostre uma mensagem caso o valor seja inválido e continue pedindo
até que o usuário informe um valor válido.
"""
while True:
nota = float(input("Digite uma nota: "))
if 0 <= nota <= 10:
break
else:
print("A nota deve ser entre 0 e 10")
print(f"{nota}"... |
#Altere o programa anterior para que ele aceite apenas números entre 0 e 1000.
continuar = "s"
conjunto = []
maior = -1
menor = -1
soma = 0
while continuar.lower() == "s":
novo_numero = int(input("Digite um número: "))
if 0 < novo_numero < 1000:
conjunto.append(novo_numero)
if maior == -1 and menor == -1:
... |
"""
Faça um programa que peça um número inteiro e determine se ele é ou não
um número primo. Um número primo é aquele que é divisível somente por ele mesmo e por 1.
"""
primo = True
numero = int(input("Informe um número: "))
for x in range(1,10):
if numero != x and x != 1:
resto = numero%x
if resto == 0:
pri... |
"""
Faça um programa para a leitura de duas notas parciais de um aluno. O programa deve calcular a média alcançada por aluno e apresentar:
A mensagem "Aprovado", se a média alcançada for maior ou igual a sete;
A mensagem "Reprovado", se a média for menor do que sete;
A mensagem "Aprovado com Distinção", se a média f... |
#Altere o programa anterior, intercalando 3 vetores de 10 elementos cada.
vetor1 = [ 0, 3, 6, 9, 12, 15, 18, 21, 24, 27 ]
vetor2 = [ 1, 4, 7, 10, 13, 16, 19, 22, 25, 28 ]
vetor3 = [ 2, 5, 8, 11, 14, 17, 20, 23, 26, 29 ]
vetor4 = []
i = 0
while i < 10:
vetor4.append(vetor1[i])
vetor4.append(vetor2[i])
vetor4.append... |
"""
Faça um Programa que leia um vetor A com 10 números inteiros, calcule
e mostre a soma dos quadrados dos elementos do vetor.
"""
vetor = [ 8, 11, 2, 9, 30, 7, 15, 56, 42, 13]
soma = 0
for numero in vetor:
quadrado = numero**2
soma+=quadrado
print(f"{numero}^2 = {quadrado}")
print(f"A soma dos quadrados é: {s... |
"""
A série de Fibonacci é formada pela seqüência 0,1,1,2,3,5,8,13,21,34,55,...
Faça um programa que gere a série até que o valor seja maior que 500.
"""
n1 = 1
n2 = 1
current = 0
i = 1
sequencia = ""
while True:
if current > 500:
break
else:
if i == 1:
sequencia+=str(n1)+", "
elif i == 2:
sequencia+=st... |
# -*- coding: utf-8 -*-
"""
Created on Fri May 29 17:16:40 2020
@author: 1052668570
VISUALIZE THE ACTIVATION OF THE INNER LAYER
Used to understand what our model is doing and for dimensional reduction of
the dataset
"""
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
import seaborn as sns
imp... |
# -*- coding: utf-8 -*-
"""
Created on Mon May 11 14:59:21 2020
@author: 1052668570
fake advertising data set, indicating whether or not a particular internet user
clicked on an Advertisement. We will try to create a model that will predict
whether or not they will click on an ad based off the features of that user.
... |
import random
secret_num = random.randinit(1, 1005)
print "I am thinking of a number between 1 and 1005"
guess = 0
while guess != secret_num:
guess = raw_input("Take a guess:")
guess = int(guess)
if guess < secret_num:
print "Your guess is too low"
if guess > secret_num:
print "Your guess is too high" |
from random import randint
numerosDaAposta = []
while len(numerosDaAposta) < 6:
numero_aleatorio = randint(1, 60)
if numero_aleatorio not in numerosDaAposta:
numerosDaAposta.append(numero_aleatorio)
numerosDaAposta.sort()
print('Os números que você deve jogar são: {}'.format(numerosDaAposta))
|
###########################
# FILE: boggle.py
# WRITER: michal ivianski , michaliv , 207182452
# maya kedem, maya_kedem, 209544121
# EXERCISE: intro2cs1 ex12 2021
# DESCRIPTION: A program that runs Boggle game using GUI.
# WEB PAGES I USED: https://katzr.net/9da5f0
# https://katzr.net/d47847
#... |
from typing import List, Tuple, Any
class ParserError(Exception):
"""Raised if there is an error while parsing"""
pass
def parse(tokens: List[str]):
"""Return JSON dict from tokens"""
if not tokens:
raise ParserError("Expected value")
t = tokens[0]
if t == "[":
return _list(... |
#make a map/dictionary of the given values (number, count)
#return the keys of the map
from collections import OrderedDict
def unique( dataList=[] ):
uniqueDict=OrderedDict() #make a dictionary to contain the unique keys
for value in dataList:
if value in uniqueDict:
uniqueDict[value]+=1
else:
uniqueDict[... |
from math import sqrt
a = float(raw_input( 'valor de a: '))
b = float(raw_input('valor de b: '))
c = float(raw_input('valor de c; '))
if a == 0:
if b == 0:
if c == 0:
print 'La ecuacion no tiene solucion'
else:
print 'La ecuacion tiene infinitas soluciones'
else:
x= -c / b
print... |
# while True:
# userRequest = input("beznam???? ")
# if userRequest == "y":
# print('fire fire fire')
# else:
# print("chashm ")
# break
#
# print("the end")
# a = 10
# while a > 0:
# print(a)
# b = int(input("be man ye adad zoj bede"))
# if b % 2 == 0:
# a = a-1... |
# This program converts Celsius temperatures
# to Fahrenheit temperatures.
celsius = int(input('What is the temperature in Celsius? '))
# Calculation
fahrenheit = (celsius * 9/5) + 32
# Display result
print('Fahrenheit =', format(fahrenheit, '.2f'))
|
# This program accepts a sentence in
# uppercase letters and then converts
# that sentence into pig latin.
def main():
# Get sentence from user
my_string = input('Enter your sentence in uppercase letters: ')
word_list = my_string.split()
new_string = []
# Converts sentence into pig l... |
# This program translates Latin words to
# English. The windows displays 3 buttons, one
# for each latin word. When clicked the program
# displays the english translation.
import tkinter
class TranslatorGUI:
def __init__(self):
# The main window
self.main_window = tkinter.Tk()
... |
# This program creates the Employee class and
# ProductionWorker subclass
class Employee:
# Data Attributes
def __init__(self, name, number):
self.__name = name
self.__employee_num = number
# The class mutators
def set_name(self, name):
self.__name = name
def se... |
# This program is a recursive function that accepts
# an interger n, and prints the number 1 through n.
def main():
num = int(input('Enter a number to count to: '))
recfun(num)
def recfun(num):
if num == 1:
print(num)
else:
recfun(num - 1)
print(num)
# Call the m... |
# This program prompts to user to enter a number
# range between 1-10. The program will display
# the corresponding number in Roman Numerals.
number = input('Please enter a number to convert: ')
# Roman Numeral converter
if number == '1':
print('Roman Numeral: I')
elif number == '2':
print('Roman ... |
# This program lets a user enter a course number
# the program then displays the course's room number,
# instructor, and meeting time.
def main():
# Room dictionary
rooms = {'CS101': '3004', 'CS102': '4501',
'CS103': '6755', 'NT110': '1244',
'CM241': '1411'}
# Instr... |
class Animal:
def __init__(self):
self.hung_level=5.00
0<=self.hung_level<=10
self.eng_level=5.00
0<=self.eng_level<=10
self.animal_name=input('choose your animal name:')
def __str__(self):
return print(f' the animal name is: {self.animal_name} hunger level :{self.hu... |
import turtle
import random
turtle.tracer(1,0)
SIZE_X=800
SIZE_Y=500
square_size=30
turtle.penup()
turtle.hideturtle()
turtle.register_shape('plane1.gif')
turtle.goto(-300,250)
turtle.showturtle()
plane=turtle.clone()
plane.shape('plane1.gif')
plane.goto(100,100)
turtle.hideturtle()
number_of_types=4
food_pos=[]
fo... |
"""
array utilities
"""
from random import randint
def array_generator(min, max, arr_size=10, isRandom=True, isRandomRange=False):
"""
Generate an array random or otherwise
:param min: int, arrays min number
:param max: int, arrays max number
:param arr_size: int, default = 10, total number of i... |
# -*- coding: utf-8 -*-
"""
@author: scatt
"""
import csv
# utility function to add two lists element-by-element
def add_lists(l1, l2):
temp = []
for i in range(len(l1)):
temp.append(l1[i]+l2[i])
return temp
# utility function to determine whether existing state is sufficient for pr... |
import os
from tkinter.filedialog import askdirectory
def prompt_user():
directory = input(
"Enter path of directory to inspect (or leave blank for directory picker): "
)
if directory == "":
directory = askdirectory()
if not os.path.exists(directory) or not os.path.isdir(directory):
... |
'''
Created on Mar 7, 2020
@author: Caleb & Sharai
'''
import platform # operating system platform
import checkerboard
import abstractstrategy
class Strategy(abstractstrategy.Strategy):
"Tonto 2.0"
def utility(self, board):
"Return the utility of the specified board"
numPawns = board.get... |
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
'''Risk2S'''
# 敏感词文本文件 filtered_words.txt,里面的内容为以下内容,当用户输入敏感词语时,则打印出 Freedom,否则打印出 Human Rights。
with open("./filtered_words.txt", 'r') as f:
words = f.readlines()
# 列表推导式
word_list = [i.replace('\n', '') for i in words]
print("敏感词:")
for w in word_list:print(w... |
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
from scipy.stats import mode
from sklearn.preprocessing import LabelEncoder
# KNN Classifier Class
class KNN_Classifier():
def __init__(self, K):
self.K = K
# Function to store... |
#conditions
#It checks the condition and return the answer in True or False
#==
#!=
#<=
#>=
#<
#>
print(2==2)
print(2<2)
print(4>8)
print(10<=5+4)
print(2+5-9>17)
print(True)
print(False==True)
print(12==3*4)
print(12+67-6+5*6/8 != 6+45+789-9)
#If-Else Statement
#case => 1:
if 2 < 10:
... |
import re
`Findall method:`
s = 'Hello world, this is a test!'
result = re.findall(r'\w+',s)
=> ['Hello', 'world,', 'this', 'is', 'a', 'test!']
`sub string method:`
print(re.sub( r'\S+' , 'WORD', s))
=> WORD WORD WORD WORD WORD WORD
|
##############################################################################################
# 1. Multiples of 3 or 5
##############################################################################################
#If we list all the natural numbers below 10 that are multiples of 3 or 5,
#we get 3, 5, 6 and 9. The s... |
def word_dictionary():
d = dict()
words = open('words.txt')
for line in words:
word = line.strip().lower()
d[word] = word
d['a']='a'
d['i']='i'
d['']=''
return d
def word_dictionary():
d=dict()
allwords=open('words.txt')
for line in allwords:
word=line.str... |
from pronounce import read_dictionary
def word_dictionary():
d = dict()
words = open('words.txt')
for line in words:
word = line.strip().lower()
d[word] = word
return d
def homophone(w1,w2,phone):
if phone[a]==phone[b]:
return True
else:
return False
reduced_ho... |
def binary(num): # перевод в 2 систему + доп код
if num == None:
return -1
if type(num) != str:
return -1
if num == "":
return -1
otr_bin = ""
dopkod = ""
count = 1
new_str = ""
bin_str = ""
num = int(num)
flag = 0
if num < 0: # определ... |
fibonacci = []
def series(n):
if n <= 1:
return n
else:
return(series(n-1) + series(n-2))
upperLimit = int(input("Enter a number: "))
if upperLimit <= 0:
print("Enter any positive number")
else:
print("series sequence:")
for i in range(upperLimit... |
#ATM program to withdraw cash from ATM
notesOf = [2000,500,100]
amount = input("Enter amount: ")
notes = 0
for i in range(len(notesOf)):
notes = amount / notesOf[i]
print notes, "notes of", notesOf[i]
amount = amount % notesOf[i]
|
from collections import OrderedDict
def seconds_to_human(seconds):
"""
Convert seconds to human readable format like 1M.
From Thomas Sileo's blog post How to convert seconds to human readable
interval back and forth with Python: <https://myl.be/d4>.
:param seconds: Seconds to convert
:type s... |
# !/usr/local/bin/python3.4.3
# ----Copyright (c) 2019 Carnegie Hall | The MIT License (MIT)----
# run script with 4 arguments:
# argument 0 is the script name
# argument 1 is path to List1: SHORTER list CSV (contains only some items)
# argument 2 is path to List2: LONGER list CSV (contains all items)
# argument 3 is d... |
import numpy as np
def vector_to_matrices(vector, sizes):
#print "LOL!", vector
matrices = []
start = 0
for s in sizes:
m = vector[start:start+(s[0]*s[1])]
start += s[0]*s[1]
matrices.append(m)
return matrices
def matrices_to_vector(matrices):
return np.hstack(matrices) |
def encrypt(text, level):
encryptedText = ""
# Visits all letters in the text
for i in range(len(text)):
#Check letter by letter
char = text[i]
#Check if it is UpperCase or LowerCase
if(char.isupper()):
#
encryptedText += chr((ord(char) + level - 65)... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.