text stringlengths 37 1.41M |
|---|
import argparse
import json
parser = argparse.ArgumentParser(description='convert csv file to json file')
parser.add_argument('-i', '--input', metavar='input', help='Specify input csv file name')
parser.add_argument('-o', '--output', metavar='output', help='Specify output json file name')
args, rem = parser.parse_known_args()
tables = {}
with open(args.input) as f:
lines = f.readlines()
for line in lines:
tmp = line.strip('\n').split(',', 3)
if tmp[0]:
if tmp[0] not in tables:
tables[tmp[0]] = {}
if not tmp[3]:
continue
if tmp[2] in ['INTEGER', 'BOOLEAN']:
tables[tmp[0]][tmp[1]] = int(tmp[3])
elif tmp[2] == "REAL":
tables[tmp[0]][tmp[1]] = float(tmp[3])
else:
if tmp[3].count('"') == 2:
try:
tmp[3] = eval(tmp[3])
except:
pass
tables[tmp[0]][tmp[1]] = tmp[3]
with open(args.output, 'w') as fp:
json.dump(tables, fp) |
from random import randint
while True:
palpite = int(input('Digite o palpite du número digitado pelo computador (0 à 5): '))
if palpite < 0 or palpite > 5:
print('\nOpa! Palpite inválido!\nTente novamente!!!', end='\n')
else:
break
n = randint(0, 5)
print('ACERTOU!' if palpite == n else 'ERROU')
|
n = int(input('Entre com o número: '))
print('Tabuada do {}'.format(n),end=' >>> \n\n')
for i in range(1, 11, 1):
print('{:2} X {} = {:3}'.format(i, n, (i*n)))
|
flag = True
num = int(input('\nDigite um número para verificação se é primo ou não: '))
for i in range(2, num):
if num % i == 0:
flag = False
break
print('O número {} '.format(num)+('é primo!' if flag else 'não é primo!'))
|
while True:
op = str(input('Digite o seu sexo: ')).upper()
if op != 'M' and op != 'F':
print('\033[1;31mERRO! Entrada inválida! Tente novamente!\033[m')
else:
break
|
valores = list()
i = 0
naList5 = False
print()
while True:
aux = (int(input(f'Digite o valor {i+1} (Digite 0 para terminar): ')))
if aux == 0:
break
else:
if aux == 5:
naList5 = True
valores.append(aux)
i += 1
valores.sort(reverse=True)
print(f'\nForam digitados {i} valores\nA lista digitada em ordem decrescente >>> ', end='')
for i in range(0, len(valores)):
print(f'{valores[i]} ', end='')
print(f'\nO valor 5 '+ ('foi digitado!' if naList5 else 'não foi digitado!'))
|
from random import randint
sorteios = list()
jogo = list()
n = 0
print()
while True:
n = int(input('Quantos jogos você quer gerar? >>> '))
if n <= 0:
print('\033[1;31mERRO! Entrada inválida! Tente novamente!\033[m')
else:
break
print('\n================================================')
for i in range(0, n):
for j in range(0, 6):
jogo.append(randint(1, 60))
sorteios.append(jogo[:])
jogo.clear()
for i in range(0, n):
print(f'Jogo {i+1}: {sorteios[i]}')
print('================================================')
|
from math import floor
n = float(input('Entre com um número: '))
print('O número {} tem como parte inteira {}'.format(n, floor(n)))
|
n = float(input('Digite quantos R$ tem na carteira: '))
print('Cotação do dolar: US$1.00 = R${:,.2f}\nLogo pode com R${:,.2f} você pode comprar US${:,.2f}'
.format(3.27, n, (n/3.27), 2))
|
n = 0
somaN = 0
keep = 'S'
allN = []
print()
while keep != 'N':
n = int(input('Entre com um número (digite 999 para parar o programa): '))
if n == 999:
allN.sort()
break
somaN += n
allN.append(n)
print(f'\nQuantidade de números digitados: {len(allN)}\nSoma de todos os números digitados: {somaN}')
|
brasileiro = ('Athetico', 'Atlético-MG', 'Avaí', 'Bahia', 'Botafogo', 'Ceará',
'Chapecoense', 'Corinthians', 'Cruzeiro', 'CSA', 'Flamengo',
'Fluminense', 'Fortaleza', 'Goiás', 'Grêmio', 'Internacional',
'Palmeiras', 'Santos', 'São Paulo', 'Vasco')
print(f'\nPrimeiros 5 colocados: {brasileiro[:5]}')
print(f'Últimos 4 colocados: {brasileiro[16:20]}')
print(f'Times em ordem alfabética: {sorted(brasileiro)}')
for i in range(0, len(brasileiro)):
if brasileiro[i] == 'Chapecoense':
print(f'A Chapecoense está ná {i+1}ª posição')
break
|
fibo = [0, 1]
i = 0
while True:
n = int(input('\nDigite quantos termos da série de fibonnaci você deseja (0 para sair): '))
if n < 0:
print('\033[1;31mERRO! Entrada inválida! Tente novamente!\033[m')
else:
if n == 1:
print('Primeiro termo da série Fibonacci: {}'.format(fibo[0]), end='')
break
while i < n:
if i == 0:
print('Primeiros {} termos da série Fibonacci: {}'.format(n, fibo[i]), end='')
elif i == 1:
print(' -> {}'.format(fibo[i]), end='')
else:
fibo.append(fibo[i-2]+fibo[i-1])
print(' -> {}'.format(fibo[len(fibo)-1]), end='')
i += 1
print('.')
break
|
peso = 0
alt = 0
while True:
peso = float(input('Entre com o seu peso: '))
if peso < 0:
print('\033[1;31mERRO! Peso inválido!\033[m')
else:
break
while True:
alt = float(input('Entre com a sua altura: '))
if alt < 0:
print('\033[1;31mERRO! Altura inválida!\033[m')
else:
break
print()
if (peso / (alt**2)) < 18.5:
print('Você está \033[1;31mABAIXO DO PESO\033[m')
elif (peso / (alt**2)) < 25:
print('Você está com \033[1;32mPESO IDEAL\033[m')
elif (peso / (alt**2)) < 30:
print('Você está com \033[1;33mSOBREPESO\033[m')
elif (peso / (alt**2)) < 40:
print('Você está com \033[1;34mOBESIDADE\033[m')
else:
print('Você está com \033[1;35mOBESIDADE MÓRBIDA\033[m')
|
pessoas =[[] for _ in range(3)]
plus18, qtdHomem, woman20minus = 0, 0, 0
aux1, aux2, aux3 = 0, 0, 0
flag = False
while not flag:
aux1 = str(input('\nNome da pessoa >>> '))
while True:
aux2 = int(input('Qual a idade? >>> '))
if aux2 < 0:
print('\033[1;31mERRO! Entrada inválida! Tente novamente!\033[m')
else:
break
while True:
aux3 = str(input('Qual o sexo [M/F]? >>> ')).upper()
if aux3 != 'M' and aux3 != 'F':
print('\033[1;31mERRO! Entrada inválida! Tente novamente!\033[m')
else:
break
pessoas[0].append(aux1)
pessoas[1].append(aux2)
pessoas[2].append(aux3)
if aux2 > 18:
plus18 += 1
if aux3 == 'M':
qtdHomem += 1
elif aux2 < 20:
woman20minus += 1
while True:
op = str(input('\nDeseja cadastrar outra pessoa [S/N]? >>> ')).upper()
if op != 'S' and op != 'N':
print('\033[1;31mERRO! Entrada inválida! Tente novamente!\033[m')
else:
break
if op == 'N':
flag = True
print(f'\nQuantidade de pessoas com mais de 18 anos >>> {plus18}\nQuantidade de homens >>> {qtdHomem}\n'
f'Quantidade de mulheres com menos de 20 anos >>> {woman20minus}')
|
# posteriors
# Compute the likelihood of posteriors
#
# Author: Benjamin Bengfort <benjamin@bengfort.com>
# Created: Tue Sep 09 16:15:32 2014 -0400
#
# Copyright (C) 2014 Bengfort.com
# For license information, see LICENSE.txt
#
# ID: posteriors.py [] benjamin@bengfort.com $
"""
Compute the likelihood of posteriors
"""
##########################################################################
## Imports
##########################################################################
import random
import numpy as np
import matplotlib.pyplot as plt
def random_observations(x=0.68, n=100):
for i in xrange(n):
if random.random() > x:
yield 0
else:
yield 1
def posterior(x, k, n):
"""
Returns the posterior probability for x given k and n
"""
return (x**k)*((1-x)**(n-k))
def graph(observations):
"""
Graphs the refining posterior for our observations
"""
x = np.arange(0.0, 1.0, 0.01)
for i, n in enumerate((1, 5, 10, 25, 50, 100)):
k = sum(observations[:n])
print "k=%i after %i observations" % (k,n)
axe = plt.subplot(2, 3, i+1)
axe.set_title("K=%i, N=%i" % (k,n))
if i > 2: axe.set_xlabel("Value of X")
if i == 0 or i==3: axe.set_ylabel("Probability of Posterior")
#axe.get_yaxis().set_ticks([])
axe.plot(x, posterior(x, k, n))
plt.suptitle("Improving Posterior with more Observations")
plt.show()
if __name__ == '__main__':
observations = list(random_observations())
graph(observations)
|
# python3
import sys
def compute_min_refills(distance, miles, tank, stops):
# write your code here
num_refill, curr_refill, limit = 0, 0, miles
while limit < distance:
if curr_refill >= tank or stops[curr_refill] > limit:
return -1
while curr_refill < tank - 1 and stops[curr_refill + 1] <= limit:
curr_refill += 1
num_refill += 1 # Stop to tank
limit = stops[curr_refill] + miles # Fill up the tank
curr_refill += 1
return num_refill
if __name__ == '__main__':
d = int(input())
m = int(input())
n = int(input())
stops = list(map(int, input().split()))
print(compute_min_refills(d, m, n, stops))
|
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def generateTrees(self, n):
"""
:type n: int
:rtype: List[TreeNode]
"""
if(n == 0):
return []
return self.recursion(1, n)
def recursion(self, start, end):
subTree = []
if(start > end):
subTree.append(None)
return subTree
for i in range(start, end + 1):
left = self.recursion(start, i - 1)
right = self.recursion(i + 1, end)
for l in left:
for r in right:
tmp = TreeNode(i)
tmp.left = l
tmp.right = r
subTree.append(tmp)
return subTree |
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
# use list as a queue
from collections import deque
class Solution:
def zigzagLevelOrder(self, root):
"""
:type root: TreeNode
:rtype: List[List[int]]
"""
res = []
if(root == None):
return res
count = 0
q = deque([])
q.append(root)
while(len(q) != 0):
row = []
size = len(q)
for i in range(size):
tmp = q.popleft()
if(tmp.left != None):
q.append(tmp.left)
if(tmp.right != None):
q.append(tmp.right)
row.append(tmp.val)
if(count % 2 == 1):
row.reverse()
count += 1
res.append(row)
return res
|
from Validations import ValidTypes, ValidDates
from datetime import datetime
class StringOperations:
"""
This class should implement all the methods needed
to process all kind of string operations
"""
@staticmethod
def getLastChar(string_var):
"""
Returns the last element of a string
:param string_var: String
:return: Last character
"""
ValidTypes.validateString(string_var)
return string_var[-1]
@staticmethod
def getDay(date_str):
"""
Get the day of a given date
:param date_str: Date as string
:return: Weekday as integer
"""
ValidTypes.validateString(date_str)
ValidDates.validateDateFormat(date_str)
date = datetime.strptime(date_str, '%d-%m-%Y')
day = date.isoweekday()
return day
|
from datetime import datetime
# My libraries
from Validations import ValidTime, ValidCustom
from Utilities import StringOperations
class PicoPlaca:
"""
This class has all the restrictions operations
required for Pico y Placa
"""
@staticmethod
def __timeRestriction():
"""
Time restriction representation using a
dictionary. M: Morning, A: Afternoon
:return: dictionary of restricted hours
"""
restriction = {"M": ["7:00", "9:30"],
"A": ["16:00", "19:30"]}
return restriction
@staticmethod
def __dayRestriction():
"""
Days restriction representation using a
dictionary. Monday: 1, ..., Sunday:7
:return: dictionary of restricted days
"""
restriction = {1: [1, 2], 2: [3, 4], 3: [5, 6],
4: [7, 8], 5: [9, 10], 6: [],
7: []}
return restriction
@staticmethod
def __getTimeRestriction(time_day):
"""
Return the time restriction in time format
:param time_day: Char parameter M: Morning, A: Afternoon
:return: time interval in which the restriction holds
"""
time_restriction = PicoPlaca.__timeRestriction()
time_ini = time_restriction[time_day][0]
time_fin = time_restriction[time_day][1]
time_ini = datetime.strptime(time_ini, "%H:%M").time()
time_fin = datetime.strptime(time_fin, "%H:%M").time()
return time_ini, time_fin
@staticmethod
def isRestrictionTime(time_str):
"""
This method verifies if the time falls inside the
restriction time established for pico y placa
:param time_str: time parameter as string
:return: True or False
"""
ValidTime.validateTime(time_str)
time = datetime.strptime(time_str, "%H:%M").time()
morning_ini, morning_fin = PicoPlaca.__getTimeRestriction("M")
if morning_ini <= time <= morning_fin:
return True
afternoon_ini, afternoon_fin = PicoPlaca.__getTimeRestriction("A")
if afternoon_ini <= time <= afternoon_fin:
return True
return False
@staticmethod
def isRestrictionDay(date_str, plate):
"""
This method verifies if the plate number is
restricted based on the day
:param date_str: Date as string
:param plate: plate number
:return: True or False
"""
ValidCustom.validatePlate(plate)
day = StringOperations.getDay(date_str)
if day == 6 or day == 7:
return False
else:
last_char = StringOperations.getLastChar(plate)
last_char = int(last_char)
day_restriction = PicoPlaca.__dayRestriction()
plate_restriction = day_restriction[day]
if last_char == plate_restriction[0] or last_char == plate_restriction[1]:
return True
else:
return False
|
def bubble_sort(elements):
elements_copy = elements[:]
n = 1
for i in range(len(elements_copy)-1):
for j in range(len(elements_copy)-n):
if elements_copy[j] > elements_copy[j+1]:
elements_copy[j], elements_copy[j+1] = (
elements_copy[j+1], elements_copy[j])
n += 1
return elements_copy
|
def partition(alist, first, last):
pivot_pos = last
cur_pos = first
while pivot_pos != cur_pos:
cur, pivot = alist[cur_pos], alist[pivot_pos]
if cur > pivot:
alist[cur_pos] = alist[pivot_pos-1]
alist[pivot_pos-1], alist[pivot_pos] = pivot, cur
pivot_pos -= 1
else:
cur_pos += 1
return cur_pos
def quick_sort(alist, first, last):
if first >= last:
return
position = partition(alist, first, last)
quick_sort(alist, 0, position-1)
quick_sort(alist, position+1, last)
|
#math module
import math
print (math.ceil(123.12424))
#concatinate
x='hello world'
print (x[:6]+'bangladesh')
#string
var1 = 'Hello World!'
var2 = "Python Programming"
print(var1[10])
print("var2[1:5]: ", var2[1:5])
#lists
x=[1,2,3,4,5]
print(x[2:4])
#tuples
tup1=(12,34.56);
tup2=('abc','xyz');
tup=tup1+tup2;
print(tup)
del tup
print(tup) |
'''
Created on Mar 5, 2016
@author: shivam.maharshi
'''
from oop.Employee import Employee
from oop.Citizen import Citizen
from logging import Manager
class Manager(Employee, Citizen):
" This is Manager class. A sub class of an Employee class."
def __init__(self, name="Manager", salary=1000, level=1):
print("In the manager constructor.")
self.level = level
setattr(self, "name", name)
setattr(self, "salary", salary)
def __del__(self):
print("Collecting A class object.")
class TeamLead(Employee, Citizen):
"This is a Team Leader class. A sub class of an Employee class."
__secret = 0 # This is a secret/private field of the TL.
def __init__(self, manager, name="TeamLead", salary=500):
self.manager = manager
self.__secret = 10
setattr(self, "name", name)
setattr(self, "salary", salary)
class HRManager(Manager):
"This is my parent B class."
def __init__(self, dept, name="HRManager", salary=1000, level=1):
self.dept = dept
setattr(self, "name", name)
setattr(self, "salary", salary)
setattr(self, "level", level)
# Lets check how inheritance work.
ctz = Citizen("USA")
emp = Employee("Uncle Sam")
hrMng = HRManager(name = "Cheap HR Manager", salary=250, dept = "Human Resource")
tl = TeamLead(manager=hrMng)
print(getattr(ctz, "country"))
print(getattr(emp, "name"), " : ", getattr(emp, "salary") )
print(getattr(hrMng, "level"))
print(getattr(tl, "manager"))
print("Citizen class dictionary: ", ctz.__dict__)
print("Employee class dictionary: ", emp.__dict__)
print("HR Manager class dictionary: ", hrMng.__dict__)
print("Team Lead class dictionary: ", tl.__dict__)
|
'''
Created on May 22, 2016
Given a matrix with traversal cost on the nodes, find the lowest cost of travelling from
point 0,0 to m,n.
Link: http://www.geeksforgeeks.org/dynamic-programming-set-6-min-cost-path/
@author: shivam.maharshi
'''
def naiveGet(a, x, y, dx, dy, val):
if(x > dx or y > dy):
return 111111111;
val = val + a[x][y];
if(x==dx and y==dy):
return val;
else:
return min(naiveGet(a, x+1, y, dx, dy, val), naiveGet(a, x, y+1, dx, dy, val), naiveGet(a, x+1, y+1, dx, dy, val));
def get(a, x, y, dx, dy, val, dp):
if(x > dx or y > dy):
return 111111111;
elif(dp[x][y] is -1):
val = val + a[x][y];
if(x==dx and y==dy):
dp[x][y] = val;
else:
dp[x][y] = min(naiveGet(a, x+1, y, dx, dy, val), naiveGet(a, x, y+1, dx, dy, val), naiveGet(a, x+1, y+1, dx, dy, val));
return dp[x][y];
a = [];
a = [[0 for i in range(3)] for j in range(3)];
a[0][0] = 1;
a[0][1] = 2;
a[0][2] = 3;
a[1][0] = 4;
a[1][1] = 8;
a[1][2] = 2;
a[2][0] = 1;
a[2][1] = 5;
a[2][2] = 3;
print(naiveGet(a, 0, 0, 2, 2, 0));
dp = [[0 for i in range (3)] for j in range(3)];
for i in range (3):
for j in range (3):
dp[i][j] = -1;
print(get(a, 0, 0, 2, 2, 0, dp));
|
from collections import Iterable
# python迭代是通过for...in来实现的。
# python的for不仅仅可以用在list和tuple,还可以用在其他任何可以迭代的对象上
# list这种数据类型虽然有下标,但很多其他数据类型是没有下标的,但是,只要是可迭代对象,无论有无下标,都可以迭代,比如dict就可以迭代
d = {'a': 123, 'b': 245, 'c': 'oop', 'd': 'ddc'}
# 打印出d的所有key,因为dict的存储顺序不想list一样顺序存储所以,迭代的顺序可能不一样。
for key in d:
print(key)
# 默认情况下dict迭代的是key,想要dict的value可以这样(python2中的itervalues()已经在python3中被移出)
for value in d.values():
print(value)
# 同时迭代(iteritems()在python3中也已经没有了)
for key, value in d.items():
print(key, value)
# 字符串也是可以迭代对象因此可以用for
string = 'python大法好'
for char in string:
print(char)
# 如何判断一个对象是不是可以迭代的,可以用python collections模块的Iterable类型判断
# from collections import Iterable
# True
print(isinstance(string, Iterable))
# False
my_int = 123
print(isinstance(my_int, Iterable))
# 如果要对list实现类型其他语言那样循环小标可以用python的enumerate函数
my_list = ['a', 'b', 'c', 'd']
for i, value in enumerate(my_list):
print(i, value)
# for循环里同时引入两个变量
my_list2 = [(1, 1), (1, 2), (1, 3)]
for x, y in my_list2:
print(x, y)
# 小结 任何可迭代对象都可以作用于for循环,包括我们知道有的数据类型,只要符合迭代条件,就可以使用for循环。
# 怎么提交到git仓库啊习芭蕾。
|
# python内建函数map学习
# map()函数接收两个参数,一个是函数,一个是Iterable,map将传入的函数依次作用到序列的每个元素,并把结果作为新的Iterator返回
L = [a for a in range(1, 11)]
def function(x):
return x*x
r = map(function, L)
print(list(r))
print(list(map(str, [a for a in range(1, 11)])))
|
'''
Created on Jun 7, 2017
@author: jwang02
'''
'''program causing an error with an undefined variable'''
def main():
x = 3
f()
def f():
print(x) # error: f does not know about the x defined in main
main()
'''A change to badScope.py avoiding any error by passing a parameter'''
'''
def main():
x = 3
f(x)
def f(y):
print(y)
main()
''' |
'''
Created on Jun 9, 2017
@author: student
'''
# Finds the maximum of a series of numbers
def main():
a, b, c = input("Please enter the coefficients (a, b, c): ")
if a >= b:
if a >= c:
my_max = a
else:
my_max = c
else:
if b >= c:
my_max = b
else:
my_max = c
print "The largest value is", my_max
main()
|
# Faça um programa que peça o tamanho de um arquivo para download (em MB) e a
# velocidade de um link de Internet (em Mbps), calcule e informe o tempo
# aproximado de download do arquivo usando este link (em minutos).
def download_file():
file_size = float(input('Informe o tamanho do arquivo para download (em MBs): '))
download_speed = float(input('Informe a velocidade de download do link de internet (em MBs): '))
download_eta = (file_size / download_speed) / 60
print('O tempo aproximado para término do download é de: ' + str(download_eta) + ' minutos')
download_file() |
# Faca um Programa que peca dois numeros e imprima a soma.
number_one = float(input('Informe o primeiro numero: '))
number_two = float(input('Informe o segundo numero: '))
add_numbers = number_one + number_two
print('A soma de ' + str(number_one) + ' + ' + str(number_two) + ' e ' + str(add_numbers) + '.') |
pineapples = 5
zebras = 3
print(zebras < pineapples)
print(pineapples > zebras)
print(pineapples == zebras)
print(pineapples != zebras)
print(pineapples == 4) and (zebras == 2)
print(pineapples == 5) or (zebras == 1)
age = 10
height = 60
print(age > 7) and (height > 46)
|
from random import randint
def get_number():
"""
Returns: User input
"""
# while loop to evaluate its correctness
while True:
try:
user_input = int(input('Please provide number: '))
break
except ValueError:
print('Provided value is not a number, please try again!')
return user_input
def user_choice():
"""
Returns: The list of numbers selected by the user
"""
# defining available numbers for the user to select from and returning it into a list
# lodging get_number function to get numbers from the user
available_numbers = list(range(1, 50))
result_user = []
while len(result_user) < 6:
number = get_number()
if number in available_numbers and number not in result_user:
result_user.append(number)
result_user.sort()
print(result_user)
return result_user
def computer_choice():
"""
Returns: The list of random numbers selected by the computer
"""
# creating a list of random numbers selected by the computer
result_comp = []
while len(result_comp) < 6:
number = randint(1, 49)
if number not in result_comp:
result_comp.append(number)
print(result_comp)
return result_comp
def comparison():
"""
Returns: Number of hits by the user from selected numbers
"""
# Comparing numbers from the user with the numbers from the computer and returning number of hits
numb_hits = 0
user_numbers = user_choice()
computer_numbers = computer_choice()
hits = []
for numb in user_numbers:
if numb in computer_numbers:
hits.append(numb)
numb_hits = len(hits)
print(f'You hit {numb_hits}')
comparison() |
#Albert Valado Pujol
#Práctica 7 - Ejercico 12b
#Escribir un programa que lea una frase, y pase ésta como parámetro a una función
#que debe contar el número de palabras que contiene.
#Debe imprimir el programa principal el resultado.
#No se sabe cómo están separadas las palabras. Pueden estar separadas por más de un blanco o por signos de puntuación.
print("Este programa cuenta el número de palabras de una frase")
frase=input("Introduzca una frase.\n")
signos=[",",".",";",":","?","¿","!","¡"]
def cuentaPalabras(a):
for i in a:
if i in signos:
frase_sin_signos=a.replace(i," ")
lista=frase_sin_signos.strip(" ")
numero=len(lista)
return numero
print("La frase tiene", cuentaPalabras(frase)," palabras.")
input()
|
#Albert Valado Pujol - Práctica 2 - Introducción a Python
#Ejercicio 1 - Calcular el área de un triángulo
print ("Vamos a calcular el área de un triángulo.\n")
base= int(input("Introduce la base.\n"))
altura= int(input ("Introduce la altura.\n"))
area= int(base*altura)/2
print ("El área del triangulo es %d." %(area))
input (" ")
#Ejercicio 2 - Convertir grados centígrados en Fahrenheit
print ("Ahora vamos a convertir grados centígrados en Fahrenheit.\n")
grados_c= float(input("Introduce la temperatura en grados centígrados.\n"))
grados_f= float(grados_c*(9/5)+32)
print ("Son %f grados Fahrenheit." %(grados_f))
input (" ")
#Ejercicio 3 - Determinar si un número es par o impar
print ("A continuación, determinaremos si un número es par o impar.\n")
numero= int(input("Introduce un número.\n"))
if (numero%2==0):
print ("\nEl número es par.")
else:
print ("\nEl número es impar.")
input (" ")
#Ejercicio 4 - Determinar el mayor de dos números
print ("Finalmente, comprobaremos cuál es el mayor de dos números.\n")
num_1= int(input("Introduce el primer número.\n"))
num_2= int(input("Introduce el segundo número.\n"))
if (num_1>num_2):
print ("\n %d es mayor." %(num_1))
elif (num_2>num_1):
print ("\n %d es mayor." %(num_2))
else:
print ("\n Son iguales.")
|
#Albert Valado Pujol
#Práctica 6 - Ejercicio 11
import random
import time
random.seed (time.time ())
print("El ordenador va a pensar un número. Trate de adivinarlo.\n")
minimo = int (input ( "Introduzca un valor mínimo:\n"))
maximo = int (input ( "Introduzca un valor máximo:\n"))
secreto = random.randint (minimo, maximo)
respuesta=int(input("El número a adivinar está entre %d y %d. Escriba un número.\n" %(minimo, maximo)))
contador=1
while not respuesta == secreto:
if respuesta>secreto and respuesta<maximo:
respuesta=int(input("¡Demasiado grande! Vuélvalo a intentar.\n"))
contador+=1
elif respuesta<secreto and respuesta>minimo:
respuesta=int(input("¡Demasiado pequeño! Vuélvalo a intentar.\n"))
contador+=1
else:
print("Le recuerdo que el número a adivinar está entre %d y %d. Escriba un número entre esos dos.\n" %(minimo, maximo))
respuesta=int(input("Vuélvalo a intentar.\n"))
contador+=1
print("¡Correcto! Lo ha adivinado y tan sólo ha necesitado %d intentos." %(contador))
input()
|
#Albert Valado Pujol
#Practica 3 - Ejercicio 5
#Pida un número que como máximo tenga tres cifras (por ejemplo serían válidos 1, 99 i 213 pero no 1001). Si el usuario introduce un número de más de tres cifras debe un informar con un mensaje de error como este “ ERROR: El número 1005 tiene más de tres cifras”.
num=int(input("Introduzca un número de tres cifras.\n"))
if (num>=1000):
print ("ERROR. %d tiene más de tres cifras." %(num))
else:
print ("Yup. Tal y como pensaba, %d es un número de tres o menos cifras." %(num))
input("Pulse ENTER para cerrar el programa.")
|
#Albert Valado Pujol
#Práctica 5 - Ejercicio 7
#Escribe un programa que pida la anchura de un triángulo y lo dibuje de
#la siguiente manera:
ancho=int(input("Introduce la anchura del triángulo.\n"))
for i in range(ancho):
print("*"*i)
for j in range(ancho, 0, -1):
print("*"*j)
input(" ")
|
#Albert Valado Pujol
#Practica 3 - Ejercicio 6
#Pida al usuario el precio de un producto y el nombre del producto y muestre el mensaje con el precio del IVA (21%). Por ejemplo: “ Tu bicicleta vale 100 euros y con el 21 % de IVA se queda en 121 euros en total”.
nombre=input("Introduzca su producto.\n")
precio=float(input("Introduzca el precio de dicho producto.\n"))
iva= precio*21/100
precio_total= precio+iva
print("Su(s)", nombre, "vale", precio, "euros y con el 21 por ciento de IVA se queda en", precio_total, "euros en total.")
input("Pulse ENTER para cerrar el programa.")
|
fruits = ['Banana', 'Warermellon', 'Grapes', 'Mango']
for items in fruits:
print(items)
|
# Write a programm using function to find greater of three number
def greater(num1, num2, num3):
if num1 > num2:
if num1 > num3:
return num1
else:
return num3
else:
if num2 > num3:
return num2
else:
return num3
m = greater(5, 8, 22)
print("The greater number is " + str(m)) |
l1 = [1, 8, 7, 2, 21, 15]
print(l1)
# l1.sort() # sort the list
# l1.reverse() # reverses the list
# l1.append(45) # appends the list
# l1.insert(2, 544) # insert 544 at index 2
# l1.pop(2) # remove element at index 2
l1.remove(21) # removes 21 from list
print(l1)
|
# The game() function in a programm lets a user play a game and returns the score as an integer. You need to read a file 'hiscore.txt' which is either blank or contains the previous hi-score. You need to write a programm to update the hiscore whenever game() breaks the hiscore.
import random
def game():
n = random.randint(1, 50)
return n
score = game()
with open("highscore.txt") as f:
highscore = f.read()
if highscore == '':
with open("highscore.txt", 'w') as f:
f.write(str(score))
if int(highscore) < score:
with open("highscore.txt", 'w') as f:
f.write(str(score)) |
# If else and elif syntax.
# a = 45
# if(a > 3):
# print("The value of a is greater then 3")
# elif(a > 7):
# print("The value of a is greater than 7")
# else:
# print("The value is not greater than 3 or 7")
# 2. Multiple if statements
a = 45
if(a > 3):
print("The value of a is greater then 3")
if(a > 7):
print("The value of a is greater than 7")
if(a < 40):
print("The value of a is smaller than 40")
else:
print("The value is not greater than 3 or 7")
|
def percent(marks):
# return ((marks[0] + marks[1] + marks[2] + marks[3])/400)*100
return sum(marks)/4
marks1 = [45, 78, 86, 77]
percentage = percent(marks1)
marks2 = [55, 40, 50, 70]
percentage2 = percent(marks2)
print(percentage, percentage2)
|
# Write a programm to format the following letter using escape sequence chracter
letter = "Dear Shibu, This Python course is nice! Thanks!"
formatter_letter = "Dear Shibu,\n\tThis Python course is nice!\nThanks!"
print(formatter_letter) |
# Write a programm to mine a log file and find out whethir it contains "python". and also find line number.
content = True
i = 1
with open("log.txt") as f:
while content:
content = f.readline()
if 'python' in content.lower():
print(content)
print(f"python is present on line number {i}")
i += 1 |
nterms =[]
res=[]
for i in range(0,1):
a=int(input())
nterms.append(a)
n1 = 0
n2 = 1
count = 0
if nterms[0] <= 0:
print("Please enter a positive integer")
elif nterms[0] == 1:
print("Fibonacci sequence upto",nterms,":")
res.append(n1)
else:
print("Fibonacci sequence upto",nterms,":")
while count < nterms[0]:
res.append(n1)
nth =n1 + n2
n1 = n2
n2 = nth
count += 1
print(res)
|
lower,upper=input().split()
lower = int(lower)
upper = int(upper)
for num in range(lower, upper):
order = len(str(num))
sum = 0
temp = num
while temp > 0:
digit = temp % 10
sum += digit ** order
temp //= 10
|
a=int(input())
sum1 = 0
while(a > 0):
sum1=sum1+a
a=a-1
print(sum1)
|
# TWI DAY NAME DETECTOR PROGRAM
# Yaw Asare, June 12 2020
# This is primarily a test of boolean and comparison operators
print()
print('*** TWI DAY NAME DETECTOR ***')
print()
print('Tell me the day of the week you were born and your gender, I will tell you your dayname in Twi')
print()
# getting the user's gender
genderpassed = False
while genderpassed == False:
print('What is your gender (m/f)?')
gender = input().lower()
# check to see if they used the shorthard
if gender == 'm' or gender == 'ma':
gender = 'male'
elif gender == 'f' or gender == 'fem':
gender = 'female'
# check to see if there is a male or female selected
if gender == 'male' or gender == 'female':
genderpassed = True
else:
print('Sorry, but Twi daynames are designated for males and females.')
print('Would you like to try again (y/n)?')
tryagain = input().lower()
if tryagain == 'y' or tryagain == 'yes':
genderpassed = False
elif tryagain == 'n' or tryagain == 'no':
genderpassed = True
else:
genderpassed = False
print()
# getting the user's bornday
daypassed = False
while daypassed == False:
print('What day of the week were you born on?')
day = input()
day = day.lower()
# check to see if they used the shorthand
if day == 'mon' or day == 'm':
day = day + 'day'
elif day == 'tues' or day == 'tu':
day = day + 'day'
elif day == 'weds' or day == 'wed':
day = 'wednesday'
elif day == 'thurs' or day == 'th' or day == 'thu':
day = 'thursday'
elif day == 'fri' or day == 'f':
day = 'friday'
elif day == 'sat' or day == 'sa':
day = 'saturday'
elif day == 'sun' or day == 'su':
day = 'sunday'
if day != 'monday' and day != 'tuesday' and day != 'wednesday' and day != 'thursday' and day != 'friday' and day != 'saturday' and day != 'sunday':
print('Sorry, but that is not a day of the week.')
print('Would you like to try again (y/n)?')
tryagain = input().lower()
if tryagain == 'y' or tryagain == 'yes':
daypassed = False
elif tryagain == 'n' or tryagain == 'no':
daypassed = True
else:
daypassed = False
else:
daypassed = True
print()
#giving the user their day name
print()
print('Your day name is: ')
if gender == 'male' and day == 'monday':
print('Kojo')
elif gender == 'male' and day == 'tuesday':
print('Kwabena')
elif gender == 'male' and day == 'wednesday':
print('Kwaku')
elif gender == 'male' and day == 'thursday':
print('Yaw')
elif gender == 'male' and day == 'friday':
print('Kofi')
elif gender == 'male' and day == 'saturday':
print('Kwame')
elif gender == 'male' and day == 'sunday':
print('Kwasi')
elif gender == 'female' and day == 'monday':
print('Adjoa')
elif gender == 'female' and day == 'tuesday':
print('Abena')
elif gender == 'female' and day == 'wednesday':
print('Akua')
elif gender == 'female' and day == 'thursday':
print('Yaa')
elif gender == 'female' and day == 'friday':
print('Afia')
elif gender == 'female' and day == 'saturday':
print('Amma')
elif gender == 'female' and day == 'sunday':
print('Akosua')
else:
print('...Sorry, there is no Twi day name for you.')
|
import random
print('Put in a number between 1 and 10 and I will see if I can guess it!')
userNumber = input()
print()
numberOfGuesses = 0
while True:
compGuess = random.randint(1, 10)
numberOfGuesses = numberOfGuesses + 1
if compGuess == int(userNumber):
print('I got it right!! Your number is: ' + str(userNumber))
break
else:
print('Hmm... I guess ' + str(compGuess) + '. Missed didnt I? I will try again!')
print()
print('It took me ' + str(numberOfGuesses) + ' tries to get it right.')
|
'''
- Given a github username extrac all his/her folowers and store them into a CSV File
https://api.github.com/users/{user}/followers
'''
import requests, csv
page = 1
cycle = True
COLUMNS = ['login', 'id', 'node_id', 'avatar_url', 'gravatar_id', 'url', 'html_url', 'followers_url', 'following_url', 'gists_url', 'starred_url', 'subscriptions_url', 'organizations_url', 'repos_url', 'events_url', 'received_events_url', 'type', 'site_admin']
FILENAME = 'tmp/followers_github.csv'
BASE_URL = 'https://api.github.com/'
# Modified functions from another file
def get_user_endpoint(username, page):
'''
Name: get_user_endpoint
Params: username -> String
Returns: The endpoint url to fetch user information from Github API
'''
return f'{BASE_URL}users/{username}/followers?page={page}'
def get_user(username, page):
'''
Name: get_user
Params: username -> String
Returns: Dictionary with user information
'''
url = get_user_endpoint(username, page)
response = requests.get(url)
if response.status_code != 200:
return None
return response.json()
# Getting the username
username = input('Give me an username: ')
# Opening file in writable mode
with open(FILENAME, mode='w', newline='') as csv_file:
writer = csv.DictWriter(csv_file, fieldnames=COLUMNS)
# Writing the columns
writer.writeheader()
while cycle == True:
# Getting the followers of the user from all the pages
followers = get_user(username, page)
if followers != None:
# Writing the rows
for follower in followers:
writer.writerow(follower)
page = page + 1
else:
cycle = False
|
import time
import json
from pprint import pprint as pp
# placed into variables for easy use
tickets_file_location = '../json/tickets.json'
ticket_types_file_location = '../json/ticket_types.json'
users_file_location = '../json/users.json'
def create_ticket(ticket_id, ticket_type_id, ticket_description, ticket_opened_by_id, ticket_due_date):
"""
Function to create a ticket and add to persistent json file
:param ticket_id: str
:param ticket_type_id: int
:param ticket_description: text
:param ticket_opened_by_id: int
:param ticket_due_date: time
"""
# Get current data to update it
with open(tickets_file_location, 'r') as f:
tickets = json.load(f)
# Place all information for new ticket into a dictionary to easily add it to the ticket dictionary
new_ticket = {
"type": int(ticket_type_id),
"description": ticket_description,
"opened_by": int(ticket_opened_by_id),
"opened_at": time.time(),
"updated_at": time.time(),
"due_date": ticket_due_date,
"updated_by": int(ticket_opened_by_id)
}
# Add the new ticket using it's ID as the key
tickets.setdefault(ticket_id, new_ticket)
# Rewrite the persistent JSON file
with open(tickets_file_location, 'w') as f:
f.write(json.dumps(tickets))
return 0
def update_ticket(ticket_id, new_data):
"""
Requires the ticket_id will update given attribute(s) of the ticket
:param ticket_id: str
:param new_data: various possible attributes
"""
print("updating", ticket_id, "...")
# Check to see which attribute is being updated
ticket_type_id = new_data.get('ticket_type', None)
ticket_description = new_data.get('ticket_description', None)
ticket_updated_by_id = new_data.get('ticket_updated_by', None)
ticket_due_date = new_data.get('ticket_due_date', None)
# Retrieve the ticket data from JSON
with open(tickets_file_location, 'r') as f:
tickets = json.load(f)
# If so, update the data
if ticket_type_id:
tickets[ticket_id]["type"] = int(ticket_type_id)
if ticket_updated_by_id:
tickets[ticket_id]["updated_by"] = int(ticket_updated_by_id)
if ticket_description:
tickets[ticket_id]["description"] = ticket_description
if ticket_due_date:
tickets[ticket_id]["due_date"] = ticket_due_date
# Set updated_at to current time
tickets[ticket_id]["updated_at"] = time.time()
# Rewrite the JSON
with open(tickets_file_location, 'w') as f:
f.write(json.dumps(tickets))
def delete_ticket(ticket_id):
"""
Deletes ticket with given id
:param ticket_id: str
"""
# Get ticket information from JSON
with open(tickets_file_location, 'r') as f:
tickets = json.load(f)
# Remove the ticket with the matching id
del tickets[ticket_id]
# Rewrite JSON
with open(tickets_file_location, 'w') as f:
f.write(json.dumps(tickets))
|
number = int (input(" enter any number : "))
for i in range(0,number ):
chr = 65
for j in range(0,number - i):
print (chr , end = " ")
print(" ") |
from .pessoa import Pessoa # primeiro importamos a classe Mãe
class PessoaFisica(Pessoa): # Para indicar que uma classe extende a outra, passamos ela como "Parâmetro" na definição da class
def __init__(self, nome, endereco, cpf, nascimento):
super().__init__(nome, endereco) # a instrução super() chama em uma classe filha, um método da classe pai. Nesse caso, está chamando o método construtor
self.__cpf = cpf
self.__nascimento = nascimento
def set_cpf(self, cpf):
self.__cpf = cpf
def get_cpf(self):
return self.__cpf
def set_nascimento(self, nascimento):
self.__nascimento = nascimento
def get_nascimento(self):
return self.__nascimento
cpf = property(get_cpf, set_cpf)
nascimento = property(get_nascimento, set_nascimento)
def imprimir_detalhes(self):
print('Chamando na classe pessoaFisica')
super().imprimir_detalhes()
print('CPF ' + self.cpf)
print('Nascimento ' + self.nascimento)
def comprar(self, produto, quantidade):
super().comprar(produto)
print(' em ' + str(quantidade) + ' unidades') |
#!/usr/bin/env python3
# https://www.hackerrank.com/challenges/itertools-combinations-with-replacement/problem
from itertools import combinations_with_replacement
if __name__ == '__main__':
# break input into list of size and string
mystringlist = [ str(x) for x in input().split(' ')]
# break string into list
mystringsplit = sorted([x for x in mystringlist[0]])
# get number of combination/replacements from string list
size = int(mystringlist[1])
# initialize list to store combos/replacements
thelist = []
# loop over combo/replacement size and populate list of raw results
for i in range(1, size + 1):
thelist.append(list(combinations_with_replacement(mystringsplit, i)))
# initialize list for parsed results
parsedlist = []
# initialize the string counter used for sorting each list item alphabetically
appstring = ''
for i in thelist:
# loop over each list item and sort
for j in range(0, len(i)):
# if list item matches the size
if len(i[j]) == size:
# sort and increment the string counter
for k in range(0, len(i[j])):
appstring += str(i[j][k])
# append if item is not an empty string
if appstring != '':
parsedlist.append(appstring)
# reset string counter for the next loop
appstring = ''
# sort all of the items in order to print out the list in lexographic order
sortedlist = sorted(parsedlist, key=lambda x: (len(x), x))
# print the list to fulfill the STDOUT requirement of the exercise
for i in sortedlist:
print(i)
|
#anju
num=int(input())
for i in range (1,num+1):
if(num%i==0):
print (i, end=" ") |
num=int(input())
f=1
if(num<0):
print("0")
if(num==0):
print("1")
else:
for i in range(1,num+1):
f=f*i
print(f)
|
#anju
x=input()
z=list(x)
y=len(z)
f=0
if y%2==0:
i=y//2
z[i]='*'
z[i-1]='*'
t=''.join(z)
print(t)
else:
f=y//2
z[f]='*'
e=''.join(z)
print(e)
|
#anju
string=list(input())
a=(sorted(string))
for i in range(0,len(a)):
print(a[i],end="") |
# coding: utf-8
# In[2]:
#define dictionary data structure
#dictionaries have key: value for the elements
example_dict = {
"class" : "astr 119",
"prof" : "Brant",
"awesomeness" : 100
}
print(type(example_dict)) #will print type dict
#get a value via key
example_dict["awesomeness"] += 1 #increase awesomeness
#print dictionary
print(example_dict)
#print dictionary element by element
for x in example_dict.keys():
print(x, example_dict[x])
|
# coding: utf-8
# In[1]:
#if else control
#define function
def flow_control(k):
#define string based on k value
if(k==0):
s = "variable k = %d equals 0" % k
elif(k==1):
s = "variable k = %d equals 1" % k
else:
s = "variable k = %d does not equal 0 or 1" % k
# print variable
print(s)
#define main function
def main():
i = 0
#try flow control for 0, 1, 2
flow_control(i)
i = 1
flow_control(i)
i = 2
flow_control(i)
#run the program
if __name__ == "_main_":
main()
#error, name is not define in line 25
|
bottles_remaining = 99
while bottles_remaining > 0:
print(f"{bottles_remaining} bottles of beer on the wall, {bottles_remaining} of beer")
print("Take one down, pass it around")
bottles_remaining = bottles_remaining - 1
print(f"{bottles_remaining} bottles of beer on the wall")
|
username = input("Enter username:")
print("Username is: " + username)
price = 50
txt = "The price is {} dollars"
print(txt.format(price))
myorder = "I have a {carname}, it is a {model}."
print(myorder.format(carname = "Telsa", model = "Model Y"))
age = 21
name = "Alex"
txt = "His name is {1}. {1} is {0} years old."
print(txt.format(age, name)) |
client_list = {1: "Anirban", 2: "John", 3: "Messi", 4:"sergio", 5: "James", 6:"Ronaldo"}
lock_list = {1: "Exercise", 2: "Diet", 3:"Games"}
def getdate():
import datetime
return datetime.datetime.now()
try:
print("Select Client Name:")
for key, value in client_list.items():
print("Press", key, "for", value, "\n", end="")
client_name = int(input())
print("Selected Client : ", client_list[client_name], "\n", end="")
print("Press 1 for Lock")
print("Press 2 for Retrieve")
op = int(input())
if op == 1:
for key, value in lock_list.items():
print("Press", key, "to lock", value, "\n", end="")
lock_name = int(input())
print("Selected Job : ", lock_list[lock_name])
f = open(client_list[client_name] + "_" + lock_list[lock_name] + ".txt", "a")
k = 'y'
while (k != "n"):
print("Enter", lock_list[lock_name], "\n", end="")
mytext = input()
f.write("[ " + str(getdate()) + " ] : " + mytext + "\n")
k = input("ADD MORE ? y/n:")
continue
f.close()
elif op == 2:
for key, value in lock_list.items():
print("Press", key, "to retrieve", value, "\n", end="")
lock_name = int(input())
print(client_list[client_name], "-", lock_list[lock_name], "Report :", "\n", end="")
f = open(client_list[client_name] + "_" + lock_list[lock_name] + ".txt", "rt")
contents = f.readlines()
for line in contents:
print(line, end="")
f.close()
else:
print("Invalid Input !!!")
except Exception as e:
print("Wrong Input !!!") |
from abc import ABC, abstractmethod
class Strain_2d(ABC):
"""
Implement a generic 2D strain rate method
Strain_2d(grid_inc, strain_range, data_range)
Parameters
-------------
grid_inc : list of [float, float]
xinc, yinc in degrees for the rectilinear grid on which strain is calculated
strain_range: list of [float, float, float, float]
west, east, south, north edges of bounding box for grid on which strain is calculated
xdata: 1d array of lon numbers
ydata: 1d array of lat numbers
data_range: list of [float, float, float, float]
west, east, south, north edges of box that contains geodetic data (potentially larger than strain_range)
Methods
--------------
compute(): required method that takes a velocity field and will eventually compute strain
only provided as a template here
"""
def __init__(self, grid_inc, strain_range, data_range, xdata, ydata, outdir):
# Initialize general parameters
self._Name = None
self._grid_inc = grid_inc
self._strain_range = strain_range
self._data_range = data_range
self._xdata = xdata
self._ydata = ydata
self._outdir = outdir
def Method(self):
return self._Name
@abstractmethod
def compute(self, myVelfield):
# generic method to be implemented in each method
pass
|
#!/usr/bin/env python3
import os
os.system("clear")
print("")
print("")
print("Use this script to remove the random junk characters that youtube-dl")
print(" adds to the end of mp3 filenames.")
print("")
print(" ____________________")
print(" | |")
print(" | Drop your |")
print(" | mp3 folder |")
print(" | here and |")
print(" | Press Enter |")
print(" |___________________|")
dir = input("")
os.system("clear")
#If the directory name has spaces in it, the drag and drop will put the
#entire path in single quotes, which need to be removed.
test = "'" in dir
if test == True:
dir = dir[1:-1]
#The path needs to have forward slash at the end in order for the script
#to be able to properly rename the files.
dir = dir + "/"
count = 0
files = os.listdir(dir)
for entry in files:
if entry.endswith(".mp3"):
os.rename(dir + entry, dir + entry[:-16] + ".mp3")
print("changing " + entry)
count += 1
count = str(count)
print("")
print("")
print(count + " file(s) renamed.")
print("")
print("")
|
#!/usr/bin/env python
class Libro:
"""Clase que modela un Libro"""
# Atributos miembros de la clase
contador = 0
# Metodo de inicializacion
def __init__(self, isbn = '', autor = '', pags = 0):
# Atributos de datos
self.__isbn = isbn
self.__autor = autor
self.__pags = pags
self.__class__.contador += 1 # Variable de clase
def __str__(self):
return "El libro " + self.__isbn + "fue escrito por " + self.__autor
@classmethod
def instances(clase):
print("Llevamos {0} libros".format(clase.contador))
def __del__(self):
print("Me acaban de destruir")
def main():
l1 = Libro()
print(l1.__doc__)
Libro.instances()
print(l1)
l2 = Libro("5678", "Juan Perez")
print(l2.__doc__)
l2.instances()
print(l2)
l3 = Libro(pags = 500, autor = "Josefa")
print(l3.__doc__)
Libro.instances()
print(l3)
main()
|
att = 0
ans1 = ''
ans2 = ''
ans3 = ''
while ans1 != '19':
ans1 = input('What is 9+10?')
if ans1 == '19':
print('Correct!')
else:
print('Wrong')
att = att + 1
while ans2 != 'kcvi':
ans2 = input('What is the best school?')
if ans2 == 'kcvi':
print('Correct!')
else:
print('Wrong')
att = att + 1
print('It took you',att,'times')
|
temp = float(input('Temperature?'))
print((temp - 32)*5/9,'celsius')
|
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def swapPairs(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
pre = ListNode(-1)
pre.next = head
tmp = pre
while tmp.next and tmp.next.next:
node1=tmp.next
node2 = tmp.next.next
tmp.next = node2
node1.next = node2.next
node2.next = node1
tmp = tmp.next.next
return pre.next
|
class Solution(object):
def hasCycle(self, head):
"""
:type head: ListNode
:rtype: bool
"""
pin2, pin = head, head
while pin2 and pin2.next:
pin, pin2 = pin.next, pin2.next.next
if pin2 is pin:
return True
return False
|
class Solution(object):
def checkPossibility(self, nums):
"""
:type nums: List[int]
:rtype: bool
"""
if len(nums)<3:
return True
count,count2 = -1,-1
for i in range(1,len(nums)):
if nums[i-1]>nums[i]:
count = i-1
count2 = i
break
i = count2
nums1 = nums[:i-1]+nums[i:]
nums2 = nums[:i]+nums[i+1:]
if self.check(nums1) or self.check(nums2):
return True
return False
def check(self,nums):
for i in range(1,len(nums)):
if nums[i-1]>nums[i]:
return False
return True
|
class Solution(object):
def isValidSudoku(self, board):
"""
:type board: List[List[str]]
:rtype: bool
"""
for i in range(9):
if not self.isValidList([board[i][j] for j in range(9)]) or not self.isValidList([board[j][i] for j in range(9)]):
return False
for i in range(3):
for j in range(3):
if not self.isValidList([board[m][n] for m in range(3*i,3*i+3) for n in range(3*j,3*j+3)]):
return False
return True
def isValidList(self, lists):
lists = filter(lambda x:x!='.',lists)
return len(set(lists))==len(lists)
#mehod 2 (faster)
class Solution(object):
def isValidSudoku(self, board):
"""
:type board: List[List[str]]
:rtype: bool
"""
res = []
for i,row in enumerate(board):
for j,nums in enumerate(row):
if nums != '.':
res += [(nums,j),(i,nums),(nums,i/3,j/3)]
#return res
return len(res) == len(set(res))
|
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def sumNumbers(self, root):
"""
:type root: TreeNode
:rtype: int
"""
return self.recur(root,0)
def recur(self, root, sums):
if not root:
return 0
sums = root.val+sums*10
return sum([self.recur(root.left, sums) ,self.recur(root.right, sums)]) or sums
|
import re
def get_float(input_str="",text="", format_=float):
while not re.match(r'^[+-]?\d{0,}\.?\d+$', input_str):
# use construction try, except for
input_str = input('Enter the value {0}: '.format(text))
if input_str == "" or input_str == " " or len(input_str) <= 0 or 'exit' in input_str:
exit()
return format_(input_str)
def division(a,b):
return a/b
|
"""
You are in charge of a display advertising program. Your ads are displayed on
websites all over the internet. You have some CSV input data that counts how many
times you showed an ad on each individual domain. Every line consists of a count
and a domain name. It looks like this:
counts = [ "900,google.com",
"60,mail.yahoo.com",
"10,mobile.sports.yahoo.com",
"40,sports.yahoo.com",
"300,yahoo.com",
"10,stackoverflow.com",
"2,en.wikipedia.org",
"1,es.wikipedia.org" ]
Write a function that takes this input as a parameter and returns a data structure
containing the number of hits that were recorded on each domain AND each domain
under it. For example, an impression on "sports.yahoo.com" counts for
"sports.yahoo.com", "yahoo.com", and "com". (Subdomains are added to the left of
their parent domain. So "sports" and "sports.yahoo" are not valid domains.)
Expected output (in any order):
1320 com
900 google.com
410 yahoo.com
60 mail.yahoo.com
10 mobile.sports.yahoo.com
50 sports.yahoo.com
10 stackoverflow.com
3 org
3 wikipedia.org
2 en.wikipedia.org
1 es.wikipedia.org
"""
def count_hits_per_domain(data):
domain_counts = {}
for domain in data:
domain = domain.split(',')
domain_counts[domain[1]] = int(domain[0])
hits_per_domain = {}
for key in domain_counts:
# split domain string into words array
words_in_domain = key.split('.')
words_in_domain_index = 1
subdomain = ''
while words_in_domain_index <= len(words_in_domain):
if subdomain == '':
subdomain = words_in_domain[-words_in_domain_index]
else:
subdomain = words_in_domain[-words_in_domain_index] + '.' + subdomain
hits_per_domain[subdomain] = hits_per_domain.get(subdomain, 0) + domain_counts[key]
words_in_domain_index += 1
output = ''
for domain in hits_per_domain:
output = output + str(hits_per_domain[domain]) + '\t' + domain + '\n'
return output
counts = [ "900,google.com",
"60,mail.yahoo.com",
"10,mobile.sports.yahoo.com",
"40,sports.yahoo.com",
"300,yahoo.com",
"10,stackoverflow.com",
"2,en.wikipedia.org",
"1,es.wikipedia.org" ]
print count_hits_per_domain(counts)
|
"""
Given a string, find the length of the longest substring without repeating
characters.
Example 1:
Input: "abcabcbb"
Output: 3
Explanation: The answer is "abc", which the length is 3.
Example 2:
Input: "bbbbb"
Output: 1
Explanation: The answer is "b", with the length of 1.
Example 3:
Input: "pwwkew"
Output: 3
Explanation: The answer is "wke", with the length of 3.
Note that the answer must be a substring, "pwke" is a subsequence
and not a substring.
"""
def lengthOfLongestSubstring(s):
"""Given a string, return the length of the longest substring without
repeating chars."""
max_count = start_idx = curr_idx = 0
curr_letters = set()
while curr_idx < len(s):
if (s[curr_idx] in curr_letters):
start_idx += 1
curr_idx = start_idx
curr_letters.clear()
else:
curr_letters.add(s[curr_idx])
curr_idx += 1
max_count = max(max_count, curr_idx - start_idx)
return max_count |
"""
Given a sorted array of intergers and an target integer, return the index of
the target integer. If the target in not found, return None.
"""
def binary_search(lst, num):
left = 0
right = len(lst) - 1
while left <= right:
mid = (left + right) / 2
if lst[mid] == num:
return mid
elif lst[mid] > num:
right = mid - 1
elif lst[mid] < num:
left = mid + 1
return None |
"""
Given a string S and a string T, find the minimum window in S which will
contain all the characters in T in complexity O(n).
Example:
Input: S = "ADOBECODEBANC", T = "ABC"
Output: "BANC"
Note:
If there is no such window in S that covers all characters in T, return the
empty string "".
If there is such window, you are guaranteed that there will always be only one
unique minimum window in S.
"""
def find_substring(s, t):
if len(t) > len(s):
return ''
chars_subset = []
found = False
for i, char in enumerate(s):
if char in t:
chars_subset.append((i, char))
t_char_count = track_char_count(t)
left = 0
right = len(t)
correct_window_left = 0
correct_window_right = 0
min_window = len(s)
while right < len(chars_subset):
sub = chars_subset[left:right + 1]
sub_char_count = track_char_count_tuple(sub)
if all(item in sub_char_count for item in t_char_count) and all(
t_char_count[item] <= sub_char_count[item] for item in t_char_count):
found = True
s_left = chars_subset[left][0]
s_right = chars_subset[right][0]
if s_right - s_left <= min_window:
correct_window_left = s_left
correct_window_right = s_right
min_window = s_right - s_left
left += 1
else:
right += 1
if found:
return s[correct_window_left:correct_window_right + 1]
return ''
def track_char_count(string):
char_count = {}
for char in string:
char_count[char] = char_count.get(char, 0) + 1
return char_count
def track_char_count_tuple(list):
char_count = {}
for idx, char in list:
char_count[char] = char_count.get(char, 0) + 1
return char_count
# print(find_substring('ADOBECODEBANC', 'ABC'))
print(find_substring('ab', 'a'))
|
# recursively
def merge_sort_recursive(list1, list2, merged_list=None):
"""Merge 2 sorted lists in order recursively"""
if merged_list is None:
merged_list = []
if list1 and list2:
if list1[0] < list2[0]:
merged_list.append(list1.pop(0))
else:
merged_list.append(list2.pop(0))
return merge_sort_recursive(list1, list2, merged_list)
elif list1:
merged_list.extend(list1)
return merged_list
elif list2:
merged_list.extend(list2)
return merged_list
# iteratively
def merge_sort_iterative(list1, list2):
"""Merge 2 sorted lists"""
merged_list = []
while list1 and list2:
if list1[0] < list2[0]:
merged_list.append(list1.pop(0))
else:
merged_list.append(list2.pop(0))
if list1:
merged_list.extend(list1)
elif list2:
merged_list.extend(list2)
return merged_list
# improved solution with indexing
def merge_sort_index(list1, list2):
"""Merge 2 sorted lists with O(n) space and runtime"""
merged_list = []
list1_index = 0
list2_index = 0
while (list1_index < len(list1) - 1) and (list2_index < len(list2) - 1):
if list1[list1_index] < list2[list2_index]:
merged_list.append(list1[list1_index])
list1_index += 1
else:
merged_list.append(list2[list2_index])
list2_index += 1
if list1_index < len(list1) - 1:
merged_list.extend(list1[list1_index:])
else:
merged_list.extend(list2[list2_index:])
return merged_list |
"""
Implement the merge sort algorithm with optimal runtime.
"""
def merge_sort(lst):
"""Given an unsorted list, returns the sorted list using merging."""
if len(lst) < 2:
return lst
mid = len(lst) / 2
left = merge_sort(lst[:mid])
right = merge_sort(lst[mid:])
return make_merge(left, right)
def make_merge(lst1, lst2):
"""Given 2 lists, return one sorted list."""
merged = []
lst1_idx = lst2_idx = 0
while lst1_idx < len(lst1) and lst2_idx < len(lst2):
if lst1[lst1_idx] <= lst2[lst2_idx]:
merged.append(lst1[lst1_idx])
lst1_idx += 1
else:
merged.append(lst2[lst2_idx])
lst2_idx += 1
if lst1_idx < len(lst1):
merged.extend(lst1[lst1_idx:])
if lst2_idx < len(lst2):
merged.extend(lst2[lst2_idx:])
return merged
print(merge_sort([2, 1, 7, 4, 5, 3, 6, 8]))
|
import unittest
"""
Compute the nth fibonacci number.
"""
def compute_fibonacci(n):
if n == 0 or n == 1:
return n
return compute_fibonacci(n - 1) + compute_fibonacci(n - 2)
def compute_finonacci_memo(n, memo=None):
if not memo:
memo = [0] * (n + 1)
if n == 0 or n == 1:
return n
if memo[n] == 0:
memo[n] = compute_finonacci_memo(
n - 1, memo) + compute_finonacci_memo(
n - 2, memo)
return memo[n]
def compute_fibonacci_iterative(n):
if n == 1 or n == 0:
return n
prev_prev = 0
prev = 1
for _ in range(n - 1):
curr = prev_prev + prev
prev_prev = prev
prev = curr
return curr
class TestFibonacci(unittest.TestCase):
test_cases = [(0, 0), (1, 1), (13, 233), (25, 75025)]
def test_compute_fibonacci(self):
for n, ans in self.test_cases:
self.assertEqual(compute_fibonacci(n), ans)
def test_compute_fibonacci_memo(self):
for n, ans in self.test_cases:
self.assertEqual(compute_finonacci_memo(n), ans)
def test_compute_fibonacci_iterative(self):
for n, ans in self.test_cases:
self.assertEqual(compute_fibonacci_iterative(n), ans)
if __name__ == '__main__':
unittest.main(verbosity=2)
|
# taylor expansion for cosine around 0
# cos(x) = 1 - x^2/2! + x^4/4! - x^6/6! + x^8/8! - ...
import numpy as np
import matplotlib.pyplot as plt
# Initialize range and number of terms
xrange = np.arange(-10, 10, .1)
print('\n\nThe Taylor Expansion of Cosine around 0 takes the form:\n'
'cos(x) = 1 - x^2/2! + x^4/4! - x^6/6! + x^8/8! - ... \n'
'The more terms you include in the expansion, \n'
'the better approximation of cosx\n')
user_req_terms = int(input('How many terms of this expansion would you like me to plot?\n'))
# Create list of powers [2,4,6,...]
num_terms = []
for a in range(1, user_req_terms+1):
num_terms.append(a*2)
# Factorial called in n_terms()
def factorial(power):
multiple = 1
for a in range(1, power + 1):
multiple = multiple * a
return multiple
# n_terms called in taylor()
def n_terms(a):
y = 0
for n in num_terms:
if num_terms.index(n) % 2 == 0:
y = y + a ** n / factorial(n)
else:
y = y - a ** n / factorial(n)
return(y)
# Creates and plots taylor function
def taylor():
taylor_func = []
for a in xrange:
z = 1 - n_terms(a)
taylor_func.append(z)
plt.plot(xrange, taylor_func, 'b+')
# Cosine for reference
def cos():
cos_ref = []
for a in xrange:
z = np.cos(a)
cos_ref.append(z)
plt.plot(xrange, cos_ref, 'y')
taylor()
cos()
plt.ylim(-1, 1)
plt.show()
|
def quick_sort(A,low,high):
if low<high:
pivot = partition(A,low,high)
quick_sort(A,low,pivot-1)
quick_sort(A,pivot+1,high)
def partition(A,low, high):
pivot= low
swap(A,pivot,high)
for i in range(low,high):
if A[i]<=A[high]:
swap(A,i,low)
low +=1
swap(A,low,high)
return low
def swap(A,x,y):
temp= A[x]
A[x]= A[y]
A[y]= temp
A=[112,432,42,4212,4344,45678,854,31,90]
print("before sorting",A)
quick_sort(A,0,len(A)-1)
print("after sorting",A) |
#!/usr/bin/env python
# 0 1 2 3
fruits = ['apple', 'cherry', 'orange', 'kiwi', 'banana', 'pear', 'fig']
# 012345678
name = "Eric Idle"
# 0 1 2
knight = 'King', 'Arthur', 'Britain'
print(fruits[3]) # <1>
print(name[0]) # <2>
print(knight[1]) # <3>
print(len(fruits), len(name), len(knight))
|
#!/usr/bin/env python
x = ["bear"]
x.extend(x)
print(x)
print(dir(x))
animals = ['bear', 'otter', 'wolf', 'moose']
print('\n'.join(animals))
# sep.join(SEQUENCE-of-STRINGS)
print("/".join(animals))
for animal in animals:
print(f"{animal}\n")
|
def string_comparison (first, second):
if type (first) != str or type (second) != str :
return 0
if first == second:
return 1
if len(first) > len(second):
return 2
if second == 'learn':
return 3
return ('Такого условия нет')
print ('Результат работы функции по прописанным переменным: ')
print(string_comparison(123, 'кот'))
print(string_comparison('котик', 'котик'))
print(string_comparison('котик', 'кот'))
print(string_comparison('котик', 'learn'))
print(string_comparison('кошка', 'котик'))
print ('Работа функции по вводимым данным')
while True:
frst_word = input ('Введите слово ')
sec_word = input ('Введите другое слово ')
result = string_comparison (frst_word, sec_word)
print(result)
if result == 'Такого условия нет':
break
#while string_comparison (first, second) != -1:
|
ParentsList = ["latch","louise"]
KidsList = ["daisy","ajay"]
PetsList = ["ted","amos","cybil"]
FamilyList = ParentsList + KidsList + PetsList
print("random order:" + str(FamilyList))
FamilyList.sort()
print ("alphabetical order:" + str(FamilyList))
|
"""
*@file
*
*@brief The MainStarter class has main in it that runs the whole program.
* You are able to do 6 things with the train line as detailed in the
* description below.
*
* @author Raiza Soares
* @mainpage Program - Python
*
* @description The program starts with displaying the menu. The user can
* choose from the following options:
* 1) Show Train Line
* 2) Add Train Car
* 3) Update with Debug Info
* 4) Show Station Details
* 5) Make Test Line
* 6) Make Custom Line
* 0) Quit
* 1) Displays the train line at that point in time. Implemented using
* the strategy pattern. 2) Adds a cautious, normal, or rushhour
* car to the start station. The different behaviors of the cars were
* implemented using the strategy pattern. 3) Updates the location of
* the cars depending on their speed and the station they are at. The order
* of updates occurs in only one direction. 4) Displays only station
* information. 5) Adds on a station with release time 1.5 to the current
* line. 6) Make a new line and replace the old one with it. Add on
* as many stations as needed.
*
* @KnownBugs None
*
* @To_Do None
*
* Note: Use original set of tests
"""
from soares_raiza import Line
from soares_raiza import Strategycartypes
from soares_raiza import Timestation
from soares_raiza import StationClass
"""
/***********************************************************************
* Class: Main
* author: Raiza Soares
* Description: Has a meu that a user can pick from and does
* specific tasks based on the options chosen. Always reprints the menu
* until the user quits the program. Handles bad input.
**********************************************************************/
"""
def main():
menu = "\n" \
"1) Show Train Line\n" \
"2) Add Train Car\n" \
"3) Update with Debug Info\n" \
"4) Show Station Details\n" \
"5) Make Test Line \n" \
"6) Make Custom Line \n" \
"0) Quit\n"
templine = Line.L()
choice = -1
while choice != 0:
print(menu)
stopmins = ""
try:
choice = input("Choice: ")
# strips out blank lines in input
while choice == '':
choice = input()
if choice == '1':
templine.prints()
for i in templine: # GRADING: LOOP_ALL
print(i)
elif choice == '2':
carType = input("Which type: 0-->Cautious, 1-->Normal, 2-->Rush hour: ")
if carType.isnumeric() and int(carType) < 3 and int(carType) >= 0:
# GRADING: SET_BEHAVIOR
if carType == '0':
c = Strategycartypes.Cautious()
elif carType == '1':
c = Strategycartypes.Normal()
else:
c = Strategycartypes.Rushhour()
templine.addcar(c)
else:
print("Invalid Option")
elif choice == '3':
templine.update()
templine.printtime()
for i in templine:
print(i)
elif choice == '4':
for i in templine.callStationIter(): # GRADING: LOOP_STATION
print(i)
elif choice == '5':
statone = Timestation.TimeSt("1", 1.5)
templine.addStation(statone)
elif choice == '6':
templine = Line.L()
print("Number of stations: ")
numstations = input()
if numstations.isnumeric():
for i in range(int(numstations)):
print("----Station " + str(i + 1) + "----\n Length of stop time in minutes: ", end="")
stopmins = input()
stopmins= float(stopmins)
if stopmins > 0 and stopmins % 0.5 == 0:
if i != int(numstations) - 1:
n = input(" Name of station: \n")
else:
n = input(" Name of station: ")
templine.addStation(Timestation.TimeSt(n, stopmins))
else:
print("Stop time must be positive and an increment of 0.5 min. Got: " + str(stopmins))
else:
print("Invalid Option")
elif choice == '0':
choice = 0
else:
print("Invalid Option")
except ValueError:
print("Stop time must be a number. Got: " + str(stopmins))
if __name__ == '__main__':
main()
|
# You are given three integers: a, b, and m. Print two lines.
# On the first line, print the result of pow(a,b). On the second line, print the result of pow(a,b,m).
# Enter your code here. Read input from STDIN. Print output to STDOUT
import math
a = int(input())
b = int(input())
m = int(input())
print(pow(a,b))
print(pow(a,b,m))
# Enter your code here. Read input from STDIN. Print output to STDOUT
# Task
# Read four numbers, and print the result of a^b + c^d
# Input Format
# Integers are given on four separate lines, respectively.
import math
a = int(input())
b = int(input())
c = int(input())
d = int(input())
print(pow(a,b) + pow(c,d))
|
import sqlite3
from sqlite3 import *
connexion = sqlite3.connect("game.db")
curseur = connexion.cursor()
data = curseur.execute("SELECT * from Map;")
table = []
for row in data:
ligne = {
'name': row[1],
'nbuse':row[3],
'path':row[2]
}
table.append(ligne)
print(table[0].name)
|
array = [10,9,8,7,6,5,4,3,2,1,11,12,13,16,15,14,17,19,18,20]
n = len(array)
for i in range(1,n):
print(array)
insertedValue = array[i]
nextIndex = i - 1
while nextIndex >= 0:
if insertedValue < array[nextIndex]:
array[nextIndex+1] = array[nextIndex]
else:
break
nextIndex -= 1
array[nextIndex + 1] = insertedValue
print(array) |
# f = open("input.txt", 'r')
# line = f.readline()
line = input()
num = int(line)
array = []
for i in range(num):
# line = f.readline()
line = input()
if not(line in array):
array.append(line)
array = sorted(array)
array = sorted(array, key=lambda x:len(x))
for i in array:
print(i)
|
from collections import defaultdict
import collections
# This class represents a directed graph using adjacency
# list representation
class Graph:
# Constructor
def __init__(self):
# default dictionary to store graph
self.graph = defaultdict(list)
# function to add an edge to graph
def addEdge(self,u,v):
self.graph[u].append(v)
# The function to do BFS traversal. It uses
def BFS(self,N,M,start):
visited=[[False for i in range(M)] for j in range(N)]
dist=[[0 for i in range(M)] for j in range(N)]
queue=collections.deque()
queue.append(start)
visited[start[0]][start[1]] = True
dist[start[0]][start[1]] = 1
while queue :
s= queue.popleft()
if s in self.graph:
for i in self.graph[s] :
if visited[i[0]][i[1]] == False:
dist[i[0]][i[1]] = dist[s[0]][s[1]] + 1
queue.append(i)
visited[i[0]][i[1]] = True
print(dist[N-1][M-1])
g = Graph()
# f = open("input.txt", 'r')
# line = f.readline()
line = input()
N, M = line.split(" ")
N, M = int(N) , int(M)
array=[[0 for i in range(M)] for j in range(N)]
for i in range (N):
# line = f.readline()
line = input()
for j in range (M):
array[i][j] = int(line[j])
for i in range (N):
for j in range (M):
if j-1>-1 and array[i][j-1]:
g.addEdge((i,j),(i,j-1))
if i-1>-1 and array[i-1][j]:
g.addEdge((i,j),(i-1,j))
if j+1<M and array[i][j+1]:
g.addEdge((i,j),(i,j+1))
if i+1<N and array[i+1][j]:
g.addEdge((i,j),(i+1,j))
# f.close()
g.BFS(N,M,(0,0))
|
import unittest
import magic_sauce
import os
class HighestSuitibilityScoreTest(unittest.TestCase):
# Read in test input file
def setUp(self):
test_input_file_dir = os.path.join(os.getcwd(), "TestInputFiles")
self.simple_customer_input = os.path.join(test_input_file_dir, "simple_customer_input.txt")
self.test_input_1 = os.path.join(test_input_file_dir, "test_input1.txt")
def tearDown(self):
pass
def test_taking_input_file_and_return_highest_SS_score_per_case(self):
#loop through the amount of test cases there are
for test_case in magic_sauce.seperate_test_cases(self.test_input_1):
evaluation = magic_sauce.eval_test(test_case)
print("Overall Score is: {0:.2f}".format(evaluation[0]))
print("Here is the list of top scores: ")
print(evaluation[1])
self.fail('Finish functional test')
# A Test to take in a simple input file of one customer and 3 products, and seeing what
# product has the highest score for the customer.
def test_one_customer_and_three_products(self):
#read in the file.
file_data = magic_sauce.read_file(self.simple_customer_input)
# Get list of customers
customers = magic_sauce.get_customers(file_data)
# Get list of products
products = magic_sauce.get_products(file_data)
highest_score = 0
highest_product_name = ""
#Pass in file string into single SS calculator
for customer in customers:
for product in products:
score = magic_sauce.single_SS_eval(customer, product)
if score > highest_score:
highest_score = score
highest_product_name = product
# return the highest score
print(str(highest_score) + " " + product)
def test_best_customer_per_product(self):
file_data = magic_sauce.read_file(self.simple_customer_input)
customers = magic_sauce.get_customers(file_data)
products = magic_sauce.get_products(file_data)
for product in products:
pass
if __name__ == '__main__':
unittest.main(warnings='ignore') |
# implementation od BFS algorithm in python
graph = {
'A' : ['B','C'],
'B' : ['D', 'E'],
'C' : ['F'],
'D' : [],
'E' : ['F'],
'F' : []
}
visited=[]
queue=[]
def bfs(visited,graph,source):
visited.append(source)
queue.append(source)
while queue:
s=queue.pop(0)
print(s,end=' ')
for node in graph[s]:
if node not in visited:
visited.append(node)
queue.append(node)
bfs(visited,graph,'C') |
'''
Binary Search in python
'''
import random
import sys
sys.setrecursionlimit(150000)
def binarysearch(list,l,h,key):
if h>=1:
mid=(h-l)//2
if list[mid]==key:
return mid
elif list[mid]>key:
return binarysearch(list,l,mid-1,key)
else:
return binarysearch(list,mid+1,h,key)
else:
return -1
arr=arr = [ 2, 3, 4, 10, 40 ]
res=binarysearch(arr,0,len(arr)-1,10)
if res ==-1:
print("elment not found")
else:
print("elemet found at",res) |
from random import randint
class ChuteNumero:
def __init__(self):
self.ranking = []
self.iniciar()
def iniciar(self):
continuar_brincando = True
while continuar_brincando:
self.numero_aleatorio = randint(0, 1000)
self.chute()
decisao = input('Quer brincar novamente? S/N')
if decisao in 'Nn':
continuar_brincando = False
def chute(self):
chute_incorreto = True
quantidade_chutes = 0
while chute_incorreto:
try:
print('De o seu chute, meu caro apedeutinha...')
chute = int(input('Dica, o número está entre 0 e 1000, fala aí qualé...'))
if chute == self.numero_aleatorio:
self.ranking.append(quantidade_chutes)
print(f'Parabéns, apdeuta, você acertou! levou {quantidade_chutes} para acertar')
self.mostrar_ranking(quantidade_chutes)
chute_incorreto = False
else:
quantidade_chutes += 1
if chute > self.numero_aleatorio:
print('Tente um número menor')
else:
print('Tente um número maior')
except ValueError:
print('Tente apenas números entre 0 e 1000')
def mostrar_ranking(self, quantidade_chutes_jogador_atual):
print(f'Melhor pontuação: {min(self.ranking)}')
print(f'Pior pontuação: {max(self.ranking)}')
self.ranking.sort()
for posicao in self.ranking:
if posicao == quantidade_chutes_jogador_atual:
print(f'Você está aqui: {posicao}')
else:
print(f'Posição: {posicao}') |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.