text stringlengths 37 1.41M |
|---|
import math
class Polygon:
def __init__(self, n, radius):
self.n = n
self.r = radius
@property
def edges(self):
return self.n
@property
def vertices(self):
return self.n
@property
def int_angle(self):
return 180 * ((self.n - 2) / self.n)
@prop... |
import numpy as np
class Solution:
def isPalindrome(self, x: int) -> bool:
# edge cases
if x < 0 or (x % 10 == 0 and x != 0):
return False
backwards_x = 0
while backwards_x < x:
backwards_x = backwards_x * 10 + (x % 10) # Build up the backwards number
... |
print('verificar par o impar')
print('digite el numero')
NunmeroParaAnalizar=int(input()) #pregunta valor
# int convierte string a entero
#print('El numero introducido es:'+NunmeroParaAnalizar)
print(f'el numero introducido es: {NunmeroParaAnalizar}')
if NunmeroParaAnalizar<0:
print('El numero debe ser posit... |
def menor_de_cinco(numero1:int,numero2:int,numero3:int,numero4:int,numero5:int)->str:
numeromenor=min(numero1,numero2,numero3,numero4)
numeroi=max(numero1,numero2,numero3,numero4)
if (numeroi>numero5):
return f'El numero {numeroi} es mayor al {numero5}'
if (numeromenor<numero5):
re... |
class student():
student_count = 0
def __init__(self, name, age, sex):
self.name = name
self.age = age
self.sex = sex
student.student_count = student.student_count + 1
def total_students(self):
print('total count is : ', student.student_count)
def student_details(... |
class Person:
def __init__(self, first, last, age):
self.firstname = first
self.lastname = last
self.age = age
def __str__(self):
return self.firstname + " " + self.lastname
class Student(Person):
def __init__(self, first, last, age):
super().__init__(first, last,... |
dict = {}
n = int(input('enter the length of the dictionary'))
for i in range(n):
dict[i+1] = (i+1)*(i+1)
print(dict) |
import math
import random
guess = input('enter the guess number ')
g = int(guess)
n = random.randint(0,9)
if g == n:
print('your guess ',g,' is right')
elif g < n:
print('your guess ',g,' is less than ',n)
elif g > n:
print('your guess ',g,' is greater than ',n) |
"""Description
Locate all repeating numbers in a given number of digits. The size of the number that gets repeated should be more than 1. You may either accept it as a series of digits or as a complete number. I shall explain this with examples:
11325992321982432123259
We see that:
321 gets repeated 2 times
32 gets ... |
# -*- coding: utf-8 -*-
"""
Created on Wed Mar 3 13:21:33 2021
@author: Роман
"""
answer=int(input('Введите время в секундах:'))
an_hours=answer//3600
an_minutes=(answer-(an_hours*3600))//60
an_seconds=(answer-(an_hours*3600)-(an_minutes*60))
print(f'Общее время: {an_hours} чч {an_minutes} мм {an_seconds} cc') |
import sys
import copy
#Function to test a particular bit of a given int_type is 0 or 1
def testBit(int_type, offset,size):
offset = offset - (size - int_type.bit_length())
if(offset < 0):
return 0
mask = 1 << offset
val = (int_type & mask)
if val:
return val >> (val.bit_length() - 1)
else:
return val
... |
# Ejercicio 8:
# Escribir un programa que permita ingresar las coordenadas (x,y) de un punto en el plano y
# verifique si el punto está dentro del círculo con centro en (0,0) y radio 10, o está fuera o en
# la circunferencia. Mostrar los mensajes adecuados.
CordenadaX = 10
CordenadaY = 1
if CordenadaX > 10 or Cordena... |
# Ejercicio 6:
# Escribir un programa que permita ingresar tres números enteros y escribirlos en orden
# creciente.
Numeros = [5 , 4, 20, 28, 93, 12, 3, 1]
Numeros.sort(reverse=True)
print (Numeros)
|
# Enter a file name
name = input("Enter a file name :")
# Converting to lower case in order to cater for both upper and lower cases
name = name.lower()
# For valid / defined file names
if name == 'measles.txt':
handle = open(name)
count = 0
for lines in handle:
count = count + 1 # Counting the nu... |
str = "banana"
sub = "a"
d = str.count(sub)
print("The letter 'a' appears", d, 'times in ', str)
|
# This program is for calculating the amount of money to be paid by a customer basing on his/her meter readings and
# his code.
print("======================RESTART==============================")
print("...........You are most welcome our dear customer.......... ")
while True:
# Customer's details
a = str(... |
##program01.py - Dice Roller
import random
try:
minDiceValue = int(input('Enter the minimum value of the die: '))
maxDiceValue = int(input('Enter the maximum value of the die: '))
except:
print('One of the values you have entered is invalid. The dice roller will return to the default values of 1-6')
... |
import turtle # python needs this to use all the turtle functions
t2=turtle.Turtle()
turtle.speed(0)
turtle.shape('turtle') # changes the shape to a turtleturtle.
turtle.bgcolor("purple")
turtle.color("white")
turtle.penup()
turtle.goto(-100,0)
turtle.pendown()
turtle.goto(-100,150)
turtle.color("yellow")
turtle.goto(0... |
print("i think of a number between 1-100 guess the number ")
import random
number = random.randint(1,100)
guess=int(input("guess"))
if guess < number:
print ("to low")
if guess > number:
print("to hgih")
while not guess==number:
guess=int(input("guess"))
if guess < number:
print ("to low")
if... |
letters = "abcdefghijklmnopqrstuvwxyz"
print('letters = "abcdefghijklmnopqrstuvwxyz"')
backwards = letters[25:0:-1]
print(backwards)
print()
print("To print above string value in reverse order: letters[25::-1]")
backwards = letters[25::-1]
print(backwards)
print()
print("To print above string value in reve... |
parrot = "Norwegian Blue"
# To print 5 characters starting from first character
print("parrot[0:6] : " + parrot[0:6])
print("parrot[3:5] : " + parrot[3:5])
print()
print("parrot[0:9] : " + parrot[0:9]) #both are same
print("parrot[:9] : " + parrot[:9]) #both are same
print()
print("parrot[:9] : " ... |
import json
from typing import NamedTuple, List
FILE_NAME = "high_score.json"
class Score(NamedTuple):
name: str
value: float
def save_score(score: Score):
with open(FILE_NAME, "r") as file_handle:
scores = json.load(file_handle)
scores.append({"name": score.name, "value": score.value})... |
#---------------------------------------------------
# Program:
# Checkpoint 02b, File Reading
# Brother Mellor, CS241
# Author: ... |
# coding: utf-8
# In[17]:
#Exercise 148:Sum a List of Numbers
line = input("Enter a number:")
total = 0
while line != "":
try:
num = float(line)
total = total + num
except ValueError:
print("Not a number")
line = input("Enter a number:")
print("The grand total is %... |
import sqlite3
import pandas as pd
con = sqlite3.connect('database.sqlite')
cur = con.cursor()
print("Names of both the Home Teams and Away Teams in each match played in 2015 and FTHG = 5 : ")
print(con.execute("Select HomeTeam,AwayTeam from Matches where Season ='2015' and FTHG ='5'").fetchall())
print("Detail... |
import random
from graphics import *
win = GraphWin("Jackpot",300,300)#Creates the graphics window
# rules
'''
- Display 3 cells in a row
- display button
- when user clicks button, randomly draw shapes in each cell (8 choices)
- square
- circle
- diamond
- triangle
- 4 text choices
- if a... |
from time import *
import math
# A perfect number is a number for which the sum of its proper divisors is exactly equal to the number. For example, the sum of the proper divisors of 28 would be 1 + 2 + 4 + 7 + 14 = 28, which means that 28 is a perfect number.
# A number n is called deficient if the sum of its proper di... |
from time import *
import math
# Using names.txt (right click and 'Save Link/Target As...'), a 46K text file containing over five-thousand first names, begin by sorting it into alphabetical order. Then working out the alphabetical value for each name, multiply this value by its alphabetical position in the list to obta... |
from time import *
import math
# The sequence of triangle numbers is generated by adding the natural numbers. So the 7th triangle number would be 1 + 2 + 3 + 4 + 5 + 6 + 7 = 28. The first ten terms would be:
# 1, 3, 6, 10, 15, 21, 28, 36, 45, 55, ...
# Let us list the factors of the first seven triangle numbers:
# 1: ... |
#!python
problem = """
A palindromic number reads the same both ways.
The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 x 99.
Find the largest palindrome made from the product of two 3-digit numbers.
"""
##
print(problem)
x = 10000
y = 10000
maxx = 0
while x < 99999:
while y < 10... |
#!python
problem = """
The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17.
Find the sum of all the primes below two million.
https://projecteuler.net/problem=10
"""
print(problem)
top = 2000000
primeset = [2,3]
possibles=[]
x=3
while x < top:
possibles.append(x)
x+=2
p=3
while (len(possibles)) > 0:
zo... |
# coding: utf-8
# In[1]:
os.chdir('/Users/chrisrappoli/Documents/Coding/dataScience/introToDS')
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
get_ipython().magic('matplotlib inline')
plt.style.use('ggplot')
# In[2]:
filename = 'turnstile_data_master_with_weather.csv'
path = './data/'
... |
import socket
def get_IP():
try:
ip_address=socket.gethostbyname(socket.gethostname())
print("Your IP Address is:" , ip_address)
except:
print("Please check your Network connection")
get_IP() |
""""2.if문을 이용해 첫번째와 두번 수, 연산기호를 입력하게 하여 계산값이 나오는 계산기를 만드시오
예시
<입력>
첫 번째 수를 입력하세요 : 10
두 번째 수를 입력하세요 : 15
어떤 연산을 하실 건가요? : *
<출력>
150
"""
def calculator():
x = input("첫 번째 수를 입력하세요 : ")
y = input("두 번째 수를 입력하세요 : ")
z = input("어떤 연산을 하실 건가요? : ")
if z == '+':
result = int(x) + int(y)
eli... |
class minHeap:
def __init__(self):
self.list = [0]
self.size = 0
def insert(self,data):
self.list.append(data)
self.size += 1
self.perc_up(self.size)
def perc_up(self,i):
parent = i//2
while parent > 0:
if self.list[i]<... |
#1 ַɸģַб
print list('hello');
#2 ı
num = [1, 2, 3, 4]
num[2] = 100
del num[0]
print num;
|
import pandas as pd
import matplotlib.pyplot as plt
# This is a python script for creating visualization of sales changes per month to see if month is a variable
# we would like to subset the data by.
df = pd.read_csv("/Users/kaihung/Desktop/Rice/Data Science/Chevron_2021_Datathon_Challenge/filesForStartOfDatathon/t... |
from Order import Order
# recebe o nome do estabelecimento
def get_Supermarket():
supermarket = input("Qual o nome do Estabelecimento? ")
return supermarket
# recebe uma quantidade (int) de produtos.
def get_amount():
while True:
try:
amount = int(input("Qual a quantidade de produtos n... |
numero = input("Digite seu número de celular:")
if len(numero) == "9" and numero[0] == "9":
print("Número cadastrado com sucesso")
else:
print("Número inválido! Digite novamente") |
# Input: nums = [1,2,3,4]
# Output: [1,3,6,10]
# Explanation: Running sum is obtained as follows: [1, 1+2, 1+2+3, 1+2+3+4].
def func(n):
output=[]
cntr=0
for i in n:
cntr=cntr+i
output.append(cntr)
return output
print(func(n=[1,2,3,4])) #Output: [1,3,6,10]
# https://lee... |
#********************************************************************
# Filename: MergeSort.py
# Author: Javier Montenegro (https://javiermontenegro.github.io/)
# Copyright:
# Details: This code is the implementation of the merge sort algorithm.
#*******************************************************************... |
# EJERCICIO 1
b=0
numeros_enteros = list()
while b < 100000:
numeros_enteros.append(b)
b=b+1
print(numeros_enteros)
numeros_enteros_pares = list()
numeros_enteros_nones = list()
for x in numeros_enteros:
if (x % 2) == 0:
numeros_enteros_pares.append(x)
else:
numeros_enteros_nones.appe... |
def find_outlier(integers):
odds = []
evens = []
for i in integers:
[evens.append(i) if i % 2 == 0 else odds.append(i)]
if len(evens) > len(odds):
return odds[0]
else:
return evens[0]
print(find_outlier([2, 4, 0, 100, 4, 11, 2602, 36]))
#Should return: 11 (the only od... |
from functools import reduce
import operator
number_list = range(-5,5)
#find the sum of list
print(reduce(lambda a,b:a+b, number_list))
print(reduce(operator.add,number_list))
#find max element
print(reduce(lambda a, b : a if a > b else b,number_list))
# filter creates a list of elements for which a function returns t... |
#Example 0
def sample():
print("Sample")
def pass_within_sample():
print("Inside Sample")
sampleDecorator = sample()
print(sampleDecorator)
#Example 0.1
def sample1(pass_within_sample1):
print("Sample 1")
return pass_within_sample1()
def pass_within_sample1():
print("Inside Sample 1")
c... |
set1 = {"John","Ravi", "Ravi", "Anil",("WPF","MOngoDB","Python") }
set2 = {"John","Ravi", "Solanki", "Singh",'Snow' }
#Add Elements
set1.add("Vikash")
#Remove element
set1.pop() # removes a random value
set1.discard("Solanki") #remove if found, else do nothing
set1.remove("Ravi")
#update set1 : Add all ements of set2 t... |
#Question 1
class A:
def __init__(self):
print(1)
class B(A):
def init(self):
super().__init__()
print(2)
obj = B()
#Question 2
class C:
def __init__(self):
print(1)
class D(C):
def __init__(self):
super().__init__()
print(2)
obj = D()
#Question 3
class ... |
isITPositive = -1
# if (isITPositive > 0):
# if(isITPositive == 5):
# print("Yesssssa")
# else:
# print("It is Positive but It is not 5. :(")
# elif(isITPositive == 0):
# print("It is Zero")
# else :
# print(":( It is Negative")
print(":( It is Negative") if isITPositive < 0 else ( print("It is Zero") if is... |
firstNum = 3
secondNum = 5
#Is Equal To
print("Is Equal To :",firstNum == secondNum)
#Is Not Equal To
print("Is Not Equal To",firstNum != secondNum)
#Is Greater Than
print("Is Greater Than",firstNum > secondNum)
#Is less Than
print("Is less Than",firstNum < secondNum)
#Is Greater Than Equal To
print("Is Greater Th... |
# Given an integer array, output all pairs that sum up to a specific value k.
arr=[2,5,3,2,4,5,1,4,6,7,7,8]
def pairSum2(arr, k):
if len(arr)<2:
return
seen=set()
output=set()
for num in arr:
target=k-num
if target not in seen:
seen.add(num)
else:
... |
#Introduction of Inheritence - How to inherit parent class
class Employee:
def __init__(self,firstName,lastName):
self.firstName = firstName
self.lastName = lastName
def FullName(self):
return self.firstName + " " + self.lastName
class Developer(Employee):
pass
class Designer(Employ... |
# coding: utf-8 出力はjson形式で 入力=音声のテキストファイル 画像認識のテキストファイル(物体5候補、らしさ5,動作)
import csv
import json
import re
import sys
import math
import random
#csvファイルの辞書化
def Csv_to_dict(mycsv):
mydict = []
with open(mycsv,"r") as f:
reader = csv.DictReader(f)
for row in reader:
mydict.append(ro... |
def app():
docs = ReadFile("../ap_docs.txt")
search = []
option = 0
while option != 3:
print ("What would you like to do?")
print ("1. Search for documents")
print ("2. Read Document")
print ("3. Quit program")
option = input(">")
if int(option) == 1:
... |
numbers = [1,6,8,9,2,1,7,9,6,1,2,9]
print (numbers)
n = int(input("Enter a number: "))
# cach 1 (with 'count')
appearance = numbers.count(n)
print(n, "appears", appearance, "times in my list.")
# cach 2 (without 'count')
freq = sum(freq == n for freq in numbers)
print ("{0} appears {1} times in my list.".format(n... |
from turtle import *
def draw_star(x, y, length):
penup()
goto(x,y)
pendown()
for i in range (5):
forward(length)
right(144)
draw_star(-94, 160, 150)
mainloop() |
# 1. Download webpage
from urllib.request import urlopen
from bs4 import BeautifulSoup
url = "http://dantri.com.vn/"
# 1.1 Open a connection
conn = urlopen(url)
# 1.2 Read data
data = conn.read()
# 1.3 Decode
html = data.decode("utf_8")
# print(html)
# cach tat:
# html = urlopen("http://dantri.com.vn/").read().de... |
menu = ["Kem", "Xoi", "Pho", "Thit", "Tao pho"]
# print(*menu, sep=",")
# print(len(menu))
# menu.append("Che")
# print(*menu, sep=", ")
# print(len(menu))
# print("Hi there, here your favorite channel so far?")
# menu = ["deathnote", "netflix", "fox", "worldcup"]
# print (*menu, sep=", ")
# y = input("wanna add? ... |
from random import randint
y = randint(0,100)
count = 0
while True:
guess = int(input("Any number? "))
if y < guess:
print ("a little too large")
elif y > guess:
print ("a little too small")
elif y == guess:
print ("BINGOOOO")
playing = False
count += 1
... |
def is_inside(point, rec):
Bx = point[0]
By = point[1]
rec_x = rec [0]
rec_y = rec [1]
width = rec [2]
height = rec [3]
if (rec_x + width) > Bx > rec_x and (rec_y + height) > By > rec_y:
return True
else:
return False
point_inside = is_inside([200,250],[140,60,100,200])... |
from turtle import*
shape("arrow")
color("black", "yellow")
begin_fill()
for i in range (4):
forward(200)
left(90)
end_fill()
mainloop()
from turtle import*
shape ("arrow")
color("black" , "yellow")
begin_fill()
for i in range (3):
forward(200)
left(120)
end_fill()
mainloop()
from turtle import*
shape... |
import calendar
m,d,y=map(int,input().split())
a=list(calendar.day_name)
b=calendar.weekday(y,m,d)
print(a[b].upper()) |
def validator(s):
print(any(char.isalnum() for char in s))
print(any(char.isalpha() for char in s))
print(any(char.isdigit()for char in s))
print(any(char.islower()for char in s))
print(any(char.isupper()for char in s))
s=input()
result=validator(s)
|
#!/usr/bin/python
# download weather station data from Wunderground
import urllib2 # retrieve data from URL (Python 2.x)
import sys # command line argument parsing
import os # call external shell script
from datetime import datetime, timedelta # date stuff
wdir="/home/pi/"
y = datetime.now() - timedelta(1... |
#lista jednokierunkowa
class Value:
def __init__(self, value):
self.value = value
self.next = None
def return_value(self):
return self.value
def return_next(self):
return self.next
def update_next(self, value):
self.next = value
class List(V... |
# -*- coding: utf-8 -*-
"""
Created on Thu Sep 6 10:29:12 2018
@author: Luis Palomino
"""
## Assumes the array is ordered
def binarySearch(x, n):
if len(x) == 1:
return x[0] == n
mid = len(x)//2
if x[mid] == n:
return True
if n > x[mid]:
return binarySearch(x[mid:len(x)], n)
... |
# -*- coding: utf-8 -*-
"""
Created on Fri Sep 7 00:43:29 2018
@author: Luis Palomino
"""
class LinkedList:
def __init__(self):
self.head = None
self.size = 0
def add(self, val):
self.size += 1
newNode = Node(val)
newNode.setNext(self.head)
self.h... |
# -*- coding: utf-8 -*-
"""
Created on Mon Aug 20 10:43:58 2018
@author: Luis Palomino
"""
import math
import matplotlib.pyplot as plt
import time
# Reto 1
# Worst Case Time Complexity: O(2^n)
def numFibonacci(n):
if n == 1:
return 1
elif n == 0:
return 0
else:
return numFibonacci(... |
# -*- coding: utf-8 -*-
"""
Created on Mon Aug 20 10:11:51 2018
@author: Luis Palomino
"""
"""
Ejercicios de Tarea
"""
# Escribe una función que sume acumulativamente
def cumSum(n):
if (n == 1):
return 1;
return n + cumSum(n-1)
# Sumar toos los digitos de un entero
def digitSum(number):
# Ch... |
class Node:
def __init__(self):
self.val = None
self.next = None
class queue:
def __init__(self):
self.top = Node()
self.top.next = None
def enqueue(self, x):
N = Node()
N.val = x
if queue.is_empty(self):
self.top.next = N
else:
... |
# Zadanie 1. (problem sumy podzbioru) Dana jest tablica n liczb A. Prosze podac i zaimplementowac
# algorytm, który sprawdza, czy da sie wybrac podciag liczb z A, które sumuja sie do zadanej wartosci T.
def sum(A, T, suma, i):
if suma == T: return True
while i+1 < len(A):
return sum(A, T, suma + A[i], ... |
def partition(tab,p,r):
x = tab[r]
i = p-1
for j in range (p,r,1):
if tab[j]<=x:
i=i+1
tab[i],tab[j]=tab[j],tab[i]
tab[i+1],tab[r]=tab[r],tab[i+1]
return i+1
def quicksort(tab,p,r):
if p<r:
q=partition(tab,p,r)
quicksort(tab,p,q-1)
quicks... |
valor = 0
try:
print("Início do bloco try")
print("Calculando valor")
valor = 3/0
print("Fim do bloco try")
except Exception as exp:
print(exp)
else:
print("Início do bloco else")
print("O resultado é ", valor)
print("Fim do bloco else")
finally:
print("Bloco finally")
|
"""def somar(a, b):
return a + b
x = lambda a, b: a + b
#print(x(43, 11))
print(somar)
print(x)"""
def calcular(num1, num2, funcao):
return funcao(num1, num2)
def multiplicar(x, y):
return x * y
print(calcular(30, 20, lambda a, b: b - a)) |
people = 20
cats = 30
dogs = 15
if people < cats:
print("people < cats")
if people > cats:
print("people > cats")
if people < dogs:
print("people < dogs")
if people > dogs:
print("people > dogs")
dogs += 5
if people <= dogs:
print("people <= dogs")
if people >= dogs:
print("people >= dogs")
i... |
#!/usr/bin/env python3
import sys
sys.path.append('./py')
from numbers import Number
from vector import Vector
from multivector import MultiVector
class GA:
"""GA(n) -> the rank-n geometric algebra with floating point coefficients
Example:
>>> ga = GA(3)
>>> x = 3 + ga[1] + 2*ga[2] - 2*ga[3] + ga[1,... |
def main():
# natural_numbers_cubic = [];
# by_three_numbers = [];
# for natural_number in range(1, 101):
# natural_numbers_cubic.append(natural_number ** 2);
# if (natural_number % 3 != 0):
# by_three_numbers.append(natural_number ** 2);
# print("natural_numbers_cubic:", natural_numbers_cubic);... |
entrada = int(input("Ingrese un número para generar patrón\n"))
linea = ''
for i in range(1, entrada+1):
linea = linea+str(i)
print(linea)
|
from sys import argv
precio = float(argv[1])
numUsuarios = int(argv[2])
gastos = float(argv[3])
if len(argv) == 5:
utilidadesAnoAnterior = float(argv[4])
else:
utilidadesAnoAnterior = 1000
# print("precio: " + str(precio))
# print("numUsuarios: " + str(numUsuarios))
# print("gastos: " + str(gastos))
# print(... |
# def letra_x(ancho):
# N = ancho
# for i in range(N):
# for j in range(N):
# if (i == j) or ((N - j - 1) == i):
# print('*', end='')
# else:
# print(' ', end='')
# print('')
def letra_x(ancho):
N = ancho
salida = ''
for i in ... |
def prostoe(a):
"""Функция проверяет является ли число простым
Args:
a (int): число проверяемое на простоту
Returns:
string: сообщаем является ли число простым
"""
deli = 2
sch = 0
while deli < a:
if a % deli == 0: # как только находится ещё одно число кроме 1 и a ... |
# пятое задание из пятой домашки
text = print('Для выхода напишите "Bыход" ')
while text != 'выход':
text = input('Введите текст пожалуйста: ')
text = text.lower()
slov = list(map(lambda x: {x: text.count(x)}, set(text)))
slov = str(slov)
slov = slov.replace(
'}',
'').replace(
... |
import random
def xor_encryption(chek):
""" Функция xor шифрования
Args:
chek ([type]): [description]
Returns:
При успешном выполнении пишет результат в файл, иначе 0
"""
text = read_from_file()
if chek == 1:
key = input("Введите ключ (Enter - ключ сгенерируется автома... |
'''
File to scrape the total number of document reads and profile views of the
members of a given institution of each of Instituto Politécnico do Porto's
(IPP) schools, through Academia.edu.
This script is by no means an API to Academia.edu, since it was specifically
created to scrape information about authors affilia... |
'''
opening http://localhost:8080/restaurants lists all the restaurants in the database
'''
from http.server import BaseHTTPRequestHandler, HTTPServer
import cgi
# import CRUD Operations from Lesson 1
from database_setup import Base, Restaurant, MenuItem
from sqlalchemy import create_engine
from sqlalchemy.orm import... |
import urllib.request
import json
def check_weather(city):
"""Function that finds the current weather info for Coventry"""
# fetches the JSON data from API
with urllib.request.urlopen(
'http://api.apixu.com/v1/current.json?key=da55ba7713f54de3a28113313172211&q=' + city) as webPage:
... |
# pip3 install unittest
# python3 -m unittest lesson.py
import unittest
def sum_sq(i, j):
return i * i + j * j
class SumSqTestCase(unittest.TestCase):
pass
def setUp(self):
pass
def tearDown(self):
pass
def test_equal(self):
self.assertEqual(sum_sq(2, 3), 13)
if __n... |
def main ():
get_name ()
print("Hellow", name)
def get_name():
name = input ("Enter your name: ")
main() |
ticket_A = int(input("Enter total amount of A Tickets sold: "))
ticket_B = int(input("Enter total amount of B Tickets sold: "))
ticket_C = int(input("Enter total amount of C Tickets sold: "))
class_a = 20 * ticket_A
class_b = 15 * ticket_B
class_c = 10 * ticket_C
print("Total Amount for Seating A")
print("-----------... |
## An example of python variables and what they can do
## Integers, float (decimals) can perform mathematical computations + - * /
my_integer = 1 + 2
print(my_integer)
## Strings are a string of characters. Do note that characters can include spaces and symbols
# my_string = "Hello World"
# print(my_string)
## Stri... |
from typing import List
from typing import Optional
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def is_num(self, s: str):
try:
float(s)
return True
except V... |
#OUTPUT- line A \n line B
print("line A \\n line B")
#OUTPUT- \" \'
print("\\\" \\\'")
#NOTE
#\\ makes \ and \" makes " and \' makes '
#OUTPUT- line A \t line
print("line A \\t line B")
#OUTPUT- to print 4 backslash
print("these are 4 backslash \\\\\\\\")
#OUTPUT- to print 2 backslash
print("these ... |
#step argument ka use step wise character print krne k liye hota h
#jaise ki agr string h "vaibhav"
#to isme agr hum step argument 1 lete h to yeh as it is print krdega
#but agr hum 2 lete h to yeh "vihv" print karega
#agr hum 3 lete h to yeh "vbv" print karega
"""name[start argument:stop argument:step argument]... |
name=input("whats your name ")
print("Hello "+name)
age=input("whats your age ")
|
'''
Samuel Pedro Campos Sena - EF3494
Trabalho prático 1 - CCF480 - MetaHeurísticas
'''
'''
Referências utilizadas:
https://machinelearningmastery.com/stochastic-hill-climbing-in-python-from-scratch/. Acesso em: 31 ago. 2021.
https://machinelearningmastery.com/iterated-local-search-from-scratch-in-python/. Ace... |
#Metodo de newton para sistemas não lineares
#By Goto
from __future__ import division
import math
import numpy as np
def f(x):
y = np.zeros(3)
y[0] = 3*x[0] - math.cos(x[1]*x[2]) - (1/2)
y[1] = ((x[0])**2) - 81*(x[1] + 0.1)**2 + math.sin(x[2]) + 1.06
y[2] = math.e**(-x[0]*x[1]) + 20*x[2] + ((10*math.p... |
maze = [[True, True, True, True],
[True, True, True, True],
[False, True, False, True],
[True, False, True, True]]
def navigate_grid(maze):
path = []
check_path(maze, path = path)
return path
def check_path(maze, position = None, path = None, cache = None):
if cache is None:
... |
def is_unique(str):
letter_set = set()
for letter in str:
if letter in letter_set:
return False
letter_set.add(letter)
return True
is_unique("not not")
|
class Recipe:
def __init__(self, name, instructions, ingredients, quantities):
self.name = name.lower()
self.ingredients = [ingredient.lower() for ingredient in ingredients]
self.quantities = quantities
self.instructions = instructions
self.occurrences = 0
def getJSON(self):
return {"name": self.na... |
# This is to verify the string
stg = 'this is some the first string'
stgs= stg.replace('this is some the first string','this is the second string')
print(stgs)
# Use the find() method to you
stg3 ="Vamsi,Vamsi,Vamsi,Vamsi,"
if "Vamsi" in stg3:
print("found it")
stg4 = input("Enter a string\n")
if "Vamsi" in stg4... |
import turtle
import time
turtle.shape("turtle")
turtle.bgcolor("#4DB8FF")
turtle.left(90)
time.sleep(5)
def drawGround(dist):
turtle.left(90)
turtle.width(100)
turtle.color("#663300")
turtle.forward(dist)
turtle.back(dist*2)
turtle.forward(dist)
turtle.width(3)
turtle.color("green")
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.