text stringlengths 37 1.41M |
|---|
#Melhore o jogo do DESAFIO 28 onde o computador vai “pensar” em um número entre 0 e 10. Só que agora o jogador vai tentar adivinhar até acertar, mostrando no final quantos palpites foram necessários para vencer.
from random import randint
import os
n = randint(1, 10)
cont = 1
print(10*'-=-')
print('{:^30}'.format("JOGO... |
"""
Test suite for Leetcode Arrays 101: In-Place Operations
https://leetcode.com/explore/learn/card/fun-with-arrays/511/in-place-operations/
"""
from leetcode.arrays_101.in_place_ops import moveZeros
from leetcode.arrays_101.in_place_ops import sortArrayByParity
from leetcode.arrays_101.in_place_ops import replaceEleme... |
"""
Leetcode Arrays 101: In-Place Operations
https://leetcode.com/explore/learn/card/fun-with-arrays/511/in-place-operations/
"""
from typing import List
def replaceElements(arr: List[int]) -> List[int]:
"""
Replace every element in the array with the greatest element among the
elements to its right, and ... |
"""
Test suite for Leetcode Arrays 101: Accessing Arrays
https://leetcode.com/explore/learn/card/fun-with-arrays/521/introduction/3238/
"""
from leetcode.arrays_101.accessing import findNumbers
from leetcode.arrays_101.accessing import findMaxConsecutiveOnes
from leetcode.arrays_101.accessing import sortedSquares
def... |
def compute(annual_salary, portion_saved, total_cost):
portion_down_payment = 0.25
num_month = 0
monthly_salary = (annual_salary/12.0)
saving = 0
current_savings = 0
r = 0.04
while current_savings < (total_cost * portion_down_payment):
saving = monthly_salary * portion_saved
... |
from ConvertNumbers import Number
num = input('Digite um número: ')
if num != '0':
try:
n = Number(num)
print (n.literal)
except ValueError:
print("Valor inválido")
else:
print("zero")
|
import turtle
brad=turtle.Turtle()
def draw_aquare():
window=turtle.Screen()
window.bgcolor("white")
brad.shape("turtle")
brad.color("white")
brad.speed(5)
brad.setposition(-150, 0)
brad.color("blue")
for i in range(36):
brad.forward(300)
brad.right(120)
i+=1
... |
from random import randint
def arma():
roll = randint(1, 100)
if roll <= 3:
return('Adaga')
elif roll <= 5:
return('Alabarda')
elif roll <= 7:
return('Alfange')
elif roll <= 9:
return('Arco composto')
elif roll <= 12:
return('Arco curto')
... |
import numbers
import numpy as np
from .utils import DEFAULT_SETTINGS
ds = DEFAULT_SETTINGS['geometry']
class Geometry:
"""
Get the model geometry.
"""
def __init__(self, d=ds[0], lx=ds[1], ly=ds[2], lz=ds[3]):
self.d = int(d)
self.lx = lx
self.ly = ly
self.lz = lz
... |
# coding: utf-8
# # Capstone Project 1: MuscleHub AB Test
# ## Step 1: Get started with SQL
# Like most businesses, Janet keeps her data in a SQL database. Normally, you'd download the data from her database to a csv file, and then load it into a Jupyter Notebook using Pandas.
#
# For this project, you'll have to... |
#!/usr/bin/python
#Code partly from https://www.tutorialspoint.com/python/python_database_access.htm
import MySQLdb
def connectAndGetCursor():
# Open database connection
db = MySQLdb.connect("localhost","testuser","pwd","testdb" )
#Get cursor
cursor = db.cursor()
return db, cursor
def executeSQL(sql):
db, cu... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Oct 22 16:35:15 2019
@author: amaury
"""
import usefulFunctions
def main():
"""Main function
Returned the desired tab of the exercise"""
# Read the CSV and get its content
jobOfferList, professionsList = usefulFunctions.readCsv()
... |
def function( x, y):
if x == y:
print('the lists are the same')
else:
print('the lists are not the same')
list_one = [1,2,5,6,2]
list_two = [1,2,5,6,2]
function( list_one, list_two)
list_one = [1,2,5,6,5]
list_two = [1,2,5,6,5,3]
function( list_one, list_two)
list_one = [1,2,5,6,5,16]
list_... |
import random
heads = 0
tails = 0
count = 0
for each in range(0,5000):
coin = random.random()
count += 1
strAttempt = "Attempt: " + str(count) + " Throwing a coin..."
if round(coin) == 1:
heads += 1
strAttempt += " It's heads! ... Got "
else:
tails += 1
strAttempt +=... |
# Classes
# declare a class and give it name User
# instantiate class User
class User(object):
# this method to run every time a new object is instantiated
def __init__(self, name, email):
# instance attributes
self.name = name
self.email = email
self.logged = True
# login method ch... |
import math
print("a)")
# define the functions
def f_a(x):
return math.exp(x) + 2**(-x) + 2*(math.cos(x)) - 6
p0 = 1
p1 = 2
q0 = f_a(p0)
q1 = f_a(p1)
e = 10**(-5) # tolerance
N0 = 41
i = 1
while i <= N0:
p = p1 - q1*(p1-p0)/(q1-q0) # compute p_i
if abs(p-p0) < e:
print("p = ",p," after ",... |
import math
# define the functions
def g(x):
return 5/math.sqrt(x)
p0 = 3
e = 10**(-4) # tolerance
N0 = 41
i = 1
print('\n Steffensen"s Method')
print('\n\n i p\n')
while i <= N0:
p1 = g(p0)
p2 = g(p1)
p = p0 - ((p1 - p0)**2)/(p2-2*p1+p0)
print(' ',i,' ', p)
if abs(p-p0... |
"""
__author__ = Angel Alba-Perez
Identity Crisis, This code will put you in the position of a post
apocalyptic survivor that has just awoken from kryo sleep. You start logging
into the main system as a user to try and figure out what happened.
"""
import random
print("Welcome back to FallenRise Inc., the only... |
n = float(input('Informe a metragem:'))
print('{} metros em centimetros: {:.0f}, em milímetros: {:.0f}'.format(n, (n*100), (n*1000)))
|
n = int (input('Informe um número:'))
print('Antecessor:{}, sucessor:{}'.format(n-1, n+1))
|
sal = float(input('Informe o salário R$'))
if sal > 1250:
au = sal * 0.1
else:
au = sal * 0.15
print('Salário atualizado: R${:.2f}, obteve aumento de: R${:.2f}'.format(au + sal, au))
|
c = float(input('Informe a temperatura em ºC:'))
f = ((9*c)/5)+32
print('{} ºC equilavem a {} ºF'.format(c,f))
|
# User INPUT
# How do we get an input from the user?
input()
# For example, you can ask the user what's their name
input("What is your name? ")
# We add a space after the question so there's a space in between the
# prompt and user's answer/input.
# Alternatively, we can use '\n' for a new line
input("What is your na... |
# Calculatey
print(72 * 234 * 12)
# Remainder
print(6439 % 6)
# Printing "twelve" 12 times
print("twelve" * 12)
# rain + bow = rainbow
word1 = "rain"
word2 = "bow"
word = word1 + word2
print(word)
# Greeting with a name
greeting = "Good Afternoon, "
name = "Bucky"
print(greeting + name + "!")
# or...
greeting = "Goo... |
import turtle
t = turtle.Pen()
# Function to draw octagon. It takes size as input parameter
def octagon(size):
#Start from 1 and end at 9. 9-1=8 => 8 sides of an octagon.
#This loop will draw eight sides
for x in range(1,9):
#Draw each side with given size
t.forward(size)
... |
def main():
a=raw_input()
if a in ('a','e','i','o','u','A','E','I','O','U'):
print("Vowel")
elif a in ('y','Y','h','H'):
print("somtimes y and h acts as a vowel")
else:
print("Consonant")
if __name__ == '__main__':
main()
|
'''
LeetCode Strings Q.434 Number of Segments in a String
Count the number of segments in a string, where a segment is defined to be a contiguous sequence of non-space characters
'''
def countSegments(s):
if s == "":
return 0
s = " ".join(s.strip().split())
seg = s.split(" ")
return len(s... |
from functools import reduce
def is_palinrome(n):
s1 = str(n)
s2 = str(n)[::-1]#反转字符串
return s1==s2
output = filter(is_palinrome,range(1,1000))
print(list(output)) |
from pprint import pprint as pp
def group_words_by_count(wc):
group_by = dict()
for word, count in wc.iteritems():
if count not in group_by:
group_by[count] = list()
group_by[count].append(word)
return group_by
def get_word_count(txt_file):
word_count =dict()
for li... |
a=12
b=12.5
c="adham"
#This is integer
print(a)
print(type(a))
#This is float
print(b)
print(type(b))
#This is string
print(c)
print(type(c))
name=input("Enter full name:")
age=input("Eanter your age:")
mail=input("Enter your mail:")
print( "\nFull name: " + name + "\nYour age: " + str(age) + "\nYour Mail: " + mai... |
funcao = lambda y: return y
h = funcao(4)
print(h)
#O programa deu erro de sintaxe, pois lambda não usa o comando return, que é mais usado em def |
"""
exercise on CNN
image = [B, C, H, W]
B : batch size
C : number of color channel, R G B
H : height of the image
W : width of the image
example
img = image[3, 1, 28, 28]
where batch size = 3 batch of three images, each image has single (1) color channel, and height x width is 28x28
color channel = Feature maps
this... |
#%% [markdown] Can you accurately predict insurance claims?
# In this project, we will discuss how to predict the insurance claim.
# We take a sample of 1338 data which consists of the following features:
# age : age of the policyholder
# sex: gender of policy holder (female=0, male=1)
# bmi: Body mass index, provid... |
while True:
try:
number= int(input('what number brah?\n'))
print(18/number)
break
except ValueError:
print('brah enter number brah')
except ZeroDivisionError:
print('brah dont do that')
except:
break
finally:
print('cool number brah') |
class mySingleton(object):
_instance = None
def __new__(self):
if not self._instance:
self._instance=super(mySingleton,self).__new__(self)
self.y=10
return self._instance
x = mySingleton()
print(x.y)
x.y = 20
z= mySingleton()
print(z.y) |
from tkinter import *
import tkinter.messagebox
root = Tk()
#tkinter.messagebox.showinfo('Windowww Title', 'Monkey orange')
answer = tkinter.messagebox.askyesno('Question 1','Do you even, brah ?')
if answer == "yes":
print(" XD ")
root.mainloop() |
#!/usr/bin/env python
import sys, os
from notehandler import Main
if __name__ == "__main__":
if sys.argv[1] in ['-h', '--help', 'help']:
print("""
note <category> <tablename> <arguments>
Writing a note:
-n / --new / new <your note>
Example:
This is... |
# -*- coding: utf-8 -*-
"""
Created on Sat Nov 30 08:08:01 2019
@author: CEC
"""
suma=lambda x,y: x+y
print(suma(5,2))
revertir= lambda cadena: cadena[::-1]
print(revertir("hola"))
doblar= lambda num: num*2
print(doblar(2))
seq= ["date","salt","dairy","cat","dog"]
print(list(filter(lambda word: wo... |
# -*- coding: utf-8 -*-
"""
Created on Fri Nov 29 20:20:30 2019
@author: CEC
"""
def address(street,city,postalcode):
print("your sddress is: ",street, city, postalcode)
s= input("street:")
pc= input("postal: ")
c=input("city: ") |
import threading
import time
start = time.time()
def squares(numbers):
print("calculating square of numbers... ")
for n in numbers:
time.sleep(.5)
print("square: ", n**2)
def cubes(numbers):
print("calculating cubes of numbers... ")
for n in numbers:
time.sleep(.5)
pri... |
# -*- coding: utf-8 -*-
"""
#url参数生成字典
"""
def UrlgetDict(url,args1='?',args2='&',args3='=',num=1):
#拆分得到参数信息,如:['a=1', 'b=2', 'c=3']
url_list = (url.split(args1)[num]).split(args2)
url_dict = {}
for i in url_list:
#遍历分别把参数信息加入字典i
value = i.split(args3)
url_dict.update(dict(zip(value[0],value[1])))
return ur... |
#!/bin/python3
""" HackerRank 'Algorithms' domain Warmup challenges.
https://www.hackerrank.com/domains/algorithms/implementation
"""
from string import ascii_lowercase
from itertools import takewhile
from math import floor, sqrt, ceil
from testing import test_fn
def mini_max_sum(integers):
"""... |
n = int(input("Please enter the value of n: "))
while n > 1:
print(str(int(n)), end = ' ')
if(n % 2 == 1): # is an odd.
n = n * 3 + 1
else:
n = n / 2
print(str(int(n)), end = ' ')
|
# Tic Tac Toe
# Reference: With modification from http://inventwithpython.com/chapter10.html.
import random
def drawBoard(board):
"""
Prints out the board that it was passed.
Parameters:
board: a list of 10 strings representing the board (ignore index 0)
"""
prin... |
#!/usr/bin/python2.6
# -*- coding : utf-8 -*
# Homme ou femme
prenom = raw_input("entrez votre prenom: ")
nom = raw_input("entrez votre nom: ")
sexe = raw_input("entrez f si vous etes une femme et m si vous etes un homme : ")
while s != "f":
sexe = raw_input("la valeur entrez n'est ni f ni m : ")
if sexe == "f" o... |
#!/usr/bin/python2.6
# -*- coding : utf-8 -*
# Ecrivez un programe qui calcule le perimetre et l'air d'un trianagle
# dont, les 3 cotes sont fourni par l'utilisateur
from math import *
print("calcul ddu perimetre et l'air d'un triangle")
a = raw_input("entrer la logueur du cote a: ")
a = float(a)
b = raw_input("entre... |
import numpy as np
import cv2
## Image reading
frame = cv2.imread('paper_test5.jpg')
## Image resizing logic
r = 400.0 / frame.shape[1]
dim = (400, int(frame.shape[0] * r))
frame = cv2.resize(frame, dim, interpolation = cv2.INTER_AREA)
### smoothing the noise
frame=cv2.GaussianBlur(frame, (5,5),0)
# convert the im... |
class MergeSort:
@classmethod
def get_reference(cls, data):
return cls._merge_sort(data, 0, len(data)-1)
@classmethod
def _merge_sort(cls, A, start, end):
if end <= start:
return
mid = start + ((end - start + 1) // 2) - 1
yield from cls._merge_sort(A, start, ... |
'''try:
1/0
except Exception as ex:
print(ex)
finally:
print('inside finally')'''
#finally block will execute everytime the code will run
'''try:
a=20
except Exception as ex:
print(ex)
else:
print('ex')'''
#else code will only run if the code does not have an exception
#if an... |
num=input('enter any number=')
num=int(num)
if num%2==0:
num1=(num/2)+1
num1=int(num1)
num2=0
for a in range(0,num1):
if a==0:
print('*')
continue
else:
for b in range(num2+2):
print('*',end='')
num2+=2
prin... |
import random
d=0
for i in range(1,11):
print(i,'chance--')
a=random.randrange(1,6)
b=random.randrange(1,6)
print('1st dice value=',a,' ','2nd dice value=',b)
c=a+b
print('total dice value=',c)
if(d+c)>50:
if(i>9):
print('you lose the game')
continu... |
l=[0,0,0,0,0]
for i in range(5):
l[i]=int(input('enter a number'))
maximum=l[0]
minimum=l[0]
for i in l:
if maximum>i:
continue
else:
maximum=i
for i in l:
if minimum<i:
continue
else:
minimum=i
print('maximum value is=',maximum)
print('minimum... |
def change(a,b):
c=a.upper()
d=b.upper()
j=0
l=[]
for i in range(len(c)):
if c[i]==' ' or c[i]==',':
if c[j:i]==d:
l.append(c[j:i])
else:
l.append(a[j:i])
j=i+1
if i==len(c)-1:
if c[j:i+1]==d... |
'''class Students:
def __init__(self):
print('inside')
self.name = 'rohit'
self.age = 25
self.course = 'python'
print('before')
obj1 = Students()
print('after')
print(obj1.name)
print(obj1.age)
print(obj1.course)
print(dir(obj1))
obj2 = Students()'''
'''class ... |
'''a=input('enter any number')
a=int(a)
b=input('enter any number')
b=int(b)
c=input('enter any number')
c=int(c)
d=input('enter any number')
d=int(d)
print(max(a,b,c,d))
print(min(a,b,c,d))'''
l=[0,0,0,0]
for i in range(4):
l[i]=input('enter a number')
print(max(l))
print(min(l))
|
# Handling different exceptions using with block multi resources
try:
with open("app.py") as file1, open("test.py", "w") as file2:
print(file1)
print(type(file1))
print(file2)
print(type(file2))
print("File opened for read and closed prop")
age = int(input("Enter ... |
from math import sqrt, floor
def p(n):
c = 0
lp = [2,3,5,7,11]
d = 13
while c <= (n-6):
if isitprime(d):
lp.append(d)
c += 1
d += 2
print(lp[-1])
def isitprime(x):
c = 0
y = int(sqrt(x))
for a in range(2, y+1):
if x%a == 0:
c += 1
if c >= 1:
return False
else:
return True
p(10001) |
#!/bin/python3
# scraper.py
# The scraper will go to a Wikipedia page, scrape the title, and follow
# a random link to the next Wikipedia page.
import requests
from bs4 import BeautifulSoup
import random
import time
BASE_URL = 'https://en.wikipedia.org'
def scrape_wiki_article(url):
response = requests.get(url=... |
#!/usr/bin/env python
bursttime=[]
print("Enter number of process: ")
noOfProcesses=int(input())
processes=[]
for i in range(0,noOfProcesses):
processes.insert(i,i+1)
print("Enter the burst time of the processes: \n")
bursttime=list(map(int, raw_input().split()))
for i in range(0,len(bursttime)-1): ... |
import random
from .card import Card, NUMBERS, SUITS
class Deck:
def __init__(self) -> None:
self._cards = [
Card(num, suit)
for suit in SUITS # 🗡 🌳 🥇 🏆
for num in NUMBERS
]
def shuffle(self) -> None:
"""Shuffles the cards in the deck."""
... |
import sqlite3
import os
def connect_db(db_name):
return sqlite3.connect(db_name)
def execute_sql(db_file,sql):
assert os.path.isfile(db_file), "Database %s does not exist"%db_file
with sqlite3.connect(db_file) as conn:
c = conn.cursor()
c.execute(sql)
file_entry = c.lastrowid
conn.commit()
return file_en... |
# Matrix Algebra
# Insert the given vectors/ matrices
import numpy
from numpy import linalg as LA
A = numpy.matrix([[1, 2, 3], [2, 7, 4]])
B = numpy.matrix([[1, -1], [0,2]])
C = numpy.matrix([[5, -1], [9,1], [6,0]])
D = numpy.matrix([[3, -2, -1], [1, 2, 3]])
u = numpy.array([6, 2, -3, 5])
v = numpy.array([3, 5, -1, ... |
a = 1
p = 1
while a <= 12:
print(a, "AM")
a = a + 1
while p <= 12:
print(p, "PM")
p = p + 1 |
#Github: https://github.com/elinbua/TileTraveller
def start_point():
"""The game starts in num= 1.1 and possible direction is north (route = 1)"""
num = 1.1
route = 1
print("You can travel: (N)orth.")
return num, route
def direction():
"""Enter direction"""
direction_str = input("Direction:... |
from domain import Room,Reservation
import random
import datetime
import calendar
import unittest
class Service:
def __init__(self,roomRepo,reservationRepo,reservationValidator):
self.__roomRepo = roomRepo
self.__resRepo = reservationRepo
self.__resValid = reservationValidator()
def ge... |
from domain import Question
import math
class Service:
def __init__(self,questionsRepo):
self.__qRepo = questionsRepo
def addQuestion(self,parts):
"""
Function that adds a new question to the master question list.
:param parts: list - the elements of the question
:return... |
def createPhone(manufacturer, model, price):
return {'mnf':manufacturer, 'model':model, 'price':price}
def add_phone(phone,phoneList):
if len(phone['mnf'])<3 or len(phone['model'])<3 or len(str(phone['price']))<3:
raise ValueError("Invalid phone!")
phoneList.append(phone)
def phones_by_manufactur... |
class ConsoleMenu:
def __init__(self,songSrv):
self.__songSrv = songSrv
self.__menu = "\nPress: [1] to search songs by name\n" \
"[2] to show the songs with the same genre as a given song"
@staticmethod
def printSongs(songs):
for song in songs:
print... |
# LAB 1 : Threading - Bank accounts
"""
At a bank, we have to keep track of the balance of some accounts. Also, each account has an associated log
(the list of records of operations performed on that account).
Each operation record shall have a unique serial number, that is incremented for each operation performed in t... |
str = 'ashanti is an idiot'
print(str.capitalize()) # capitalise
print(str.count("an", 0, len(str))) # look for occurence of text in a string
s = str.encode('utf-8', 'strict')
print(s)
##################################################################
print(max(str))
print(min(str))
###############################... |
from decimal import Decimal, getcontext
import os
getcontext().prec = 10
def line():
print()
print("-=" * 30)
print()
def header(msg):
line()
print(f"{msg:^60}")
line()
def showMenu():
header("MENU PRINCIPAL")
print("""[1] Calcular Frete
[2] Calcular Preço de Venda [Com Frete Gráti... |
import xml.etree.ElementTree as ET
from airline import Airline
class AirlineParser(object):
"""
Utility for parsing airline information from an XML files.
"""
@staticmethod
def parse_airlines(xml_file):
"""
Parses airline information from an XML file.
Returns a... |
import xml.etree.ElementTree as ET
from flightstatus import FlightStatus
class FlightStatusParser(object):
"""
Utility for parsing messages from a given XML file.
"""
@staticmethod
def parse_statuses(xml_file):
"""
Parses the status messages from a given XML file.
... |
from math import sin, cos, radians, atan2, sqrt, asin
class Position(object):
def __init__(self, latitude, longitude):
self.latitude = latitude
self.longitude = longitude
def compute_distance_to(self, p):
# geometric mean from wikipeda
earth_radius = 6371.0
# convert ... |
"""
Tipe data dictionary sekedar menghubungkan antara KEY dan Value
KVP = Key Value Pair
dictionary = kamus
"""
kamus_ind_eng = {'anak': 'son', 'istri': 'wife', 'ayah': 'father', 'ibu': 'mother'}
print(kamus_ind_eng)
print(kamus_ind_eng['ayah'])
print(kamus_ind_eng['ibu'])
print('\nData ini dikirimkan oleh server Go... |
'''Todo e-mail é formado por duas partes: o login do usuário e o domínio do provedor.
Veja o exemplo abaixo:
E-mail: antonio.silva@ifpb.edu.br
Login: antonio.silva
Domínio: ifpb.edu.br
Escreva um programa que leia o login de um usuário e o domínio do seu provedor e mostre o seu e-mail completo.'''
login =... |
'''5. Escreva um programa para determinar as raízes de uma equação de segundo grau, dados os
seus coeficientes. Fórmulas:
Obs: se Δ for negativo, não existem as raízes da equação.
Dica: use a função sqrt do módulo math.'''
from math import sqrt
print('Resolução de uma equação de segundo grau!')
a = int(inpu... |
'''Escreva um programa que leia o peso (kg) e a altura (m) de uma
pessoa, determine e mostre o seu grau de obesidade, de acordo com a
tabela seguinte. O grau de obesidade é determinado pelo índice de
massa corpórea, cujo cálculo é realizado dividindo-se o peso da pessoa
pelo quadrado da sua altura.'''
altura = ... |
'''Faça um programa que leia um número inteiro N, calcule e mostre o maior
quadrado perfeito menor ou igual a N. Por exemplo, se N for igual a 38, o
resultado é 36.'''
import math
maior = 0
n = int(input('Informe um número: '))
for i in range(1, n + 1):
raiz = math.sqrt(i)
if raiz == int(raiz) and... |
'''Faça um programa que, para um grupo de N pessoas (obs: N será lido):
• Leia o sexo (M ou F) de cada pessoa;
• Calcule e escreva o percentual de homens;
• Calcule e escreva o percentual de mulheres.'''
cont_mulher = 0
cont_homem = 0
n = int(input('Informe a quantidade de pessoas que participarão do teste: '... |
'''3. Faça um programa que leia vários números, determine e mostre o maior e o
menor deles.
Obs: a leitura do número 0 (zero) encerra o programa.'''
flag = 0
print('A entrada do número 0 (zero) encerrará o programa.')
num = int(input())
maior = num
menor = num
while num != flag:
if num > maior:
... |
'''Faça um programa para ler o nome e o salário bruto dos 100 funcionários de uma determinada empresa.
Para cada funcionário lido, o programa deverá emitir o respectivo contracheque, que deverá conter:
O nome do funcionário;
O valor do salário bruto;
O valor do desconto do INSS (12% do Salário Bruto)
O valor do sa... |
'''5. Escreva um programa para ler o nome e o sobrenome de uma pessoa e escrevê-
los na seguinte forma: sobrenome seguido por uma vírgula e pelo nome'''
nome = input('Nome: ')
sobrenome = input('Sobrenome: ')
print(f'{sobrenome}, {nome}')
|
import random
x = input("What is your name? ")
print("Hello, " + x + "!")
y = str(random.randint(-10000, 10000))
print("Your lucky number is: " + y)
avg = 0
for x in range(1000):
found = 0
for i in range(10000):
if random.randint(-100, 100) == 0:
found = found + 1
print("Percentage " +... |
# -----------------------------------------------------------------------------
# Calculator with English words and numbers.
# Oscar Rubio Pons, oscar.rubio.pons@gmail.com
# 16 Sept 2013, Hamburg, Germany
# -----------------------------------------------------------------------------
import sys
sys.path.insert(0,"../.... |
from structure import Structure
class SandCastle (Structure): # inheritance
'''Defines a sand castle.'''
__num_castles = 0 # private class field
purpose = 'fun' # public class field
# Constructor:
def __init__(self, name, size):
self.name = name
self.size = size
Sa... |
def is_palindrome(n):
return str(n) == str(n)[::-1]
result = 0
for i in range(1000000):
if is_palindrome(i) and is_palindrome("{:b}".format(i)):
result += i
print(result)
|
#Challenge 3
x = int(input("Please enter an integer: "))
y = int(input("Please enter a larger integer: "))
def sumOddNumbersInRange(x, y):
"""A function to calculate the sum of odd numbers from x
(including x) to y (excluding y) return the result
e.g. if x = 4 and y = 9 then the result is 5 + 7 = 12
"""
as... |
"""
Zihao Li
Class: CS 521 - Fall 2
Date: Wed Dec 11, 2019
Final Project
Description:
Recognize face method
"""
import face_recognition
from PIL import Image, ImageDraw
def recognize_face(filename):
"""This is a method to recognize a face in a group photo."""
# Load the jpg file into a numpy array
image = face_r... |
import numpy as np
import matplotlib.pyplot as plt
def sigmoid(x):
return 1 / (1+np.exp(-x))
x = np.arange(-5, 5, 0.1)
y = sigmoid(x)
print(x.shape, y.shape)
plt.plot(x, y)
plt.grid()
plt.show()
# activation 은 가중치 값을 한정시킴 |
#1. 데이터
import numpy as np
x=np.array([range(1, 101), range(311, 411), range(100)])
y=np.array([range(101, 201), range(711, 811),range(100)])
print(x.shape) #(3,100)
#행과 열을 바꾸는 함수 (3,100)--->(100,3)
x = np.transpose(x)
y = np.transpose(y)
print(x.shape) #(100,3)
print(y.shape)
#x=np.swapaxes(x,0,1)
#x=np.arange... |
import matplotlib.pyplot as plt
import numpy as np
# 사진 데이터 읽어들이기
photos = np.load('myproject/photos.npz')
x = photos['x']
y = photos['y']
# 시작 인덱스 --( 1)
idx = 0
#pyplot로 출력하기
plt.figure(figsize=(10, 10))
for i in range(9):
plt.subplot(3, 3, i+1)
plt.title(y[i+idx])
plt.imshow(x[i+idx])
plt.show() |
import pandas as pd
titanic_df = pd.read_csv(r'C:\Users\bitcamp\Desktop\titanic\train.csv')
titanic_df['Child_Adult']=titanic_df['Age'].apply(lambda x : 'Child' if x <= 15 else 'Adult')
print(titanic_df[['Age', 'Child_Adult']].head(8))
titanic_df['Age_cat'] = titanic_df['Age'].apply(lambda x : 'Child' if x<=15 else... |
# 1. 데이터
import numpy as np
x_train = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
y1_train = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
y2_train = np.array([1, 0, 1, 0, 1, 0, 1, 0, 1, 0])
# 2. 모델 구성
from keras.models import Sequential, Model
from keras.layers import Dense, Input
input1 = Input(shape=(1,))
x1 ... |
#1. R2를 0,5 이하 2. 레이어 5개이상 인풋아웃풋포함 3. 노드의 개수 10개 이상 4. EPOCHS 30개 이상 5. BATCHI_SIZE = 8 이하
#1. 데이터
import numpy as np
x=np.array([range(1, 101), range(311, 411), range(100)])
y=np.array(range(711, 811))
print("x.shape : ", x.shape)
print("y.shape : ", y.shape)
#행과 열을 바꾸는 함수
x = np.transpose(x)
y = np.transpo... |
a = {'name' : 'yun', 'phone':'010', 'birth' : '0511'}
'''a = 0
for(i=1, i=100, i++){
a= i + a
}
print(a)
for i in 100:
a i 결과a
0 1 1
1 2 3
3 3 6
6 4 10
213 100'''
for i in a.keys():
print(i)
a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
for i in a:
i = i*i
print(i)
# print('melong') melong 이 10번출력됨
#prin... |
import numpy as np
from Layer import Layer
from losses import *
class NeuralNetwork:
"""Multi layer network.
Parameters
----------
loss: string ("mean_squared_error")
Specifies loss to train the function on
Attributes
----------
layers: list
list contaning all layers with... |
#number = input("number : ")
def iterate(n):
i=0
n = int(n)
while i <= n:
print(i)
i += 1
def fibonnaci(n):
list = [0]
i = 0
n = int(n)
while i < n-1 :
if list[i] == 0:
list.append(1)
else:
list.append(list[i]+list[i-1])
i... |
#coding: utf-8
from Tkinter import *#Importation de l'outil ,comme pour Turtle
from random import *
from time import sleep
fen1 = Tk() #Creation de la fenetre principale
fen1.attributes('-fullscreen', 1)#Fenetre en plein écran
#---------------Definitions---------------#
#Initialisation
def initMainTableau(... |
from itertools import permutations
def create_matchups(teams):
return list(permutations(teams, 2))
class Team:
def __init__(self, name, abbreviation):
self.name = name
self.abbreviation = abbreviation.upper()
# stores points gained for win or draw
self.points = 0
# records goal difference
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.