text
stringlengths 37
1.41M
|
---|
n = 1
i = 0
# Um abaixo do outro
while n < 21:
print(n),
n = n + 1
# Um ao lado do outro
print("")
for i in range(1, 21):
print(i, end = ' ') |
n1 = 0
n1 = int(input("Informe um Valor : "))
if (n1 > 0):
print("O valor é positivo")
elif (n1 < 0):
print("O valor é negativo")
else:
print("O numero eh igual a 0") |
turno = ""
print("-- Em que turno voce estuda?")
print("-- Digite M para matutino, V para vespertino ou N para noturno")
turno = input("Opção escolhida: ").upper()
if (turno == "M"):
print("Bom dia!")
elif (turno == 'V'):
print("Boa tarde!")
elif (turno == 'N'):
print("Boa noite!")
else:
print("Valor invalido") |
nome = input('Informe seu nome: ')
nome = nome.upper()
nome_2 = list( nome )
nome_3=""
for i in nome_2 :
nome_3 += i
print(nome_3)
|
frase = 'insira a frase aqui a ser analisada'
contagem_espaco = int(frase.count(" "))
contagem_vogais = 0
for i in 'aeiou' :
contagem_vogais += int(frase.count(i))
print("Espaços:{0}, vogais:{1}".format(contagem_espaco,contagem_vogais)) |
# -*- coding: utf-8 -*-
"""
Created on Wed Aug 1 21:55:05 2018
@author: Toby
"""
number=int(input("請輸入大於一的整數:"))
for a in range(2,number):
if (number%a==0):
print("%d不是質數!"%(number))
break
else:
print("%d是質數!"%(number))
|
# -*- coding: utf-8 -*-
"""
Created on Tue Jul 31 12:43:20 2018
@author: Toby
"""
x=int(input("請輸入成績:"))
if(x>=90):
print("優等")
elif(x>=80):
print("甲等")
elif(x>=70):
print("乙等")
elif(x>=60):
print("丙等")
else:
print("丁等")
|
# -*- coding: utf-8 -*-
"""
Created on Tue Jul 31 20:23:29 2018
@author: Toby
"""
a=0
for x in range (1,int(input("請輸入正整數:"))+1):
a+=x
print("1到"+str(x)+"的整數合為"+str(a)) |
#Faça um programa que tenha uma função chamada ficha(),
# que receba dois parâmetros opcionais: o nome de um jogador e quantos gols ele marcou.
# O programa deverá ser capaz de mostrar a ficha do jogador, mesmo que algum dado não tenha sido informado corretamente.
def ficha(nome = ''.strip(), gols = 0):
print(f'O jogador {nome} fez {gols} gols')
n = str(input('Qual o seu nome ? '))
g = str(input('Quantos gols voce fez ? '))
if g.isnumeric(): #se g for numeric, gols = g se nao, placeholder
int(g)
elif g == '':
g = 0
else:
g = '</placeholder/>'
if not n.isnumeric():
nome = n
else:
n = '</placeholder/>'
ficha(n,g)
#|ERRO|Valor de gol nao identificado |
frase = input('digite uma frase ')
a = len(frase)
b = frase.count('a')
c = frase.find('a')
inv = frase[::-1]
p = inv.find('a')
r = a - p
print('a letra a aparece {} vezes, aparece pela primeira vez o espaço {} e aparece pela ultima vez no espaço {}'.format(b,c,r))
|
#Crie um programa que tenha uma dupla totalmente preenchida com uma contagem por extenso,
# de zero até vinte. Seu programa deverá ler um número pelo teclado (entre 0 e 20) e mostrá-lo por extenso.
extenso = ('zero', 'um', 'dois', 'três', 'quatro', 'cinco', 'seis', 'sete',
'oito', 'nove', 'dez', 'onze', 'doze', 'treze', 'quatorze',
'quinze', 'dezeseis', 'dezessete', 'dezoito', 'dezenove', 'vinte')
numero_escolhido = int(input('escolha um numero entre 0 e 20 para ser escrito por extenso: '))
while numero_escolhido <= 20 and numero_escolhido >= 0:
if numero_escolhido >= 0:
print(extenso[numero_escolhido])
break
else:
print('valor nao reconhecido')
break
|
sexo = ''
while sexo == '':
sexo = input('qual o seu sexo, 1- masculino, 2- feminino: ')
if sexo == '1':
print('sexo masculino')
exit()
if sexo == '2':
print('sexo feminino')
exit()
else:
sexo = ''
|
numero = input('digite um numero entre 1 e 9999 ')
a = numero[0]
b = numero[1]
c = numero[2]
d = numero[3]
print('unidade {}\n dezena {}\n centena {}\n milhar {}'.format(d,c,b,a))
|
'''Classe Bola: Crie uma classe que modele uma bola:
Atributos: Cor, circunferência, material
Métodos: trocaCor e mostraCor'''
class Bola:
def __init__(self, cor, circunferencia, material):
self.cor = cor
self.circunferencia = circunferencia
self.material = material
def trocar_cor(self, cor):
self.cor = cor
def mostrar_cor(self):
print(f'a cor da bola é {self.cor}')
bola1 = Bola('amarelo', 10, 'cilicone')
bola1.mostrar_cor()
bola1.trocar_cor('vermelho')
bola1.mostrar_cor()
|
num1 = float(input('Digite um numero '))
num2 = float(input('Digite outro numero '))
print('numero 1: {}\nnumero 2: {}'.format(num1,num2))
if num1 > num2:
print('O numero 1 é maior ')
elif num2 > num1:
print('O numero 2 é maior ')
else:
print('Os números nao tem diferença ou seja sao iguais ')
|
import sys
sexo = str(input('Qual o seu sexo (feminino) ou (masculino)? ')).lower()
if sexo == 'feminino':
print('mulheres nao tem alistamento obrigatorio')
sys.exit()
id = int(input('Qual seu ano de nascimento? '))
ano = 2019 - id
anoda = id + 18
alist = 18 - ano
if ano == 18:
print('O dever te chama, esta na hora de se alistar!!!')
elif ano < 18:
print('Voce ainda nao precisa se alistar, porem faltam {} anos para tal'.format(alist))
elif ano > 18:
print('ja passaram {} anos da sua hora de alistar, dispensado.'.format(alist * -1))
#print('voce nao precisa se alistar nas forças armadas') |
x = int(input('Digite um número para fazer a tabuada até o 10: '))
y = 1
while y <= 10:
print(f'{x} X {y} = {x*y}')
y = y + 1
|
#Defining the ride_costCalc function
def ride_costCalc(pickup_time,drop_off_time): # Calculate_fair function
ride_time = drop_off_time-pickup_time
#Time in minutes used for a ride
ride_cost=0
if ride_time<=30:
ride_cost=0
elif ride_time>30 and ride_time<=60:
ride_cost=1
elif ride_time>60 and ride_time<=120:
ride_cost=3
elif ride_time>120 and ride_time<=600:
ride_cost=7
elif ride_time>600:
ride_cost=50+7
else:
return "Invalid input"
return ride_cost
|
# -*- coding: utf-8 -*-
"""
Created on Sun Mar 18 21:16:22 2018
This script will clean up our terrorism event table.
It will then create a tableby reading from the referenced csv file.
The csv file had minor datamunging done in excel as well, including:
-- eliminating columns we were not interested in.
-- adding a date column
-- no edits appear needed to the column titles.
@author: joelee
"""
#
# import csv file and pull into a pandas dataframe
# end result incidents_df
# Dependencies
# import sqlite3
import pandas as pd
incidents_csv = "gtdb_0617_proj_cols.csv" #
# Read our Data file with the pandas library
# Not every CSV requires an encoding, but be aware this can come up
incidents_df = pd.read_csv(incidents_csv, encoding = "ISO-8859-1")
# display columns imported to confirm column names
#print(incidents_df.head())
# Dates show up as NaN where there are blanks.
# replace the NaNs with blanks
incidents_df = incidents_df.fillna({'Date':0, 'nkill':0, 'nwound':0})
#print(incidents_df.head(40))
# I'm not sure why, but putting a zero date value
# assigns it a date of 1/1/1970
incidents_df['Date'] = pd.to_datetime(incidents_df['Date'])
#print(incidents_df.head(40))
# incident nkill and nwound come in as float64. convert to int64
incidents_df['nkill'] = incidents_df['nkill'].fillna(0).astype(int)
incidents_df['nwound'] = incidents_df['nwound'].fillna(0).astype(int)
incidents_df['latitude'] = incidents_df['latitude'].astype(float)
incidents_df['longitude'] = incidents_df['longitude'].astype(float)
incidents_df['iyear'] = incidents_df['iyear'].astype(int)
# inspect the df datatypes, and convert any datatypes necessary for
# proper behavior
# event_id = integer;
# year = integer
# month = integer
# day = integer
# country_id = integer
# country_txt = varchar
# lat = float
# long = float
# attack Type 1 nvarchar
#
incidents_df = incidents_df.rename(columns={"eventid":"incident_id",
"Date":"idate",
"country":"icountry_id",
"country_txt":"icountry_txt",
"latitude":"ilatitude",
"longitude":"ilongitude",
"attacktype1":"attacktype_id",
"attacktype1_txt":"attacktype_txt",
"targtype1":"targtype_id",
"targtype1_txt":"targtype_txt",
"weaptype1":"weaptype_id",
"weaptype1_txt": "weaptype_txt",
"property":"property_flg"
})
#print(incidents_df.head())
#print(incidents_df['idate'].dtype)
#print(incidents_df.count())
# lat/long missing for 959-907 of the sample rows.
# remove rows where lat is nan or blank
incidents_df = incidents_df[pd.notnull(incidents_df['ilatitude'])]
#print(incidents_df.count())
#print (incidents_df.dtypes)
# text columns come in as objects instead of strings. examples online indicate this is ok.
#print(incidents_df.head())
# I consider this clean enough.
# trim off columns that appear to be difficult to maintain data integrity on.
org_inc_df = incidents_df[[ # "incident_id",
"iyear", "icountry_txt", "ilatitude", "ilongitude",
"attacktype_txt", "targtype_txt", "gname",
"weaptype_txt", "nkill"
]]
# Import SQL Alchemy
from sqlalchemy import create_engine # , func
# Import PyMySQL (Not needed if mysqlclient is installed)
import pymysql
pymysql.install_as_MySQLdb()
# Import and establish Base for which classes will be constructed
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()
# Import modules to declare columns and column data types
from sqlalchemy import Column, Integer, String, Float # , Date , ForeignKey
from sqlalchemy_utils import database_exists, create_database, drop_database
# Create the Incident class
class Incidents(Base):
__tablename__ = 'incidents_tbl'
incident_id = Column(Integer, primary_key=True)
iyear = Column(Integer) # incident year Column(String(255))
# imonth = Column(Integer) # incident month Column(Float)
# iday = Column(Integer) # incident day (String(255))
# idate = Column(Date) # Incident Date
# icountry_id = Column(Integer)
icountry_txt = Column(String(50))
ilatitude = Column(Float)
ilongitude = Column(Float)
# attacktype_id = Column (Integer)
attacktype_txt = Column (String(50))
# targtype_id = Column (Integer)
targtype_txt = Column (String(50))
gname = Column (String(100))
# weaptype_id = Column(Integer)
weaptype_txt = Column(String(100))
nkill = Column(Integer)
# nwound = Column(Integer)
# property_flg = Column (Integer)
# Create a connection to a SQLite database
# sqlite blows chunks. commenting out the sqlite db and Switching to mysql
#engine = create_engine('sqlite:///gtdb.sqlite')
# here we create a connection to the mysql database engine.
engine = create_engine("mysql://gtdb_admin:[email protected]:3306/gtdb")
if database_exists(engine.url):
drop_database(engine.url)
if not database_exists(engine.url):
create_database(engine.url)
conn = engine.connect()
# Create the incidets_tbl table within the database
Base.metadata.create_all(conn)
# To push the objects made and query the server we use a Session object
from sqlalchemy.orm import Session
session = Session(bind=engine)
## First approach--to write a row for each row in the df
## For each row of the dataframe, create an instance of the Incidents class
for idx in org_inc_df.index:
incident_row = Incidents( #incident_id=org_inc_df.loc[idx,'incident_id'],
iyear=org_inc_df.loc[idx,'iyear'],
# imonth= org_inc_df.loc[idx,'imonth'],
# iday= org_inc_df.loc[idx,'iday'],
# idate= org_inc_df.loc[idx,'idate'],
# icountry_id= org_inc_df.loc[idx,'icountry_id'],
icountry_txt= org_inc_df.loc[idx,'icountry_txt'],
ilatitude= org_inc_df.loc[idx,'ilatitude'],
ilongitude= org_inc_df.loc[idx,'ilongitude'],
# attacktype_id= org_inc_df.loc[idx,'attacktype_id'],
attacktype_txt= org_inc_df.loc[idx,'attacktype_txt'],
# targtype_id= org_inc_df.loc[idx,'targtype_id'],
targtype_txt= org_inc_df.loc[idx,'targtype_txt'],
gname= org_inc_df.loc[idx,'gname'],
# weaptype_id= org_inc_df.loc[idx,'weaptype_id'],
weaptype_txt= org_inc_df.loc[idx,'weaptype_txt'],
nkill= org_inc_df.loc[idx,'nkill'],
# nwound= org_inc_df.loc[idx,'nwound'],
# property_flg= org_inc_df.loc[idx,'property_flg']
)
# Add these objects to the session
session.add(incident_row)
# Commit the objects to the database
session.commit()
#connn = sqlite3.connect('gtdb.sqlite')
#c = connn.cursor()
#we only added this following portion to attempt to fix sqlite, but don't need it in mysql
#c.executescript('''
# PRAGMA foreign_keys=off;
#
# BEGIN TRANSACTION;
# ALTER TABLE incidents_tbl RENAME TO old_table;
#
# /*create a new table with the same column names and types while
# defining a primary key for the desired column*/
# CREATE TABLE incidents_tbl (incident_id Integer PRIMARY KEY NOT NULL,
# iyear INTEGER,
# icountry_txt TEXT,
# ilatitude REAL,
# ilongitude REAL,
# attacktype_txt TEXT,
# targettype_txt TEXT,
# gname TEXT,
# weaptype_txt TEXT,
# nkill INTEGER);
#
# INSERT INTO incidents_tbl SELECT * FROM old_table;
#
# DROP TABLE old_table;
# COMMIT TRANSACTION;
#
# PRAGMA foreign_keys=on;''')
# c.close()
conn.close()
print ('OK')
# 2nd approach: use pandas .to_sql()
#incidents_df.to_sql(name='incidents_tbl.',
# con=engine, if_exists = 'fail', index=False)
#session.commit()
# I find that the 2nd approach doesn't allow the assignment of a key.
#conn.close() |
from PyPDF2 import PdfFileWriter, PdfFileReader, PdfFileMerger
import time
def mesclarPDF():
documento1 = input("Digite o caminho do arquivo 1: ")
documento2 = input("Digite o caminho do arquivo 2: ")
caminhos = [documento1,documento2]
documentos_unificados = 'C:\\Projetos\\Python\\documentos\\Artigos_Unificados.pdf'
merger = PdfFileMerger(caminhos)
for documentos in caminhos:
merger.append(PdfFileReader(documentos, 'rb'))
merger.write(documentos_unificados)
print("Mesclando os arquivos " + documento1 + " e " + documento2 + "!")
time.sleep(2)
print("Arquivos mesclados!")
#mesclar = mesclarPDF() |
# The task you have to perform is “Your Age In 2090”. This task consists of a total of 10 points to evaluate your performance.
# Problem Statement:-
# Take age or year of birth as an input from the user. Store the input in one variable. Your program should detect whether the entered input is age or year of birth and tell the user when they will turn 100 years old. (5 points).
# Here are a few instructions that you must have to follow:
# Do not use any type of modules like DateTime or date utils. (-5 points)
# Users can optionally provide a year, and your program must tell their age in that particular year. (3points)
# Your code should handle all sort of errors like: (2 points)
# You are not yet born
# You seem to be the oldest person alive
# You can also handle any other errors, if possible!
CurrentYear = 2020
while True:
Age = int(input("\n\nPlease enter your birth of year or your age : "))
if len(str(Age)) == 4 and Age > 1885 :
if Age > CurrentYear:
print("You are not yet born !\n\n")
print("Please try again! \n\n")
continue
elif Age < 1920:
print("OMG ! YOU ARE TOOOOOO OLD AND OLDEST PERSON LIVING !")
elif Age < CurrentYear+1:
temp = Age + 100
print(f"You will turn 100 in {temp}\n\n")
Tellage = int(input("Please enter a year so that we tell your age in that year : "))
if Tellage < Age:
print("Sorry, your are not yet born !")
elif Tellage >= Age:
temp = Tellage - Age
print(f"You will be {temp} years old in {Tellage}")
else:
print("Wrong Input !")
elif Age > 0 and len(str(Age)) < 4:
if Age == 100:
print("You are already 100 ! Congratulations\n\n")
elif Age > 120:
print("You are the oldest man living on Earth !!!\n\n")
elif Age > 100:
print("You are quite old and already crossed 100 !\n\n")
elif Age < 100:
temp = 100 - Age
temp = CurrentYear + temp
print(f"You will turn 100 in {temp}\n\n")
Tellage = int(input("Please enter a year so that we tell your age in that year : "))
temp = CurrentYear - Age
if Tellage < temp:
print("Sorry, your are not yet born !")
elif Tellage >= temp:
temp = Tellage - temp
print(f"You will be {temp} years old in {Tellage}")
else:
print("Wrong Input !")
else :
print("The input provided by you is not valid !")
continue
Input1 = input("\nIf you want to quit program, enter \"quit\" in the field : ")
if Input1 == "quit":
exit()
|
import math
x = float(input("Enter x:"))
y = float(input("Enter y:"))
# координаты прямоугольника
x1 = -1
x2 = 6
y1 = -2
y2 = 1
# центр окружности и радиус
yc = 0
xc = 2
r = 3
#прямая линия y=kx+b
k = 1
b = -2
if(y<k*x+b):
if((x-xc)**2+(y-yc)**2<r**2):
if(x1<x<x2) and (y1<y<y2):
print("Обл.4")
else:
if(y>y2):
print("Обл.5")
else:
print("Обл.6")
else:
if (x1 < x < x2) and (y1 < y < y2):
print("Обл.7")
else:
print("Обл.8")
else:
if ((x - xc) ** 2 + (y - yc) ** 2 < r ** 2):
if (x1 < x < x2) and (y1 < y < y2):
print("Обл.3")
else:
print("Обл.2")
else:
print("Обл.1")
print("Конец") |
#82.题目:计算字符串中子串出现的次数。
str1=input("请输入一个字符串:")
str2=input("请输入一个字符串:")
print(str1.count(str2))
|
#58.在一个长字符串中查找短字符串的位置
str1 = input('请输入第一个字符串:')
str2 = input('请输入第二个字符串:')
print(str1.find(str2))
|
#71.题目:循环输出列表
list1 = [1, 2, 3, 4, 5]
for i in range(len(list1) - 1):
print(list1[i], end=' ')
print(list1[i + 1])
|
a_list=list(input('请输入一行字符:'))
letter=[]
space=[]
number=[]
other=[]
for i in range(len(a_list)):
if ord(a_list[i]) in range (65,91) or ord(a_list[i]) in range(97,123):
letter.append(a_list[i])
elif a_list[i]==' ':
space.append(' ')
elif ord(a_list[i]) in range(48,58):
number.append(a_list[i])
else:
other.append(a_list[i])
print('英文字母个数: %s' %len(letter))
print('空格个数: %s' %len(space))
print('数字个数: %s' %len(number))
print('其他字符个数: %s' %len(other))
|
sum,n=0,1
while n<=100:
sum=sum+n
n=n+1
print("1+2+3+...+100=",sum)
|
def hourglassSum(arr):
# Write your code here
w = len(arr[0])
h = len(arr)
_max = 0
if w<3 or h<3:
print("array dimension is not enough for hourGlass implementation")
else:
rowLoop = w-2
columnLoop = h-2
print(columnLoop)
#columnLoop---------
for c in range(0,columnLoop,1):
print('lajfljdsl')
#rowloop----------
for r in range(0,rowLoop,1):
#matrix columnloop
print('kkkkkkkk')
add=0
for m in range(c,c+3,1):
#matrix rowLoop
print('internal loop')
if m==c+1:
add+=arr[m][r+1]
else:
for n in range(r, r+3,1):
add+=arr[m][n]
if _max <add:
_max = add
print(add)
return _max
#print(add)
matrix = [[1, 1, 1],[0,1,0],[0,0,1]]
hourglassSum(matrix) |
# Definition for binary tree with next pointer.
# class TreeLinkNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
# self.next = None
class Solution:
# @param root, a tree link node
# @return nothing
def connect(self, root):
def dfs(node, father, flag):
if not node:
return
if not father:
node.next = None
if father and flag:
node.next = father.right
if father and not flag:
node.next = father.next.left if father.next else None
dfs(node.left, node, True)
dfs(node.right, node, False)
dfs(root, None, False)
return |
#!/usr/bin/env python3
"""Turning an LED on as long as the switch is pressed"""
import RPi.GPIO as GPIO
OUTPIN = 15
SWITCHPIN = 21
GPIO.setmode(GPIO.BOARD)
GPIO.setup(OUTPIN, GPIO.OUT)
GPIO.setup(SWITCHPIN, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)
status = True
def switch_led_status(channel):
"""detects if the LED is on or off and turns it into the complement"""
print("Rising signal on pin " + str(channel))
global status
status = not status
GPIO.output(OUTPIN, status)
try:
GPIO.add_event_detect(SWITCHPIN, GPIO.RISING,\
callback=switch_led_status, bouncetime=200)
while True:
pass
except KeyboardInterrupt:
print("Programm canceled through KeyInterrupt.")
finally:
print("Cleaning up...")
GPIO.cleanup()
print("Finished script!")
|
from math import sqrt
def distance(x1, y1, x2, y2):
dx = x2 - x1
dy = y2 - y1
return sqrt(dx*dx + dy*dy)
print(distance (0,0, 3,4))
|
#!/usr/bin/env python
"""
Prints word counts for given files.
"""
import sys
if len(sys.argv) < 2:
# No filenames given, print usage info.
print "USAGE: python {0} FILE1 [FILE2] ...".format(sys.argv[0])
print "Prints the number of words per file given."
sys.exit()
for filename in sys.argv[1:]:
try:
file = open(filename, "r")
except IOError:
# On IOError we print a message and continue with the other files.
sys.stderr.write("Could not open {0}!\n".format(filename))
continue
# Iterate through lines and increment counter per word
wordcount = 0
for line in file:
words = line.split()
for _ in words:
wordcount += 1
print "{0}: {1}".format(filename, wordcount)
file.close()
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import matplotlib.pyplot as plt
def heat_equation(t0, t1, dt, n, m, u, f, nu, verbose=False):
"""
Solves heat equation where t0 is start time, t1 is end time,
dt is time step, n is rectangle is rectangle width, m is rectangle height,
u are the initial values (as a n x m list), f is the heat source function
(also a n x m list) and nu is thermal diffusivity. Returns the result as a
n x m list.
Note that this function is destructive and will manipulate the given u
argument.
"""
if verbose:
print "Solving with python heat equation solver."
t = t0
while t < t1:
# Init u_n to zero.
u_n = [([0] * n) for _ in xrange(m)]
for i in xrange(1, m-1):
for j in xrange(1, n-1):
u_n[i][j] = u[i][j] \
+ dt*(nu*u[i-1][j] + nu*u[i][j-1] -
4*nu*u[i][j] + nu*u[i][j+1] +
nu*u[i+1][j] + f[i][j])
u = u_n
t += dt
return u
def heat_equation_plot(t0, t1, dt, n, m, u, f, nu, solver_func=heat_equation,
verbose=False, save_to=None, time=False):
"""
Solves and plots heat equation where t0 is start time, t1 is end time,
dt is time step, n is rectangle is rectangle width, m is rectangle height,
u are the initial values (as a n x m list), f is the heat source function
(also a n x m list), nu is thermal diffusivity, solver_func is the
solver function you want to use, verbose gives verbose output,
save_to is a file handle to save the file to. Returns the solved
heat_equation.
Note that this function is destructive and will manipulate the given u
argument.
"""
if verbose:
print "Entering plotting function"
# Init subplots and create t0 plot.
fig, axes = plt.subplots(nrows=1, ncols=2)
axes[0].imshow(u, plt.get_cmap("gray"))
# Call the given solver function, this lets us plot with other solvers.
u = solver_func(t0, t1, dt, n, m, u, f, nu, verbose)
# Plot t1 plot and colorbar.
im = axes[1].imshow(u, plt.get_cmap("gray"))
plt.colorbar(im, ax=axes.ravel().tolist())
if save_to:
if verbose:
print "Saving figure to {}".format(save_to.name)
plt.savefig(save_to)
plt.show()
# Return u so UI can save.
return u
if __name__ == '__main__':
# Set initial values for a run if we call the file.
t0 = 0
t1 = 1000
dt = 0.1
n = 50
m = 100
u = [([0] * n) for y in xrange(m)]
f = [([1] * n) for y in xrange(m)]
nu = 1.
heat_equation_plot(t0, t1, dt, n, m, u, f, nu)
|
#Getting an input: NOTE this works when getting text fromm the user
# name= input("Enter your name: ")
# print("Hello " + name, "Welcome home for breakfast")
# This is use for getting number from the user
# num= eval(input("Enter a number: "))
# print("Your number square: ", num*num)
# NOTE:The (eval) function converts the text entered by the user into a number.
# OR
# num= float(input("Enter a number: "))
# print("Your number square: ", num*num)
# temp=eval(input("Enter your temperature in celsius: "))
# print("In Fahrenheit, that is ",+9/5*temp+32)
# temp=eval(input("Enter the temperature in celsius: "))
# f_temp= 9/5*temp*32
# print("In Fahrenheit, that is",+ f_temp)
# if f_temp > 212:
# print("That temperature is above the boiling point.")
# else:
# f_temp < 32
# print("That temperature is below the freezing point.")
# *******************
# *******************
# *******************
# *******************
# for i in range(4):
# print("*"*19)
# print(f"""*******************
# * *
# * *
# *******************""")
# *
# **
# ***
# ****
# for i in range(4):#(4,0,-1):
# print("*"*(i+1))
# a= 512
# b= 41.48
# c= 5
# d= 282
# f= a-d/b+c
# print(round(f))
# for i in range(12):
# user= eval(input("Enter a number: "))
# num= user/100
# print("The percentage of your number is",num)
# print("My Gee your've run out of loop, kindly run it again if you want or i will Blast you off!!!!")
# user= eval(input("Please enter your number: "))
# num= user*user
# print("The square of", user,"is",num, sep=" " )
# for i in range(10):
# num = eval(input("Enter a number: "))
# print("The square of your number is", num*num)
# print("You have run out of space, please purchase for new one.")
# for i in range(45,100,3):
# print(i+1, "---TitanRoot")
#Roll a dice hundred times:
# for i in range (100):
# print("Roll the Dice",i+1)
# for i in range(10):
# print("Hello")
'''The program below ask the user for a number
and prints it's square, the ask for
another number and prints its square,etc.
It does this three times and then print that the loop is done'''
# for i in range(3):
# num= eval(input("Enter a number: "))
# print("The square of the number is", num*num)
# print("The loop is now done.")
# print("A")
# print("B")
# for i in range(5):
# print("C")
# for i in range(5):
# print("D")
# print("E")
# for i in range(100,1000,50):
# print(i)
# for i in range(100):
# print(i)
# for wacky_name in range(100):
# print(wacky_name)
# for i in range(100):
# print(i+1,"---Wacky_name")
# for i in range(4):
# print(i+1, "---Greg")
# for i in range(3):
# print(i+1, "---Scott")
#Here is an exampple program that counts down from 5 and then prints a message.
# for i in range(5, 0, -1):
# print(i, end=" ")
# print("Blast off !!!!!!!") #NOTE: The end="" just keeps everything on the same line.
# for i in range (100):
# print(i+1,"GregFabian232")
# print("Yo man you have inserted your name hundred times")
# OR:
#NOTE: Here they will not be numbered according to it's counting; like from 1-100
# for i in range (100):
# print("GregFabian232")
# i=i+1
# print("Yo man you have inserted your name hundred times")
# NOTE: we use the end="" to join two lines of sentence to become one at the terminal
# print("This is to inform all programers in FESTAC:",end=" ")
# print("You will be having a practical exams on 22^nd of July 207
# for i in range(20):
# user = eval(input("Enter a number: "))
# a= user*user
# print("The square of:",user,"=",a,sep=' ')
# print("start again out of prerogative")
# for i in range(8,90,3):
# print(i)
# Write the following program in to be in this form: AAAAAAAAAABBBBBBBCDCDCDCDEFFFFFFG
for i in range(10):
print("A",end=' ')
for i in range(7):
print("B",end=' ')
for i in range(4):
print("CD",end=' ')
print("E",end=' ')
for i in range(6):
print("F",end=' ')
print("G")
''' Write a program that ask a user for their name and how many times
to print it. The program should print out the user's name the specifies
number of times.'''
# for i in range(50):
# user= input("please enter your name: ")
# print(i+1,user,sep='-- ')
# print("You can still enter more in future, just wait for my update coming up on 2/4/2025") |
name_surname_birth_date = input("Podaj swoje imie, nazwisko i date urodzenia: ")
print(f"Twoje dane to: {name_surname_birth_date}")
|
# 题目:输入三个整数x,y,z,请把这三个数由小到大输出
while True:
arr = []
for i in range(1, 4):
item = int(input('请依次输入三个整数'))
arr.append(item)
brr = arr.reverse()
print('排序后的数组', arr, brr)
|
# 题目:打印出所有的"水仙花数",所谓"水仙花数"是指一个三位数,其各位数字立方和等于该数本身
arr = []
def getArr(min, max):
for i in range(min, max):
ge = i % 10
shi = i // 10 % 10
bai = i // 100
if ge**3 + shi**3 + bai**3 == i:
arr.append(i)
return arr
print('水仙花数组', getArr(100, 1000))
|
# 题目:输入一行字符,分别统计出其中英文字母、空格、数字和其它字符的个数
obj = {}
while True:
astr = str(input('输入一串字符串'))
print(astr)
# for i in range(astr):
|
"""Find the smallest integer in the array (7 kyu).
Given an array of integers your solution should find the smallest integer.
For example:
Given [34, 15, 88, 2] your solution will return 2.
Given [34, -345, -1, 100] your solution will return -345.
You can assume, for the purpose of this kata,
that the supplied array will not be empty.
"""
def find_smallest_int(arr):
"""Return the integer with the lowest value in arr."""
return sorted(arr)[0]
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Feb 26 14:10:16 2020
@author: vanessa
"""
# functions for iterators for efficient looping
from itertools import groupby
import numpy as np
import pandas as pd
from scipy.stats import linregress
def aggregate_returns(returns,convert_to):
"""
Aggregates returns by day, week, month or year.
:param returns:
:param convert_to:
"""
def cumulate_returns(x):
"""
:return: the cumulative sum of returns
"""
return np.exp(np.log(1+x).cumsum())[-1] - 1
# print(returns)
# print(type(returns))
# .isocalendar() return a 3-tuple with (year, wk num, wk day).
# dt.isocalendar()[0] returns the year,dt.isocalendar()[1] returns
# the week number, dt.isocalendar()[2] returns the week day.
if convert_to == 'weekly':
return returns.groupby(
[lambda x : x.year,
lambda x : x.month,
lambda x : x.isocalendar()[1]
]).apply(cumulate_returns)
elif convert_to == 'monthly':
return returns.groupby([
lambda x: x.year,
lambda x: x.month]).apply(cumulate_returns)
elif convert_to == 'yearly':
return returns.groupby([
lambda x: x.year]).apply(cumulate_returns)
else:
ValueError('convert_to must be weekly, monthly or yearly')
def create_cagr(equity,periods=252):
"""
Calculates the compound annual rate(CAGR) for the portfolio, by determing
the number of years and then creating a compound annualised rate based on
the total return.
:param equity: Represents the equity curve
:param periods: Daily(252)
:return:
"""
years = len(equity) / float(periods)
return (equity[-1] ** (1.0 / years)) -1.0
def create_sharpe_ratio(returns, periods =252):
"""
Create the sharpe ratio for thr strategy, based on a benchmark of zero(
i.e. no risk-free rate inoformation).
:param returns: Representing period percentage returns
:param periods:
:return:
"""
return np.sqrt(periods) * (np.mean(returns)) / np.std(returns)
#def create_sortino_ratio(returns, periods=252):
# """
# Create the Sortino ratio for the strategy, based on a
# benchmark of zero (i.e. no risk-free rate information).
# Parameters:
# returns - A pandas Series representing period percentage returns.
# periods - Daily (252), Hourly (252*6.5), Minutely(252*6.5*60) etc.
# """
# return np.sqrt(periods) * (np.mean(returns)) / np.std(returns[returns < 0])
def create_drawdowns(returns):
"""
Calculate the maximum peak to through drawdown of the equity curve
as well as the duration of the drawdown. Requires that the pnl_returns is
a pandas Series.
:param returns:
:returns: drawdown, drawdown_max, duration
"""
# Calculate the cumulative returns curve
# and set uo the High Water Mark
idx = returns.index
hwm = np.zeros(len(idx))
#create the high water mark
for t in range(1,len(idx)):
hwm[t] = max(hwm[t-1],returns.ix[t])
#Calculate the drawdown and duration statistics
perf = pd.DataFrame(index=idx)
perf['Drawdown'] = (hwm - returns) / hwm
perf['Drawdown'].ix[0] = 0.0
perf["DurationCheck"] = np.where(perf["Drawdown"] == 0, 0, 1)
duration = max(
sum(1 for i in g if i == 1)
for k, g in groupby(perf["DurationCheck"])
)
return perf["Drawdown"], np.max(perf["Drawdown"]), duration
def rsuqare(x,y):
"""
Return R^2 where a and y are array-like.
"""
slop,interception,r_value,p_value,std_err = linregress(x,y)
return r_value ** 2
|
from Tkinter import Tk, Canvas
import math, time
class Planet():
def __init__(self, x, y, space, color):
self.x = x
self.y = y
self.space = space
self.color = color
self.radius = 5
self.draw()
def draw(self):
self.id = self.space.create_oval(self.x - self.radius,
self.y - self.radius,
self.x + self.radius,
self.y + self.radius,
fill = self.color,
outline = self.color)
def move_to(self, x, y):
self.space.move(self.id, x - self.x, y - self.y)
self.x = x
self.y = y
class Animation():
def __init__(self):
root = Tk()
self.canvas = Canvas(root, height = 500, width = 500)
self.canvas.pack()
self.canvas.create_rectangle(0, 0, 500, 500, fill = "#0D4566", outline = "#0D4566") # space
self.venus = Planet(250, 150, self.canvas, "red")
self.earth = Planet(250, 100, self.canvas, "green")
self.sun = Planet(250, 250, self.canvas, "yellow")
self.start = time.time()
self.ticks = 0
self.done = False
self.timer()
root.mainloop()
def rotate_body(self, body, amount):
theta = math.degrees(amount)
x = body.x - 250
y = body.y - 250
x, y = x * math.cos(theta) - y * math.sin(theta), x * math.sin(theta) + y * math.cos(theta)
x += 250
y += 250
body.move_to(x, y)
self.canvas.update()
def timer(self):
if self.done:
print "Done after %2.2f seconds!" % (time.time() - self.start)
return
self.rotate_body(self.earth, math.pi/36000*13.0)
self.rotate_body(self.venus, math.pi/36000*8.0)
self.ticks += 1
if self.ticks % 2 == 0:
self.canvas.create_line(self.earth.x, self.earth.y, self.venus.x, self.venus.y, fill = "white")
if self.ticks > 1250:
self.done = True
self.canvas.after(5, self.timer)
Animation() |
#Output
# enter the size:4
# 1 1
# 1 2 2 1
# 1 2 3 3 2 1
# 1 2 3 4 4 3 2 1
n=int(input("enter the size:"))
for i in range(1,n+1):
for j in range(1,i+1):
print(j,end=" ")
x=(2*n)-(2*i)
for j in range(x):
print(" ",end=" ")
for j in range(i,0,-1):
print(j,end=" ")
print()
|
def tower_of_brahma(n,A,C,B):
if n == 1:
print("Move disk {0} from rod {1} to rod {2}".format(n,A,C))
return
tower_of_brahma(n-1,A,B,C)
print("Move disk {0} from rod {1} to rod {2}".format(n,A,C))
tower_of_brahma(n-1,B,C,A)
if __name__ == '__main__' :
tower_of_brahma(3,'A','C','B') |
def merge_overlapping(intervals):
merge_list = []
if len(intervals) == 0:
return merge_list
intervals.sort(key = lambda x: x[0])
tenmp_interval = intervals[0]
for interval in intervals:
if interval[0] <= tenmp_interval[1]:
tenmp_interval[1] = max(interval[1],tenmp_interval[1])
else:
merge_list.append(tenmp_interval)
tenmp_interval = interval
merge_list.append(tenmp_interval)
return merge_list
if __name__ == "__main__" :
l = [[1,3],[2,6],[8,10],[15,18]]
print(merge_overlapping(l))
|
An array is a type of data structure that stores elements of the same type in a contiguous block of memory. In an array, , of size , each memory location has some unique index, (where ), that can be referenced as (you may also see it written as ).
Given an array, , of integers, print each element in reverse order as a single line of space-separated integers.
Note: If you've already solved our C++ domain's Arrays Introduction challenge, you may want to skip this.
Input Format
The first line contains an integer, (the number of integers in ).
The second line contains space-separated integers describing .
Constraints
Output Format
2 3 4 1
Print all integers in in reverse order as a single line of space-separated integers.
#!/bin/python3
import math
import os
import random
import re
import sys
# Complete the reverseArray function below.
def reverseArray(a):
n = len(arr)
array = [0] * n
for i in range(0, len(arr)):
array[i] = arr[(n-1) - i]
return array
if __name__ == '__main__':
fptr = open(os.environ['OUTPUT_PATH'], 'w')
arr_count = int(input())
arr = list(map(int, input().rstrip().split()))
res = reverseArray(arr)
fptr.write(' '.join(map(str, res)))
fptr.write('\n')
fptr.close()
|
# -*- coding: utf-8 -*-
from collections import defaultdict
class StatCalculator(object):
def median(self, data):
new_list = sorted(data)
if len(new_list) % 2 > 0:
return new_list[len(new_list) / 2]
elif len(new_list) % 2 == 0:
return (new_list[(len(new_list) / 2)] + new_list[(len(new_list) / 2) - 1]) / 2.0
def is_odd(self, number):
return number % 2 == 0
def is_even(self, number):
return number % 2 != 0
def calc(self, sequence, remove_duplicates=False, remove_odd_numbers=False, remove_even_numbers=False, remove_minmal_and_maximal_numbers=False):
if remove_minmal_and_maximal_numbers:
sequence = sorted(sequence)[1:-1]
if remove_duplicates:
sequence = list(set(sequence))
if remove_odd_numbers:
sequence = [i for i in sequence if self.is_even(i)]
if remove_even_numbers:
sequence = filter(self.is_odd, sequence)
if len(sequence) is 0:
return {
"min": None,
"max": None,
"count": None,
"average": None,
"sum": None,
"median": None,
}
return {
"min":min(sequence),
"max": max(sequence),
"count": len( sequence),
"average": sum(sequence) / float(len(sequence)),
"sum": sum(sequence),
"median": self.median(sequence)
} |
#problem=58
top=100000
primes = [2,3,5,7]
for j in range(8, top):
i = 0
div = primes[i]
while div**2<=j and j%div!=0 and i < len(primes)-1:
i+=1
div=primes[i]
if j%div!=0:
primes.append(j)
#print(primes)
print("primes array has been created")
def isprime(num):
global primes
if num <= primes[len(primes)-1]:
if num in primes:
return True
else:
return False
else:
i=0
div = primes[i]
while div**2<=num:
if num%div==0:
return False
i+=1
div = primes[i]
return True
print(isprime(200011))
x,y,num=1,0,2
pd_cnt=0
ratio=1
size=1
while ratio>0.1:
size+=2
if isprime(size**2-size+1):
pd_cnt+=1
if isprime(size**2-2*size+2):
pd_cnt+=1
if isprime(size**2-3*size+3):
pd_cnt+=1
ratio=float(pd_cnt)/(2*size-1)
print size, ', ', pd_cnt, ', ', ratio
#print size, ' , ', pd_cnt, ' , ', ratio
#print(diag_p) |
import Queue
class Graph:
def __init__(self, directed):
self.graph = {}
self.directed = directed
def add_edge(self, first, second, depth=0):
if first in self.graph and second not in self.graph[first] and second is not None:
self.graph[first].append(second)
elif first not in self.graph:
self.graph[first] = [second] if second is not None else []
depth += 1
if not self.directed:
if depth == 1:
self.add_edge(second, first, depth)
else:
if depth == 1:
self.add_edge(second, None, depth)
@property
def nodes(self):
return sorted(list(self.graph.keys()))
def neighbors(self, node):
return sorted(self.graph[node])
def print(self):
for node in self.nodes:
print("Neighbors of " + node + ":", end=" ")
for neighbor in self.neighbors(node):
print(neighbor, end=" ")
print()
def dfs(self, node, visited=[]):
if node not in visited:
visited.append(node)
for neighbour in self.neighbors(node):
print(visited)
self.dfs(neighbour, visited)
def bfs(self, node):
visited = [node]
queue = Queue.Queue()
queue.enqueue(node)
while queue:
node_ = queue.dequeue()
for neighbor in self.neighbors(node_):
if neighbor not in visited:
queue.enqueue(neighbor)
visited.append(neighbor)
print(visited)
# @property
# def adj_matrix(self):
#
graph = Graph(directed=True)
graph.add_edge("A", "B")
graph.add_edge("A", "C")
graph.add_edge("B", "D")
graph.add_edge("B", "E")
graph.add_edge("E", "F")
graph.add_edge("C", "F")
print(graph.graph)
print(graph.nodes)
print(graph.neighbors('A'))
graph.print()
graph.dfs("A")
graph.bfs("A")
|
class MarkovAlgorithm:
class Rule:
def __init__(self, l_part, r_part, terminal=False):
self.l_part = l_part
self.r_part = r_part
self.terminal = terminal
__special_symbol = "*"
def __init__(self, rules):
self.rules = rules
def execute(self, word):
word = " " + word
while True:
for rule in self.rules:
if rule.l_part in word:
new_word = word.replace(rule.l_part, rule.r_part, 1)
if word != new_word and not rule.terminal:
print(word + " - > " + new_word)
word = new_word
break
elif word != new_word and rule.terminal:
print(word + " - > " + new_word)
word = new_word
return word
elif word == new_word and rule is self.rules[-1]:
return word
elif rule is self.rules[-1]:
return word
# keep in mind, that " " is an empty symbol
def main():
rules1 = [MarkovAlgorithm.Rule("aa", "a"), MarkovAlgorithm.Rule("bb", "b")]
markov1 = MarkovAlgorithm(rules1)
print(markov1.execute("aabbaaa"))
rules2 = [MarkovAlgorithm.Rule("*a", "b*"), MarkovAlgorithm.Rule("*b", "a*"),
MarkovAlgorithm.Rule("*", " ", terminal=True), MarkovAlgorithm.Rule(" ", "*")]
markov2 = MarkovAlgorithm(rules2)
print(markov2.execute("abaa"))
rules3 = [MarkovAlgorithm.Rule("*a", "a*"), MarkovAlgorithm.Rule("*b", "b*"),
MarkovAlgorithm.Rule("a*", "aa", terminal=True), MarkovAlgorithm.Rule("b*", "bb", terminal=True),
MarkovAlgorithm.Rule("*", " ", terminal=True), MarkovAlgorithm.Rule(" ", "*")]
markov3 = MarkovAlgorithm(rules3)
print(markov3.execute("abba"))
main()
|
from itertools import combinations
def distance(codes):
return min(sum(bit1 != bit2 for bit1, bit2 in zip(code1, code2)) for code1, code2 in combinations(codes, 2))
def detected(hdistance):
return hdistance - 1
def correct(hdistance):
return (hdistance - 1) / 2
codes_array1 = ['11110', '01011', '00000', '10101']
codes_array2 = ['01010', '10100', '00001', '11111']
distance1, distance2 = distance(codes_array1), distance(codes_array2)
print(distance1, distance2)
print(detected(distance1), detected(distance2))
print(correct(distance1), correct(distance2))
|
"""
This functions in this module perform validation to check that their inputs
of the needed types for this project.
"""
def is_vector(to_check):
"""
Checks if the argument is a single-leveled list, meaning that all of its
contents are one of three acceptable types: Int, Float, or String.
Args:
to_check (List): The list to check for vectorhood.
Returns:
Boolean.
Examples:
>>> w = [1.0, 2.0, 3.0]
>>> is_vector(w)
True
>>> x = [1, 2, 3]
>>> is_vector(x)
True
>>> y = ['a', 'b', 'c']
>>> is_vector(y)
True
>>> z = [1, 2, [1, 2]]
>>> is_vector(z)
False
"""
return all((isinstance(i, str) or
isinstance(i, int) or
isinstance(i, float))
for i in to_check)
def is_matrix(to_check):
"""
Checks if the argument is a valid matrix, meaning that each list within
the list is of the same length and and a valid type (Int, Float, String).
Args:
to_check (List): The list of lists to check for matrixhood.
Return:
A tuple where the first element indicates if the argument is a valid
matrix and the second is a (possibly empty) List of Strings containing
the problem messages to raise in the body of the error message.
Examples
>>> w = [ [1, 2, 3], [3, 2, 1] ]
>>> is_matrix(w)
(True, [])
>>> x = [ [1, 2, 3], ['a', 'b', 'c'] ]
>>> is_matrix(x)
(True, [])
>>> y = [ [1, 2, 3], ['a', 'b', 'c'], [1.0, 2.0, 3.0] ]
>>> is_matrix(y)
(True, [])
>>> z = [ [1, 2, 3], [3, 2] ]
>>> is_matrix(z)
(False, ['Each row must have the same number of columns.'])
>>> zz = [ [1, 2, 3], [3, 2, [3, 2]] ]
>>> is_matrix(zz)
(False, ['One of the rows in the matrix is not a valid vector.'])
>>> zzz = [ [1, 2, 3], [3, 2], [4, 5, [5, 4]] ]
>>> is_matrix(zzz) # doctest: +NORMALIZE_WHITESPACE
(False,
['One of the rows in the matrix is not a valid vector.',
'Each row must have the same number of columns.'])
"""
collector = []
if not all(is_vector(i) for i in to_check):
collector.append('One of the rows in the matrix is not ' +
'a valid vector.')
num_cols = len(to_check[0])
if any([len(a) != num_cols for a in to_check]):
collector.append('Each row must have the same number of columns.')
valid_matrix = not bool(collector)
return valid_matrix, collector
|
a=int(input())
b=int(input())
if a<2:
print("Before")
elif a>2:
print("After")
else:
if b<18:
print("Before")
elif b>18:
print("After")
else:
print("Special") |
a=int(input())
if a%2==0:
if (a//2)%2==0:
print(2)
else:
print(1)
else:
print(0) |
while 1:
a,b,c=input().split()
if a=="#":break
if int(b)>17 or int(c)>=80:print(a, "Senior")
else:print(a, "Junior") |
n=int(input())
for _ in range(n):
a,b=map(float,input().split())
c,d=map(float,input().split())
if a/b > c*c*3.14/d:print("Slice of pizza")
else:print("Whole pizza") |
for _ in range(int(input())):
n=int(input())
for i in range(n):
for j in range(n):
print(f"{'#' if i==0 or i==n-1 or j==0 or j==n-1 else 'J'}",end='')
print()
print() |
n=int(input())
r=0.0
l=list(map(float,input().split()))
for i in l:
r+=(i**3)
print(f"{r**(1/3.0):.6f}") |
n=int(input())
res=0
for i in range(n+1):
for j in range(i, n+1):
res+=i+j
print(res) |
n=int(input())
print("Gnomes:")
for i in range(n):
a,b,c=map(int,input().split())
if (a<b and b<c) or (a>b and b>c):print("Ordered")
else:print("Unordered") |
# Uses python3
def calc_fib(n):
if (n <= 1):
return n
#initializing total_last(n-2)th and (n-1)th fibonacci number
total_last=0
total_current=1
#also introducing variable that will tabulate fib_n (nth fib number)
fib_n=0
for i in range(2,n+1):
fib_n=total_last+total_current
total_last=total_current
total_current=fib_n
return fib_n
n=int(input())
print(calc_fib(n))
|
def reachable(graph, node):
reachable_nodes = []
nodes_to_travel = graph[node]
#print(nodes_to_travel)
while nodes_to_travel:
current_node = nodes_to_travel.pop()
#print(current_node)
if current_node not in reachable_nodes:
#print(graph[current_node])
#if graph[current_node] not in nodes_to_travel:
nodes_to_travel.extend(graph[current_node])
#print(nodes_to_travel)
reachable_nodes.append(current_node)
if node not in reachable_nodes:
reachable_nodes.extend(node)
return reachable_nodes
graph = {'a': ['b', 'c'], 'b': ['a', 'c'], 'c': ['b', 'd'], 'd': ['a'], 'e': ['a']}
#print (reachable(graph, 'a'))
#>>> ['a', 'c', 'd', 'b']
#print (reachable(graph, 'd'))
#>>> ['d', 'a', 'c', 'b']
print(reachable(graph, 'e'))
#>>> ['e', 'a', 'c', 'd', 'b']
|
from functools import reduce
values = [1,2,3,4,5, 6, 2, 3,6,7]
def addthem(currentsum, nextelement):
return currentsum + nextelement
complicatedsum = reduce(addthem, values, 0)
def buildset(currentset, nextelement):
currentset.add(nextelement)
return currentset
setfromlist = reduce(buildset, values, set())
print(complicatedsum)
print(setfromlist) |
def bubblesort(dataset):
for i in range(len(dataset)-1,0,-1): #O(n^2) performance due to the nested for loop
for j in range(i):
if dataset[i] > dataset[j+1]:
temp = dataset[j]
dataset[j] = dataset[j+1]
dataset[j+1] = temp
print("current state: ", dataset)
#current state: [20, 8, 19, 6, 23, 56, 41, 49, 87, 53]
#current state: [8, 19, 6, 23, 56, 41, 49, 20, 87, 53]
#current state: [19, 6, 8, 23, 56, 41, 49, 20, 87, 53]
#current state: [6, 8, 23, 19, 41, 56, 49, 20, 87, 53]
#current state: [8, 23, 19, 41, 6, 56, 49, 20, 87, 53]
#current state: [8, 23, 19, 41, 6, 56, 49, 20, 87, 53]
#current state: [23, 19, 8, 41, 6, 56, 49, 20, 87, 53]
#current state: [23, 19, 8, 41, 6, 56, 49, 20, 87, 53]
#current state: [23, 19, 8, 41, 6, 56, 49, 20, 87, 53]
#Result: [23, 19, 8, 41, 6, 56, 49, 20, 87, 53]
def main():
list1 = [6, 20, 8, 19, 56, 23, 87, 41, 49, 53]
list2 = [5, 3, 4, 67, 82, 22, 24, 44, 56]
bubblesort(list1)
bubblesort(list2)
print("Result: ", list1)
print("result for the second list:", list2)
if __name__ == "__main__":
main()
|
# Import Game modules
import pychallenge
import tictactoe
import typing
#Main Menu
print ("""Hello, welcome to our arcade! Which of the following games would you like to play?
1. Python Challenge
2. Text Adventure
3. Guess my Color
4. Tic Tac Toe
5.Exit/Quit
""")
ans=int(input("What would you like to do? "))
if ans==1:
print("\n Python Quiz it is!")
pychallenge.py_challenge()
elif ans==2:
print("\n Text Adventure it is!")
typing.tyingClub()
elif ans==3:
print("\nGuess my Color it is!")
from random import randint
colors = ['red', 'blue', 'yellow', 'purple', 'green', 'orange']
generator = randint(0,len(colors)-1)
guess = input("Please guess a color from the color wheel: ")
while True: #you want to keep guessing until you actually get it
if guess != colors[generator]:
print("Incorrect. Please try again.")
guess = input("Please guess a color: ").strip()
elif guess == colors[generator]:
break
print("Correct! The color is " + colors[generator] + ".")
elif ans==4:
tictactoe.game()
elif ans==5:
print("\n Goodbye!")
elif ans !="":
print("\n Not Valid Choice Try again") |
def fib(n):
a, b = 0, 1
c = a + b
counter = 0
result = []
result.extend((a, b, c))
if n == 0:
return 0
elif n == 1 or n == 2:
return 1
else:
while counter < n: # this here's a *wild* loop
a, b = b, c
c = a + b
counter += 1
result.append(c)
return result[n]
print fib(6)
|
from board import Block, Board
import random
from bfs import BFS
class Generator:
# accumulative probability
P = {
Block.BlockKinds.OBSTACLE: 0.05,
Block.BlockKinds.PURPLE_CAR: 0.40,
Block.BlockKinds.BLUE_CAR: 0.7,
Block.BlockKinds.TRUCK:1.0
}
def __init__(self):
self.board = Board()
def GetAnObject(self, x, y):
num = random.random()
if num < Generator.P[Block.BlockKinds.OBSTACLE]:
return Block(x, y, 1, Block.BlockKinds.OBSTACLE, False);
if num < Generator.P[Block.BlockKinds.PURPLE_CAR]:
return Block(x, y, 2, Block.BlockKinds.PURPLE_CAR, True)
if num < Generator.P[Block.BlockKinds.BLUE_CAR]:
return Block(x, y, 2, Block.BlockKinds.BLUE_CAR, False)
if random.randint(1,10) <= 3:
return Block(x, y, 3, Block.BlockKinds.TRUCK, True)
return Block(x, y, 3, Block.BlockKinds.TRUCK, False)
def Assemble(self):
while True:
self.board.Clear()
# first place the delivery car at the exit
self.board.AddDelivery(4, 2)
num_tries = 0
# filling in object until we think there are enough
while len(self.board._blocks) <= random.randint(9,12):
# pick a position to place the next object
x = random.randint(0, 5)
y = random.randint(0, 5)
obj = self.GetAnObject(x, y)
if (x <= 4 and y == 2 and (obj._kind == Block.BlockKinds.OBSTACLE or
obj._isVertical)):
continue
num_tries += 1
if self.board.IsBlockAddable(obj):
self.board.AddBlock(obj)
minSteps = BFS(self.board, visitAll=False)
if minSteps >= 15:
print "Found a board with %d moves" % minSteps
self.board.PrintData()
self.board.PrintBlocksInfo()
if __name__ == "__main__":
bg = Generator()
bg.Assemble()
print "Done" |
"""
A particular cell phone plan includes 50 minutes of air time and 50 text messages
for $15.00 a month. Each additional minute of air time costs $0.25, while additional
text messages cost $0.15 each. All cell phone bills include an additional charge of
$0.44 to support 911 call centers, and the entire bill (including the 911 charge) is
subject to 5 percent sales tax.
Write a program that reads the number of minutes and text messages used in a
month from the user. Display the base charge, additional minutes charge (if any),
additional text message charge (if any), the 911 fee, tax and total bill amount. Only
display the additional minute and text message charges if the user incurred costs in
these categories. Ensure that all of the charges are displayed using 2 decimal places
"""
base_charge = 15
emergency_support = 0.44
extra_min = 0.25
extra_text = 0.15
def cell_phone_bill(total_minutes, total_texts):
additional_minutes = 0
additional_texts = 0
additional_minutes += (total_minutes - 50) * extra_min
additional_texts += (total_texts - 50) * extra_text
subtotal = base_charge + emergency_support
tax = 0.05 * subtotal
result = f"{'Monthly rate:':25} {base_charge:.2f}\n"\
f"{'Emergency support:':25} {emergency_support:.2f}\n"
if additional_minutes > 0:
subtotal += additional_minutes
result += f"{'Additional minutes:':25} {additional_minutes:.2f}\n"
if additional_texts > 0:
subtotal += additional_texts
result += f"{'Additional texts:':25} {additional_texts:.2f}\n"
total = subtotal * 1 + tax
result += f"{'Tax:':25} {tax:.2f}\n{'Total:':25} {total:.2f}"
return result
|
# -*- coding: utf-8 -*-
"""
Created on Thu Jan 21 17:21:12 2021
@author: Mohamed Amr
"""
import pandas as pd
import math
class DataPreProcessing:
def get_data(path, label_path = "", shuffle = False):
'''
Used to get feature matrix and label vector out of les.
The feature matrix is a numpy array with dimensions (N X D), where N: number
of samples and D: number of features in every sample.
The label vector is a numpy array with dimensions (N X 1), where N: number
of samples.
• Parameters:
1. path: {'string'} The path of the file that contains the features and
labels.
2. label path: {'string'} The path of labels file if label is not included
in first path.
3. shuffe: {'bool'} If True the rows will be rearranged randomly.
• Return: {'tuple'} of 2 items
1. Feature Matrix: {'numpy.array'}
2. Label Vector: {'numpy.array'}
• Limitations
1. You must input label path if there are no labels data in first path.
2. Label column name must be 'Label' and can't be anything else.
'''
df = pd.read_csv(path)
df.columns = df.columns.map(str.lower)
if(label_path != ""):
df_temp = pd.read_csv(label_path)
df_temp.columns = df_temp.columns.map(str.lower)
df['label'] = df_temp['label']
if(shuffle):
df = df.sample(frac = 1)
X = df.loc[:, df.columns != 'label'].to_numpy()
label = df['label'].to_numpy()
return (X, label)
def normalize(matrix):
'''
Used to normalize input matrix, The returned matrix has the same dimen-
sions as the input.
• Parameters
1. matrix: {'numpy.array'} Unormalized matrix.
• Return: {'numpy.array'} normalized matrix.
'''
mean = matrix.mean()
variance = matrix.var()
return (matrix - mean)/math.sqrt(variance+0.0000001)
def split_data(X, label):
'''
Used to split data into training data set with it's training labels and test
data set with it's test labels.
The data is split with splitting ratio 75% training data and 25% testing data.
• Parameters
1. X: {'numpy.array'} The feature matrix.
2. label: {'numpy.array'} The labels vector.
• Return: f'tuple'g of 4 items
1. Training Feature Matrix: {'numpy.array'}
2. Test Feature Matrix: {'numpy.array'}
3. Training Label vector: {'numpy.array'}
4. Test Label Vector: {'numpy.array'}
'''
ratio = int(len(label)*0.75)
X_train = X[:ratio]
X_test = X[ratio:]
label_train = label[:ratio]
label_test = label[ratio:]
return (X_train, X_test, label_train, label_test)
################################################################################
#test cases:
#-----------
#data = DataPreProcessing()
#X = data.get_X('C:/Users/Mohamed Amr/Documents/Computer & Systems Engineering/4th CSE/First Term/Neural Networks/digit-recognizer/train.csv')
#label = data.get_label('C:/Users/Mohamed Amr/Documents/Computer & Systems Engineering/4th CSE/First Term/Neural Networks/digit-recognizer/train.csv')
# X, label = DataPreProcessing.get_data("C:/Users/Mohamed Amr/Documents/Computer & Systems Engineering/4th CSE/First Term/Neural Networks/digit-recognizer/train.csv", shuffle = True)
# X_train, X_test, label_train, label_test = DataPreProcessing.split_data(X, label)
# print("X_train: {}, Label_train: {}, X_test: {}, Label_test: {}".format(X_train.shape, X_test.shape, label_train.shape, label_test.shape))
# print(DataPreProcessing.normalize(X))
|
from types import MethodType
class Student(object):
# 控制对象可以添加的属性。在__sorts__ 不存在的属性不允许添加
slots__ = ("name", "age", "score")
pass
@property
def score(self):
return self._score
@score.setter
def score(self, value):
if not isinstance(value, (int, float)):
raise ValueError('score must be an integer!')
if value < 0 or value > 100:
raise ValueError('score must between 0 ~ 100!')
else:
self._score = value
def set_age(self, age):
self.age = age
if __name__ == '__main__':
# 判断类型
# t = type(123)
# dir 命令是获得对象的所有属性和方法
#print(dir("object"))
#print(type(abs))
s = Student()
# 给实例添加属性
s.set_age = MethodType(set_age, s)
s.set_age(25)
print(s.age)
s.score = 100
print(s.score)
|
#Напишите программу, которая считывает целое число и выводит текст, аналогичный приведенному в примере (пробелы важны!).
number = int(input())
print('The next number for the number',number, 'is', number+1)
print('The previous number for the number',number, 'is', number-1) |
def bouncingBall(h, bounce, window):
counter = 0
if h <= window or bounce <= 0 or bounce >= 1 or h < 0 or window < 0:
return -1
else:
while h > window:
if h * bounce > window: #ball passes up and down
h = h * bounce
counter = counter + 2
else: #ball just passes down
h = h * bounce
counter = counter + 1
return counter
|
#!/usr/bin/env python3
import random
FIRST_MONEY = 10_000
BET = 1000
# ユーザーの辞書型を作る
def create_user(user_name):
return {'money': FIRST_MONEY, 'name': user_name}
# userのお金を見てゲームが終わってるかを見る
def is_finish_game(users):
for user in users:
if user['money'] <= 0:
print("{}さんは破産しました".format(user['name']))
return True
return False
def get_card():
return random.randint(1, 12)
# 2人しかいない想定
# 返り値: -1 引き分け, 0か1, 勝った人のindex
def battle(cards):
if cards[0] == cards[1]: # 同じ数だったら引き分け
return -1
for i in range(len(cards)): # 1を引いてたら引いた人が勝ち
if cards[i] == 1:
return i
if cards[0] > cards[1]: # 数が大きい人が勝ち
return 0
return 1
# ユーザーのお金を更新する
# win_user_indexで指定されているuserは勝ったuser
def money_upgrade(users, win_user_index):
for i in range(len(users)):
if i == win_user_index: # バトルに勝った人だったらお金を増やす
users[i]['money'] += BET
continue
users[i]['money'] -= BET # 負けた人ならお金を減らす
def main():
users = []
for user_name in ['あなた', 'ディーラー']:
users.append(create_user(user_name))
turn = 0
while 1:
turn += 1
cards = []
print('{}ターン目 あなたの総資産 {}'.format(turn, users[0]['money']))
for user in users:
card = get_card()
print('{}のカードは{}です'.format(user['name'], card))
cards.append(card)
win_user = battle(cards)
if win_user < 0: # -1で来ていた場合は引き分け
print('引き分け\n')
continue
print('{}のかち\n'.format(users[win_user]['name']))
money_upgrade(users, win_user)
if is_finish_game(users):
print('ゲーム終了')
break
if __name__ == "__main__":
main()
|
# -*- coding: utf-8 -*-
'''
第 06 题
author: Honglei1990
url:http://www.pythonchallenge.com/pc/def/channel.html
有一个按钮提示 Paypal 捐赠。图片一个裤子的图标
查看源代码提示 作者希望对 pythonchallenage 做出一些捐赠,想象一下作为解密游戏,是不是有其他玄机。 channel 管道。
源代码最上端显示 - zip -- 是不是跟这个模块有关呢
事实证明捐赠的和本关游戏毫无关系
zip指向 html
<html> <!-- <-- zip -->
把channel 替换zip 登陆网页 提示 yes, find the zip.找到了它
然后尝试把html替换成zip,直接下载了一个zip解压包
利用zipfile模块解压缩zip读取文件,在最下边有一个 readme.text
readme提示
welcome to my zipped list.
hint1: start from 90052
hint2: answer is inside the zip
从文件90052开始,答案就在zip里面
import zipfile
import re
num = '90052'
z_file = zipfile.ZipFile('channel.zip')
def go_next(zfile, num):
#循环读取zip里面的txt文件,取出文件名 递归调用,自己调用自己
filename = num+'.txt'
print(zfile.getinfo(filename).comment,)
text1 = zfile.read(filename).decode('utf-8')
num = ''.join(re.findall('Next nothing is (\d+)', text1))
if num:
go_next(zfile, num)
go_next(z_file, num)
#打印到最后提示收集注释 collect the comments 换另外一个方法 方便打印注释 collect
'''
import zipfile
import chardet
import re
z_file = zipfile.ZipFile('channel.zip')
print(chardet.detect(z_file.read('readme.txt')))
#输出文件后,前边带一个b,编码格式为ascii
#需要decode 转码为utf-8
#设置初始文件头文件名和存储注释的comments
num = '90052'
comments = ''
while num:
filename = num+'.txt'
text1 = z_file.read(filename).decode('utf-8')
comments += (z_file.getinfo(filename).comment).decode('utf-8')
# print(text1)
num = ''.join(re.findall("Next nothing is (\d+)", text1))
print(comments)
#结果为 HOCKEY.html 但进入后 网页提示 it's in the air. look at the letters.
#它在空气中。看字母,返回结果查看 看字母的话原来是 oxygen(氧气)
#重新使用 oxygen.html 后进入 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Dec 4 10:20:25 2018
@author: madeline
"""
import pandas as pd
import numpy as np
import plotly
plotly.tools.set_credentials_file(username='madelinelee', api_key='FW2B67yKVADiMx2Ahz5G')
import plotly.plotly as py
from plotly import tools
import plotly.graph_objs as go
from plotly.tools import FigureFactory as FF
from scipy import stats
from statistics import mean
merged_data = pd.read_csv('merged_data.csv')
#function to create boxplots of average humidity from 2013-2017 by team
def create_humidity_box_by_team():
data_list = []
#get list of teams
team_list = merged_data['team'].unique().tolist()
#create subsets and calculate average year humidity, add to list, create boxplot
#append boxplot to data list
for item in team_list:
y1 = []
team_subset = merged_data[merged_data['team'] == item]
year_list = team_subset['year_id'].unique().tolist()
for year in year_list:
year_team_data = team_subset[team_subset['year_id'] == year]
game_date_data = year_team_data.drop_duplicates('game_date', inplace = False)
#print(game_date_data)
year_humidity = game_date_data['kickoff_humidity_x'].tolist()
#print(year_humidity)
avg_year_humidity = mean(year_humidity)
#print(avg_year_humidity)
y1.append(avg_year_humidity)
trace = go.Box(
y=y1,
name = item,
)
data_list.append(trace)
layout = go.Layout(
title = "Average Yearly Humidity Per Team"
)
fig = go.Figure(data=data_list,layout=layout)
py.iplot(fig, filename = 'Average Yearly Humidity Per Team')
#function to create set of subplots that measure pass yards and rush yards vs visibility
def create_visibility_pass_yds_rush_yds():
qb_data = merged_data[merged_data['position'] == 'QB']
rb_data = merged_data[merged_data['position'] == 'RB']
qb_trace = go.Scatter(
x = qb_data['kickoff_visibility_x'].tolist(),
y = qb_data['pass_yds'].tolist(),
mode = 'markers'
)
rb_trace = go.Scatter(
x = rb_data['kickoff_visibility_x'].tolist(),
y = rb_data['rush_yds'].tolist(),
mode = 'markers'
)
fig = tools.make_subplots(rows=1, cols=2)
fig.append_trace(qb_trace, 1, 1)
fig.append_trace(rb_trace, 1, 2)
fig['layout']['xaxis1'].update(title='kickoff visibility', range=[0,65])
fig['layout']['xaxis2'].update(title='kickoff visibility', range=[0,65])
fig['layout']['yaxis1'].update(title='pass yards', range=[0, 600])
fig['layout']['yaxis2'].update(title='rushing yards', range=[0, 600])
fig['layout'].update(height=700, width=1000, title='qb vs rb visibility')
py.iplot(fig, filename='qb_vs_rb_visibility')
#function to create subplot of qb vs wr humidity,
#pass yards and receiving yards vs humidity
def create_humidity_wr_graphs():
#data_list = []
wr_data = merged_data[merged_data['position'] == 'WR']
qb_data = merged_data[merged_data['position'] == 'QB']
wr_trace = go.Scatter(
x = wr_data['kickoff_humidity_x'].tolist(),
y = wr_data['rec_yds'].tolist(),
mode = 'markers'
)
qb_trace = go.Scatter(
x = qb_data['kickoff_humidity_x'].tolist(),
y = qb_data['pass_yds'].tolist(),
mode = 'markers'
)
fig = tools.make_subplots(rows=1, cols=2)
fig.append_trace(qb_trace, 1, 1)
fig.append_trace(wr_trace, 1, 2)
fig['layout']['xaxis1'].update(title='kickoff humidity', range=[0,100])
fig['layout']['xaxis2'].update(title='kickoff humidity', range=[0,100])
fig['layout']['yaxis1'].update(title='pass yards', range=[0, 600])
fig['layout']['yaxis2'].update(title='receiving yards', range=[0, 600])
fig['layout'].update(height=600, width=800, title='qb vs wr humidity')
py.iplot(fig, filename='qb_vs_wr_humidity')
#layered plot with home vs away scoring, function requires team input
def graph_scoring_home_away_by_team(team):
scoring_team_data = merged_data[merged_data['team'] == team]
home_data = scoring_team_data[scoring_team_data['away'] == 0]
away_data = scoring_team_data[scoring_team_data['away'] == 1]
home_date_data = home_data['game_date'].unique().tolist()
away_date_data = away_data['game_date'].unique().tolist()
#print(away_date_data)
home_scoring_y = []
for date in home_date_data:
date_subset = home_data[home_data['game_date'] == date]
#print(date_subset)
scoring_list = date_subset['scoring'].tolist()
total = sum(scoring_list)
home_scoring_y.append(total)
away_scoring_y = []
for date in away_date_data:
date_subset = away_data[away_data['game_date'] == date]
scoring_list = date_subset['scoring'].tolist()
total = sum(scoring_list)
away_scoring_y.append(total)
scoring_team_data['game_date'] = pd.to_datetime(scoring_team_data['game_date'])
scoring_team_data = scoring_team_data.drop_duplicates('game_date', inplace = False)
x_list = scoring_team_data['game_date'].tolist()
x_list.sort()
home_data['game_date'] = pd.to_datetime(home_data['game_date'])
home_data = home_data.drop_duplicates('game_date', inplace = False)
away_data['game_date'] = pd.to_datetime(away_data['game_date'])
away_data = away_data.drop_duplicates('game_date', inplace = False)
home_data_x = home_data['game_date'].tolist()
home_data_x.sort()
away_data_x = away_data['game_date'].tolist()
away_data_x.sort()
home_scoring = go.Scatter(x=home_data_x,
y=home_scoring_y,
name='Home Scoring',
line=dict(color='#33CFA5'))
away_scoring = go.Scatter(x=away_data_x,
y=away_scoring_y,
name='Away Scoring',
line=dict(color='#F06A6A', dash='dash')
)
data = [home_scoring, away_scoring]
updatemenus = list([
dict(type="buttons",
active=-1,
buttons=list([
dict(label = 'Home Scoring',
method = 'update',
args = [{'visible': [True, False]},
{'title': 'Home Scoring vs Date',
'annotations': []}]
),
dict(label = 'Away Scoring',
method = 'update',
args = [{'visible': [False,True]},
{'title': 'Away Scoring vs Date',
'annotations': []}]),
dict(label = 'Both',
method = 'update',
args = [{'visible': [True, True]},
{'title': team + 'Scoring vs Date',
'annotations': []}]),
dict(label = 'Reset',
method = 'update',
args = [{'visible': [True, True]},
{'title': team + 'Scoring vs Date',
'annotations': []}])
]),
)
])
layout = dict(title=team + ' Scoring',
showlegend=False,
xaxis = dict( title = 'Date'),
updatemenus=updatemenus)
fig = dict(data=data, layout=layout)
py.iplot(fig, filename=team+'_scoring')
#graph_scoring_home_away_by_team('PIT')
#graph_scoring_home_away_by_team('ARI')
#graph_scoring_home_away_by_team('KAN')
#graph_scoring_home_away_by_team('MIA')
#graph_scoring_home_away_by_team('SEA')
#create graph to make time series of weather attributes:
#humidity, visibility, pressure measured over time
def graph_weather_attributes(team):
team_data = merged_data[merged_data['team'] == team]
team_data = team_data.drop_duplicates('game_date', inplace = False)
team_data = team_data[team_data['away'] == 0]
#team_data.sort_values(by='game_date')
#print(team_data['game_date'].tolist())
team_data['game_date'] = pd.to_datetime(team_data['game_date'])
team_data.sort_values(by='game_date', ascending=True)
x_list = team_data['game_date'].tolist()
x_list.sort()
#print(x_list)
#print(team_data['game_date'].tolist())
#print(team_data['kickoff_humidity_x'].tolist())
humidity = go.Scatter(x=x_list,
y=team_data['kickoff_humidity_x'].tolist(),
name= 'Humidity (%)',
line=dict(color='#33CFA5')
)
visibility = go.Scatter(x=x_list,
y=team_data['kickoff_visibility_x'].tolist(),
name= 'Visibility (mi)',
line=dict(color='#F06A6A', dash='dash')
)
barometer = go.Scatter(x = x_list,
y = team_data['kickoff_barometer_x'].tolist(),
name = 'Barometer (in)',
line = dict(color='blue', dash='dot')
)
data = [humidity, visibility, barometer]
updatemenus = list([
dict(type="buttons",
active=-1,
buttons=list([
dict(label = 'Humidity',
method = 'update',
args = [{'visible': [True, False, False]},
{'title': team + ' Humidity (%) vs Date',
'annotations': []}]
),
dict(label = 'Visibility',
method = 'update',
args = [{'visible': [False,True, False]},
{'title': team + ' Visibility (mi)vs Date',
'annotations': []}]),
dict(label = 'Pressure',
method = 'update',
args = [{'visible': [False,False, True]},
{'title': team + ' Barometer (in) vs Date',
'annotations': []}]),
dict(label = 'All',
method = 'update',
args = [{'visible': [True, True, True]},
{'title': team + 'Weather Metrics vs Date',
'annotations': []}]),
dict(label = 'Reset',
method = 'update',
args = [{'visible': [True, True, True]},
{'title': team + 'Weather Metrics vs Date',
'annotations': []}])
]),
)
])
layout = dict(title=team + ' Weather Metrics vs Date', showlegend=False,
xaxis=dict(
title = 'Date'
),
yaxis=dict(
title = 'Humidity (%), Visibility(mi), Barometer(in)'
),
updatemenus=updatemenus)
fig = dict(data=data, layout=layout)
py.iplot(fig, filename= team + '_weather_metrics')
#graph_weather_attributes('PIT')
#graph_weather_attributes('ARI')
#graph_weather_attributes('MIA')
#graph_weather_attributes('SEA')
#graph_weather_attributes('KAN')
#create graph to determine how wind speed affects
#pass yards, field goal percentage, rush yards
def wind_spd_vs_other():
drop_null_wind = merged_data.dropna(subset=['kickoff_wind_x'])
drop_null_wind["wind_intensity"], drop_null_wind["wind_direction"] = zip(*drop_null_wind['kickoff_wind_x'].apply(lambda x: x.split("mi")))
wind_speed_list = drop_null_wind['wind_intensity'].unique().tolist()
for i in range(0, len(wind_speed_list)):
wind_speed_list[i] = int(wind_speed_list[i])
wind_speed_list.sort()
#print(wind_speed_list)
pass_yds = []
rec_yds = []
fgp = []
rush_yds = []
for speed in wind_speed_list:
wind_subset = drop_null_wind[drop_null_wind['wind_intensity'] == str(speed)]
qb_data = wind_subset[wind_subset['position'] == 'QB']
pass_yd_temp_avg = mean(qb_data['pass_yds'].tolist())
pass_yds.append(pass_yd_temp_avg)
wr_data = wind_subset[wind_subset['position'] == 'WR']
rec_yd_temp_avg = mean(wr_data['rec_yds'].tolist())
rec_yds.append(rec_yd_temp_avg)
k_data = wind_subset[wind_subset['position'] == 'K']
fgp_temp_avg = mean(k_data['fg_perc'].tolist())
fgp.append(fgp_temp_avg)
rb_data =wind_subset[wind_subset['position'] == 'RB']
rush_yd_temp_avg = mean(rb_data['rush_yds'].tolist())
rush_yds.append(rush_yd_temp_avg)
#print('passyds')
#print(pass_yds)
slope, intercept, r_value, p_value, std_err = stats.linregress(wind_speed_list,rec_yds)
wr_line = slope*wind_speed_list+intercept
qb = go.Scatter(x=wind_speed_list,
y=pass_yds,
name= 'QB Pass Yds',
line=dict(color='#33CFA5')
)
wr = go.Scatter(x=wind_speed_list,
y=rec_yds,
name= 'WR Receiving Yds',
line=dict(color='orange')
)
k = go.Scatter(x=wind_speed_list,
y=fgp,
name= 'K Field Goal Percentage',
line=dict(color='blue')
)
rb = go.Scatter(x=wind_speed_list,
y=rush_yds,
name= 'RB Rushing Yds)',
line=dict(color='#F06A6A')
)
data = [qb, wr, k, rb, wr_line]
#drop_null_wind['wind_intensity'].tolist()
updatemenus = list([
dict(type="buttons",
active=-1,
buttons=list([
dict(label = 'QB',
method = 'update',
args = [{'visible': [True, False, False, False]},
{'title': 'QB Pass Yards (Yards) vs Wind Speed (mi)',
'annotations': []}]
),
dict(label = 'WR',
method = 'update',
args = [{'visible': [False,True, False,False]},
{'title': 'WR Receiving Yards (Yards) vs Wind Speed (mi)',
'annotations': []}]),
dict(label = 'K',
method = 'update',
args = [{'visible': [False, False,True, False]},
{'title': 'K Field Goal Percentage (%) vs Wind Speed (mi)',
'annotations': []}]),
dict(label = 'RB',
method = 'update',
args = [{'visible': [False, False, False, True]},
{'title': 'RB Rush Yards (Yards)',
'annotations': []}]),
dict(label = 'All',
method = 'update',
args = [{'visible': [True, True, True, True]},
{'title': 'Position Metrics vs Wind Speed (mi)',
'annotations': []}]),
dict(label = 'Reset',
method = 'update',
args = [{'visible': [True, True, True, True]},
{'title': 'Position Metrics vs Wind Speed (mi)',
'annotations': []}])
]),
)
])
layout = dict(title='Position Metrics vs Wind Speed (mi)',
showlegend=False,
xaxis=dict(
title = 'Wind Speed (mi)'
),
yaxis=dict(
title = 'Pass Yards (Yds), Receiving Yards (Yds), Rush Yards (Yds), Field Goal Percentage (%)'
),
updatemenus=updatemenus)
fig = dict(data=data, layout=layout)
py.iplot(fig, filename='position_metrics_vs_wind_speed')
#create graph to measure how humidity has an effect on pass yards, rec yards, field goal percentage, rush yards
def humidity_vs_other():
humidity_list = merged_data['kickoff_humidity_x'].unique().tolist()
humidity_list.sort()
#print(wind_speed_list)
pass_yds = []
rec_yds = []
fgp = []
rush_yds = []
for percent in humidity_list:
temp_data = merged_data[merged_data['kickoff_humidity_x'] == percent]
qb_data = temp_data[temp_data['position'] == 'QB']
temp_list = qb_data['pass_yds'].tolist()
if not temp_list:
pass_yd_temp_avg = 0
else:
pass_yd_temp_avg = mean(temp_list)
pass_yds.append(pass_yd_temp_avg)
wr_data = temp_data[temp_data['position'] == 'WR']
temp_list = wr_data['rec_yds'].tolist()
if not temp_list:
rec_yd_temp_avg = 0
else:
rec_yd_temp_avg = mean(wr_data['rec_yds'].tolist())
rec_yds.append(rec_yd_temp_avg)
k_data = temp_data[temp_data['position'] == 'K']
temp_list = k_data['fg_perc'].tolist()
if not temp_list:
fgp_temp_avg = 0
else:
fgp_temp_avg = mean(k_data['fg_perc'].tolist())
fgp.append(fgp_temp_avg)
rb_data =temp_data[temp_data['position'] == 'RB']
temp_list = rb_data['rush_yds'].tolist()
if not temp_list:
rush_yd_temp_avg = 0
else:
rush_yd_temp_avg = mean(rb_data['rush_yds'].tolist())
rush_yds.append(rush_yd_temp_avg)
#print('passyds')
#print(pass_yds)
qb = go.Scatter(x=humidity_list,
y=pass_yds,
name= 'QB Pass Yds',
line=dict(color='#33CFA5')
)
wr = go.Scatter(x=humidity_list,
y=rec_yds,
name= 'WR Receiving Yds',
line=dict(color='orange')
)
k = go.Scatter(x=humidity_list,
y=fgp,
name= 'K Field Goal Percentage',
line=dict(color='blue')
)
rb = go.Scatter(x=humidity_list,
y=rush_yds,
name= 'RB Rushing Yds)',
line=dict(color='#F06A6A')
)
data = [qb, wr, k, rb]
#drop_null_wind['wind_intensity'].tolist()
updatemenus = list([
dict(type="buttons",
active=-1,
buttons=list([
dict(label = 'QB',
method = 'update',
args = [{'visible': [True, False, False, False]},
{'title': 'QB Pass Yards (Yards) vs Humidity (%)',
'annotations': []}]
),
dict(label = 'WR',
method = 'update',
args = [{'visible': [False,True, False,False]},
{'title': 'WR Receiving Yards (Yards) vs Humidity (%)',
'annotations': []}]),
dict(label = 'K',
method = 'update',
args = [{'visible': [False, False,True, False]},
{'title': 'K Field Goal Percentage (%) vs Humidity (%)',
'annotations': []}]),
dict(label = 'RB',
method = 'update',
args = [{'visible': [False, False, False, True]},
{'title': 'RB Rush Yards (Yards)',
'annotations': []}]),
dict(label = 'All',
method = 'update',
args = [{'visible': [True, True, True, True]},
{'title': 'Position Metrics vs Humidity (%)',
'annotations': []}]),
dict(label = 'Reset',
method = 'update',
args = [{'visible': [True, True, True, True]},
{'title': 'Position Metrics vs Humidity (%)',
'annotations': []}])
]),
)
])
layout = dict(title='Position Metrics vs Humidity (%)',
showlegend=False,
xaxis=dict(
title = 'Humidity (%)'
),
yaxis=dict(
title = 'Pass Yards (Yds), Receiving Yards (Yds), Rush Yards (Yds), Field Goal Percentage (%)'
),
updatemenus=updatemenus)
fig = dict(data=data, layout=layout)
py.iplot(fig, filename='position_metrics_vs_humidity')
#create graph to measure how humidity has an effect on receiving yards
#separated by if the game was played in a dome or not
def rec_yds_humidity_dome():
dome_data = merged_data[merged_data['kickoff_dome_x'] == 'Y']
no_dome_data = merged_data[merged_data['kickoff_dome_x'] == 'N']
dome_humidity_list = dome_data['kickoff_humidity_x'].unique().tolist()
#print(dome_humidity_list)
for i in range(0, len(dome_humidity_list)):
dome_humidity_list[i] = dome_humidity_list[i]
dome_humidity_list.sort()
no_dome_humidity_list = no_dome_data['kickoff_humidity_x'].unique().tolist()
#print(no_dome_data)
for i in range(0, len(no_dome_humidity_list)):
no_dome_humidity_list[i] = no_dome_humidity_list[i]
no_dome_humidity_list.sort()
dome_rec_list = []
no_dome_rec_list = []
for i in dome_humidity_list:
humidity_subset = dome_data[dome_data['kickoff_humidity_x'] == i]
humidity_subset = humidity_subset[humidity_subset['position'] == 'WR']
rec_list = humidity_subset['rec_yds'].tolist()
if not rec_list:
dome_humidity_list.remove(i)
else:
avg_rec = mean(rec_list)
dome_rec_list.append(avg_rec)
for i in no_dome_humidity_list:
nd_humidity_subset = no_dome_data[no_dome_data['kickoff_humidity_x'] == i]
nd_humidity_subset = nd_humidity_subset[nd_humidity_subset['position'] == 'WR']
nd_rec_list = nd_humidity_subset['rec_yds'].tolist()
#print(nd_rec_list)
if not nd_rec_list:
no_dome_humidity_list.remove(i)
#print('removed')
else:
#print('found 1 value')
avg_rec = mean(nd_rec_list)
no_dome_rec_list.append(avg_rec)
#print(dome_rec_list)
#print(no_dome_rec_list)
d_rec_yds = go.Scatter(x=dome_humidity_list,
y=dome_rec_list,
name= 'Receiving Yards in Dome',
line=dict(color='blue')
)
nd_rec_yds = go.Scatter(x=no_dome_humidity_list,
y=no_dome_rec_list,
name= 'Receiving Yards Not in Dome',
line=dict(color='#F06A6A', dash = 'dash')
)
data = [d_rec_yds, nd_rec_yds]
updatemenus = list([
dict(type="buttons",
active=-1,
buttons=list([
dict(label = 'Dome',
method = 'update',
args = [{'visible': [True, False]},
{'title': 'Avg Receiving Yards in Dome',
'annotations': []}]
),
dict(label = 'No Dome',
method = 'update',
args = [{'visible': [False,True]},
{'title': 'Avg Receiving Yards Not in Dome',
'annotations': []}]),
dict(label = 'Both Metrics',
method = 'update',
args = [{'visible': [False, False]},
{'title': 'Avg Receiving Yards',
'annotations': []}]),
dict(label = 'Reset',
method = 'update',
args = [{'visible': [True, True]},
{'title': 'Avg Receiving Yards',
'annotations': []}]),
]),
)
])
layout = dict(title='Position Metrics vs Humidity',
showlegend=False,
xaxis=dict(
title = 'Humidity (%)'
),
updatemenus=updatemenus)
fig = dict(data=data, layout=layout)
py.iplot(fig, filename='position_metrics_vs_humidity_dome')
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Jan 6 21:01:18 2021
@author: aswin
"""
import csv
def read_data(filename):
with open(filename,'r') as csvFile:
datareader = csv.reader(csvFile,delimiter=',')
headers = next(datareader)
metadata = []
traindata = []
for name in headers:
metadata.append(name)
for row in datareader:
traindata.append(row)
return (metadata,traindata) |
#http://www.careercup.com/question?id=5747769461440512
#graphics.stanford.edu/~seander/bithacks.html#NextBitPermutation
#!usr/bin/env python
class Solution:
def __init__(self):
pass
def nextHigh(self, x):
_len = 1
while x & (1 << (32 - _len)) == 0:
_len += 1
_len = 32 - _len
one = -1
zero = -1
i = 0
while i <= _len:
if ((x & (1 << i)) != 0):
if one == -1:
one = i
else:
if zero == -1 and one != -1:
zero = i
if one != -1 and zero != -1:
break
i += 1
if one == -1:
print "invalid input"
return
if zero == -1:
x |= (1 << i)
x ^= (1 << _len)
return x
x ^= (1 << one)
x |= (1 << zero)
return x
def nextSmall(self, x):
_len = 1
while x & (1 << (32 - _len)) == 0:
_len += 1
_len = 32 - _len
one = -1
zero = -1
i = 0
while i <= _len:
if ((x & (1 << i)) != 0):
if one == -1:
if i > 0 and (x & (1 << (i - 1)) == 0):
one = i
zero = i - 1
break
#else:
# if zero == -1:
# zero = i
#if one != -1 and zero != -1:
# break
i += 1
if zero == -1 or one == -1:
print "invalid input"
return
x ^= (1 << one)
x |= (1 << zero)
return x
if __name__ == "__main__":
sol = Solution()
print sol.nextHigh(5)
print sol.nextHigh(6)
print sol.nextHigh(9)
print sol.nextHigh(10)
print '-------------------'
print sol.nextSmall(12)
print sol.nextSmall(10)
print sol.nextSmall(6)
|
#http://www.careercup.com/question?id=15542726
#!usr/bin/env python
class Solution:
def __init__(self):
self.matrix = [['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']]
def remote(self, text):
text = text.lower()
ret = ""
x = 0
y = 0
COL = 5
ROW = 6
for it in text:
location = ord(it) - ord('a')
print location
_y = location % COL
_x = location / COL
if _x > x:
i = 0
while i < _x - x:
ret += "D "
i += 1
else:
i = 0
while i < x - _x:
ret += "U "
i += 1
if _y > y:
j = 0
while j < _y - y:
ret += "R "
j += 1
else:
j = 0
while j < y - _y:
ret += "L "
j += 1
ret += "OK "
x = _x
y = _y
return ret
if __name__ == "__main__":
sol = Solution()
print sol.remote('con')
print sol.remote('zebra')
|
def find_cart(list1, list2, n1, n2):
for i in range(0,n1):
for j in range(0,n2):
print("\n"
"\n"
"{",list1[i],", ",list2[j],"}, ",sep="" , end="")
# creating an empty list
list1 = []
list2 = []
# number of elemetns as input
m1 = int(input("Enter number of elements you want your first set to have : "))
query1 = input("If you want to input integers press1\n"
"If you want to input words press 2")
if query1 == "1":
# iterating till the range
for i in range(0, m1):
ele = int(input())
list1.append(ele) # adding the element
print(list1)
n1 = len(list1)
elif query1 == "2":
for i in range(0, m1):
ele = str(input())
list1.append(ele) # adding the element
print(list1)
n1 = len(list1)
else:
print("Wrong input, try again!")
m2 = int(input("enter the number of elements you want your second set to have!"))
query2 = input("If you want to input integers press1\n"
"If you want to input words press 2")
if query2 == "1":
for j in range(0, m2):
ele2 = int(input())
list2.append(ele2)
print(list2)
# arr2 = set(list2)
n2 = len(list2)
elif query2 == "2":
for j in range(0, m2):
ele2 = str(input())
list2.append(ele2)
print(list2)
# arr2 = set(list2)
n2 = len(list2)
else:
print("Wrong input, try again!")
find_cart(list1, list2, n1, n2) |
my_list = [6, 5, 3, 2, 2]
while True:
new_el_int = input('Введите натуральное число для его оценки в нашем рейтинге:\nДля выхода введите "Quit".')
if new_el_int.isdigit() and new_el_int != 'Quit':
new_el_int = int(new_el_int)
i = 0
for el in my_list:
if new_el_int <= el:
i += 1
my_list.insert(i, new_el_int)
print(my_list)
continue
elif new_el_int == 'Quit':
break
else:
# new_el_int != float(new_el_int) or not new_el_int.isdigit():
print('Нужно ввести натуральное число! Попробуйте еще раз!')
continue
|
import numpy as np
import math
def levenshtein(x,y):
'''
Author: Sungjun Han
Description: computes levenshtein distance
x : str
y : str
'''
dp = [[0]*(len(y)+1) for _ in range(len(x)+1)]
for i in range(1, len(x)+1):
for j in range(1,len(y)+1):
if x[i-1] == y[j-1]:
dp[i][j] = min(dp[i-1][j-1], dp[i-1][j]+1, dp[i][j-1]+1)
else:
dp[i][j] = min(dp[i-1][j-1]+1, dp[i-1][j]+1, dp[i][j-1]+1)
return dp[-1][-1]
def distributional(x,y):
'''
Author: Anastasiia
check coocurrence value
'''
dist = 0
try:
dist = x.get(y, 0) / sum(x.values())
except ZeroDivisionError:
dist = 0
return dist
def cosine(x,y):
'''
Author: Anastasiia
cosine tokens' distance
'''
dist = 0
try:
axes = set(x[1].keys())
except KeyError: #for handling OOV words
return 0
except IndexError: #for handling OOV words
return 0
try:
axes = axes.intersection(set(y[1].keys()))
except KeyError: #for handling OOV words
return 0
except IndexError: #for handling OOV words
return 0
for axis in axes:
x_ = x[1].get(axis, 0)
y_ = y[1].get(axis, 0)
dist += x_ * y_
dist = dist / (x[0] * y[0])
return dist
def euclidian(x,y):
'''
Author: Anastasiia
euclidian tokens' distance
'''
dist = 0
axes = set(x.keys())
axes = axes.union(set(y.keys()))
for axis in axes:
x_ = x.get(axis, 0)
y_ = y.get(axis, 0)
dist += (x_ - y_)**2
dist = math.sqrt(dist)
return dist
if __name__ == '__main__':
x = 'chad'
y = 'to'
print(levenshtein(x,y)) |
#my first programme in python3
def is_proper(sudoku):
"""
This function checks if all numbers in each row, column and subsquare are unique.
"""
return rows_proper(sudoku) and columns_proper(sudoku) and square_proper(sudoku)
def rows_proper(sudoku):
for row in sudoku:
for i, element in enumerate(row): # for each element with index i in a row
if not element: # if element = 0 do not compare with other elements
continue
for next_el in row[i+1:]: # for next element to the end of a row
if element == next_el:
return False
return True
def rows_proper2(sudoku):
nrows = len(sudoku)
ncols = len(sudoku[0])
for row_id in range(nrows):
for col_id in range(ncols):
element = sudoku[row_id][col_id]
if not element:
continue
for j in range(col_id + 1, ncols):
next_el = sudoku[row_id][j]
if element == next_el:
return False
return True
def columns_proper(sudoku):
nrows = len(sudoku) # number of rows (elements of sudoku)
ncols = len(sudoku[0]) # numner of columns = number of elements in first row in sudoku
for col_id in range(ncols):
for i in range(nrows):
element = sudoku[i][col_id]
if not element:
continue
for j in range(i+1, nrows): #
next_el = sudoku[j][col_id] #
if element == next_el:
return False
return True
def square_proper(sudoku): # asumption - dim 9x9
for sqrow in range(3): # "duży" wiersz (składa się z 3 zwykłych wierszy sudoku)
for sqcol in range(3): # "duża" kolumna (z 3 kolumn sudoku)
for row_id in range(3): # mały wiersz w dużym wierszu
for col_id in range(3): # mała kolumna w dużej kolumnie
i = sqrow*3 + row_id # wiersz sudoku zapisany z użyciem dużego i małego wiersza
j = sqcol*3 + col_id # analogicznie
element = sudoku[i][j] # współrzędne elementu
# współrzędne następnego elementu next_el, z którym porównuję element
for nrow_id in range(3):
for ncol_id in range(3):
m = sqrow*3 + nrow_id
n = sqcol*3 + ncol_id
next_el = sudoku[m][n]
if m==i and n==j:
continue
if not element:
continue
if element == next_el:
return False
return True |
from collections import deque, defaultdict
def dfs_topo(i, stack):
explored.append(i)
for edge in graph[i]:
if edge not in explored:
dfs_topo(edge, stack)
stack.insert(0, i)
def Toposrt():
stack = []
for i in range(1, len(graph) + 1):
if i not in explored:
dfs_topo(i, stack)
return stack
def dfs(vertex):
stack = deque(vertex)
while stack:
ver = stack.pop()
if ver not in explored:
explored.append(ver)
for edge in graph[ver]:
stack.append(edge)
num_nodes = int(input())
graph = defaultdict(list)
explored = []
explored1 = []
ln_scc = []
with open("graph.txt") as file:
for line in file:
if line != "\n":
items = line.split()
graph[int(items[0])] += [int(items[1])]
print(Toposrt())
|
from collections import deque
def bfs(graph, vertex):
queue = deque()
queue.append(vertex)
explored = {vertex: True}
level = {vertex: 0}
while queue:
temp = queue.popleft()
for edge in graph[temp]:
if edge not in explored:
level[edge] = level[temp]+1
explored[edge] = True
queue.append(edge)
def main():
graph = {}
print("Enter the vertices")
for i in range(n):
vertex = tuple(map(int, input().split()))
graph[vertex] = []
print("Enter the edges")
for i in range(m):
v1 = tuple(map(int, input().split()))
v2 = tuple(map(int, input().split()))
graph[v1].append(v2)
graph[v2].append(v1)
vertex = tuple(map(int, input().split()))
print(graph)
bfs(graph, vertex)
if __name__ == '__main__':
n, m = map(int, input().split())
INF = 2*n
main()
|
def long_repeat(line: str) -> int:
"""
length the longest substring that consists of the same char
"""
max_count, count = 0, 0
letter = ''
for symbol in line:
if symbol == letter:
count += 1
if count > max_count: max_count = count
elif symbol != letter:
count = 1
letter = symbol
return max_count
if __name__ == '__main__':
# These "asserts" using only for self-checking and not necessary for auto-testing
assert long_repeat('sdsffffse') == 4
assert long_repeat('ddvvrwwwrggg') == 3
assert long_repeat('abababaab') == 2
assert long_repeat('') == 0
print('"Run" is good. How is "Check"?')
|
def frequency_sort(items):
dct = dict()
recorded_items, ans = [], []
for element in items:
if element in recorded_items:
continue
recorded_items.append(element)
count_element = items.count(element)
if count_element in dct:
dct[count_element] += [element]
else:
dct[items.count(element)] = [element]
for frequency in sorted(dct.keys(), reverse=True):
for element in dct[frequency]:
ans.extend([element] * frequency)
return ans
if __name__ == '__main__':
print("Example:")
print(frequency_sort([4, 6, 2, 2, 6, 4, 4, 4]))
# These "asserts" are used for self-checking and not for an auto-testing
assert list(frequency_sort([4, 6, 2, 2, 6, 4, 4, 4])) == [
4, 4, 4, 4, 6, 6, 2, 2]
assert list(frequency_sort(['bob', 'bob', 'carl', 'alex', 'bob'])) == [
'bob', 'bob', 'bob', 'carl', 'alex']
assert list(frequency_sort([17, 99, 42])) == [17, 99, 42]
assert list(frequency_sort([])) == []
assert list(frequency_sort([1])) == [1]
print("Coding complete? Click 'Check' to earn cool rewards!")
|
# Щедрый покупатель
# Добавляет к счету чаевые в расчете 15 и 20 % от суммы
# Дополнена возможностью выбора процента
obed = float(input('Введите сумму за обед'))
n = float(input('Сколько желаете оставить(в %)?'))
chai_15 = obed * 1.15
chai_20 = obed * 1.20
chai_n = obed * (1+ n / 100)
print('Сумма к оплате при 15%', chai_15, ', 20%', chai_20, 'Ваш %', chai_n)
input('\n Нажмите Enter для выхода')
|
'''Напишите программу, на вход которой подается одна строка с целыми
числами. Программа должна вывести сумму этих чисел.
Используйте метод split строки.
'''
s = 0
numbers = [int(i) for i in input().split()]
for number in numbers:
s += number
print(s)
|
'''
Напишите программу, на вход которой подаётся список чисел одной строкой.
Программа должна для каждого элемента этого списка вывести сумму двух
его соседей. Для элементов списка, являющихся крайними, одним из
соседей считается элемент, находящий на противоположном конце этого
списка. Например, если на вход подаётся список "1 3 5 6 10", то на выход
ожидается список "13 6 9 15 7" (без кавычек).
Если на вход пришло только одно число, надо вывести его же.
Вывод должен содержать одну строку с числами нового списка,
разделёнными пробелом.
'''
numbers = [int(j) for j in input().split()]
length = len(numbers)
rez = []
for i in range(length - 1):
rez.append(numbers[i - 1] + numbers[i + 1])
rez.append(numbers[0] + numbers[length - 2])
if len(rez) == 1:
rez[0] = int(rez[0] / 2)
for i in rez:
print(i, end= ' ')
|
# Урок 5 задание 1
# Создайте программу, которая выводит список слов в случайном порядке.
# На экране должны печаться без повторения все слова из представленного списка
words = ['Создайте', 'программу', 'которая', 'выводит', 'список', 'слов',
'в', 'случайном', 'порядке']
import random
while words:
word = random.randrange(len(words))
print(words[word])
del words[word]
input()
|
'''Напишите программу, на вход которой подаётся список чисел одной строкой. Программа должна для каждого элемента этого списка вывести сумму двух его соседей. Для элементов списка, являющихся крайними, одним из соседей считается элемент, находящий на противоположном конце этого списка. Например, если на вход подаётся список "1 3 5 6 10", то на выход ожидается список "13 6 9 15 7" (без кавычек).
Если на вход пришло только одно число, надо вывести его же.
Вывод должен содержать одну строку с числами нового списка, разделёнными пробелом.
'''
a = [int(i) for i in input().split()]
if len(a) > 1:
for i in range(len(a)):
# Важно помнить, что питон нумероет эдементы массива и с конца,
# причем отрицательно
print(a[i - 1]+a[i + 1 - len(a)])
else:
print(a[0])
|
def count_consecutive_summers(num):
s, count = 0, 0
i, first_num = 0, 0
while i <= num:
if s == num:
count += 1
s -= first_num
first_num += 1
elif s < num:
s += i
i += 1
elif s > num:
s -= first_num
first_num += 1
return count
print(count_consecutive_summers(42)) |
# Урок 4 задача 2
# Печатаем текст наоборот
#
#
word = input('Введите слово и получите его наоборот ')
new_word = ''
while word:
length = len(word) - 1
new_word += word[length : ]
word = word [:length]
print(new_word.capitalize())
input('\nНажмите Enter для выхода')
|
def checkio(text: str) -> str:
dct = {}
for symbol in text.lower():
if symbol < 'a' or symbol > 'z':
continue
if symbol in dct.keys():
dct[symbol] += 1
else:
dct[symbol] = 1
popular_symbol = sorted(dct.keys())[0]
for key in sorted(dct.keys()):
if dct[key] > dct[popular_symbol]:
popular_symbol = key
return popular_symbol
if __name__ == '__main__':
print("Example:")
print(checkio("Hello World!"))
# These "asserts" using only for self-checking and not necessary for auto-testing
assert checkio("Hello World!") == "l", "Hello test"
assert checkio("How do you do?") == "o", "O is most wanted"
assert checkio("One") == "e", "All letter only once."
assert checkio("Oops!") == "o", "Don't forget about lower case."
assert checkio("AAaooo!!!!") == "a", "Only letters."
assert checkio("abe") == "a", "The First."
print("Start the long test")
assert checkio("a" * 9000 + "b" * 1000) == "a", "Long."
print("The local tests are done.")
|
#Biggie Size - Given a list, write a function that changes all positive numbers in the list to "big". Example: biggie_size([-1, 3, 5, -5]) returns that same list, but whose values are now [-1, "big", "big", -5]
print("---Biggie Size---")
# def biggie_size(a_list):
# for val in a_list:
# if(int(val) > -1):
# val = "big"
# return a_list
def biggie_size(a_list):
for x in range(len(a_list)):
if(a_list[x] > -1):
a_list[x] = "big"
return a_list
x = [-1, 3, 5, -5]
y = biggie_size(x)
print(y)
#Count Positives - Given a list of numbers, create a function to replace the last value with the number of positive values. (Note that zero is not considered to be a positive number). Example: count_positives([-1,1,1,1]) changes the original list to [-1,1,1,3] and returns it Example: count_positives([1,6,-4,-2,-7,-2]) changes the list to [1,6,-4,-2,-7,2] and returns it
print("\n\n---Count Positives---")
def count_positives(a_list):
count = 0
for x in range(len(a_list)):
if(a_list[x] > 0):
count += 1
a_list[x] = count
return a_list
x = [-1,1,1,1]
y = count_positives(x)
print(y)
#Sum Total - Create a function that takes a list and returns the sum of all the values in the array. Example: sum_total([1,2,3,4]) should return 10 Example: sum_total([6,3,-2]) should return 7
print("\n\n---Sum Total---")
def sum_total(a_list):
sum = 0
for val in a_list:
sum += val
return sum
x = [1,2,3,4]
y = sum_total(x)
print(y)
#Average - Create a function that takes a list and returns the average of all the values. Example: average([1,2,3,4]) should return 2.5
print("\n\n---Average---")
def average(a_list):
sum = 0
for val in a_list:
sum += val
return sum / len(a_list)
x = [1,2,3,4]
y = average(x)
print(y)
#Length - Create a function that takes a list and returns the length of the list. Example: length([37,2,1,-9]) should return 4 Example: length([]) should return 0
print("\n\n---Length---")
def length(a_list):
return len(a_list)
# x = [37,2,1,-9]
x = []
y = length(x)
print(y)
#Minimum - Create a function that takes a list of numbers and returns the minimum value in the list. If the list is empty, have the function return False. Example: minimum([37,2,1,-9]) should return -9 Example: minimum([]) should return False
print("\n\n---Minimum---")
def minimum(a_list):
if(len(a_list) == 0):
return False
min = a_list[0]
for val in a_list:
if(val < min):
min = val
return min
x = [37,2,1,-9, 24]
# x = []
y = minimum(x)
print(y)
#Maximum - Create a function that takes a list and returns the maximum value in the array. If the list is empty, have the function return False. Example: maximum([37,2,1,-9]) should return 37 Example: maximum([]) should return False
print("\n\n---Maximum")
def maximum(a_list):
if(len(a_list) == 0):
return False
max = a_list[0]
for val in a_list:
if(val > max):
max = val
return max
x = [37,2,1,-9]
# x = []
y = maximum(x)
print(y)
#Ultimate Analysis - Create a function that takes a list and returns a dictionary that has the sumTotal, average, minimum, maximum and length of the list. Example: ultimate_analysis([37,2,1,-9]) should return {'sumTotal': 31, 'average': 7.75, 'minimum': -9, 'maximum': 37, 'length': 4 }
print("\n\n---Ultimate Analysis---")
def ultimate_analysis(a_list):
new_dict ={}
sum = 0
min = a_list[0]
max = a_list[0]
list_len = len(a_list)
for i in range(len(a_list)):
sum += a_list[i]
if(a_list[i] < min):
min = a_list[i]
elif(a_list[i] > max):
max = a_list[i]
avg = sum / list_len
new_dict['sumTotal'] = sum
new_dict['average'] = avg
new_dict['minimum'] = min
new_dict['maximum'] = max
new_dict['length'] = list_len
return new_dict
x = [37,2,1,-9]
y = ultimate_analysis(x)
print(y)
#Reverse List - Create a function that takes a list and return that list with values reversed. Do this without creating a second list. (This challenge is known to appear during basic technical interviews.) Example: reverse_list([37,2,1,-9]) should return [-9,1,2,37]
print("\n\n---Reverse List---")
def reverse_list(a_list):
for i in range(int(len(a_list)/2)):
temp = a_list[i]
a_list[i] = a_list[len(a_list)-1-i]
a_list[len(a_list)-1-i] = temp
return a_list
x = [37,2,1,-9]
y = reverse_list(x)
print(y) |
var = 100
if var == 100:
print "Value of expression is 100"
elif var == 1000:
print "Value of expression is 1000"
else:
print "Value of expression is not 100 or 1000"
print "Good bye!" |
def check_binary(word):
ret = True
for b in word:
if b == '1' or b == '0':
ret = True
else:
return False
return ret
def Xor(a,b):
xor = ''
for i,j in zip(a,b):
if i == j:
xor = xor + '0'
else:
xor = xor + '1'
return xor
def filter_bin(b):
count = 0
for i in b:
if i == '0':
count = count + 1
else:
break
b = "" + b[count:]
#print( 'bin =',b,'count =',count
return b,count
def Crc(msg, g):
rem = ''
crc = ''
count = 0
msg_with_redundant_bits = msg + '0'*(len(g)-1)
a = msg_with_redundant_bits[0:len(g)]
crc = crc + '1'
j = len(g)
while len(crc)<=len(msg):
print( a,'with',g,'gives')
a = Xor(a,g)
print( a,a,count = filter_bin(a))
print('filtered a =',a)
a = a + msg_with_redundant_bits[j:j+count]
j = j + count
crc = crc + '0'*(count-1)
crc = crc + '1'
print( 'crc = ',crc)
print( '********************************************************')
#break
crc = "" + crc[:-1] + a
return crc,a
def main():
msg = input("Enter the binary msg: ")
g = input("Enter the Generator function G(x): ")
#msg,g = '11010011101100','1011'
if check_binary(msg) and check_binary(g):
crc, r = Crc(msg, g)
print( 'Cyclic Encoded MESSAGE =', crc)
print( 'Remainder =',r)
main()
|
"""Provide the user with a programming problem from r/DailyProgrammer and a
language in which the problem should be solved.
"""
import argparse
from itertools import chain
from random import choice
from datetime import datetime
from dailyprogrammer.challenges import get_challenges
from dailyprogrammer.utils import JSONFileManager
def _filter_repeats(challenges, log):
"""Remove the challenges appearing in the challenge log to avoid repeating a challenge.
"""
used_links = [entry['link'] for entry in log]
return [(title, link) for title, link in challenges if link not in used_links]
def _get_valid_challenges(valid_difficulties):
"""Retrieve and filter challenges by difficulty
valid_difficulties - an iterable of strings representing acceptable difficulty levels
"""
challenges = get_challenges()
valid_challenge_items = (challenge_dict.items()
for diff, challenge_dict in challenges.iteritems()
if diff in valid_difficulties)
valid_challenges = list(chain.from_iterable(valid_challenge_items))
return valid_challenges
def do_challenge():
"""Provide a random challenge from r/DailyProgrammer to the user along with
a language in which the language should be completed.
"""
config = JSONFileManager('config.json', create=False)
languages = config.obj['languages']
no_repeat_challenges = config.obj['no_repeat_challenge']
parser = argparse.ArgumentParser()
parser.add_argument('--difficulty', '-d',
choices=['easy', 'med', 'hard'], default='hard',
dest='difficulty')
args = parser.parse_args()
if args.difficulty == 'easy':
valid_difficulties = ("easy")
elif args.difficulty == 'med':
valid_difficulties = ("easy", "intermediate")
elif args.difficulty == 'hard':
valid_difficulties = ("easy", "intermediate", "hard", "extra")
valid_challenges = _get_valid_challenges(valid_difficulties)
challenge_log = JSONFileManager('.challenge_log.json', default=[])
if no_repeat_challenges:
valid_challenges = _filter_repeats(valid_challenges, challenge_log.obj)
title, link = choice(valid_challenges)
language = choice(languages)
print (" %s " % title).center(120, '=')
print "Using %s, complete the challenge found at:\n\t %s" % (language, link)
# add to challenge log
challenge_log.obj.append({
'title': title,
'link': link,
'time': datetime.now().isoformat()
})
challenge_log.dump()
if __name__ == "__main__":
do_challenge()
|
import tkinter as tk
import tkinter
import pika
class TextExtension( tkinter.Frame ):
"""Extends Frame. Intended as a container for a Text field. Better related data handling
and has Y scrollbar now."""
def __init__( self, master, textvariable = None, *args, **kwargs ):
self.textvariable = textvariable
if ( textvariable is not None ):
if not ( isinstance( textvariable, tkinter.Variable ) ):
raise TypeError( "tkinter.Variable type expected, {} given.".format( type( textvariable ) ) )
self.textvariable.get = self.GetText
self.textvariable.set = self.SetText
# build
self.YScrollbar = None
self.Text = None
super().__init__( master )
self.YScrollbar = tkinter.Scrollbar( self, orient = tkinter.VERTICAL )
self.Text = tkinter.Text( self, yscrollcommand = self.YScrollbar.set, *args, **kwargs )
self.YScrollbar.config( command = self.Text.yview )
self.YScrollbar.pack( side = tkinter.RIGHT, fill = tkinter.Y )
self.Text.pack( side = tkinter.LEFT, fill = tkinter.BOTH, expand = 1 )
def Clear( self ):
self.Text.delete( 1.0, tkinter.END )
def GetText( self ):
text = self.Text.get( 1.0, tkinter.END )
if ( text is not None ):
text = text.strip()
if ( text == "" ):
text = None
return text
def SetText( self, value ):
self.Clear()
if ( value is not None ):
self.Text.insert( tkinter.END, value.strip() )
root = tk.Tk()
#root.geometry("600x700") #You want the size of the app to be 500x500
text = TextExtension(root, font='Arial 10')
text.pack()
code=TextExtension(root,height=1, font='Arial 10',wrap=tk.WORD)
code.pack()
#hscrollbar.pack()
#vscrollbar.pack()
c = '''
#This is sample code for eval on consumer
def add(a,b):
return a+b
'''
text.SetText(c)
code.SetText( ' { "in" : [ 1, 1 ] , "call", "add" , "out", "return" }')
clicks = 0
def click_button():
global clicks, text
clicks += 1
root.title("Clicks {}".format(clicks))
connection = pika.BlockingConnection(pika.ConnectionParameters(host='localhost'))
channel = connection.channel()
c = text.GetText()
channel.exchange_declare(exchange='code',
exchange_type='fanout')
channel.basic_publish(exchange='code',
routing_key='',
body=c
)
#print(c)
channel.close()
def click_button_send():
global clicks, text
clicks += 1
root.title("Clicks {}".format(clicks))
connection = pika.BlockingConnection(pika.ConnectionParameters(host='localhost'))
channel = connection.channel()
c = text.GetText()
channel.basic_publish(exchange='',
routing_key='bss',
body=c
)
#print(c)
channel.close()
btn = tk.Button(text="Send code to all consumers", command=click_button)
btn.pack()
btn_msg = tk.Button(text="Send message", command=click_button_send)
#btn_msg.pack()
root.mainloop()
|
class User:
"""
Class that generates new users.
"""
userList = []
def __init__(self, name, username, password):
self.username = username
self.name = name
self.password = password
def save_user(self):
'''
function that saves User objects into userList
'''
self.userList.append(self)
|
def find_max_min(values):
min = values[0]
for elm in values[1:]:
if elm < min:
min = elm
max = values[0]
for elm in values[1:]:
if elm > max:
max = elm
res = set()
res.add(min)
res.add(max)
return sorted(list(res))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.