text stringlengths 37 1.41M |
|---|
def write_to_file(filename, txt):
with open(filename, 'w') as file_object:
file_object.write(txt)
if __name__ == '__main__':
print("Python File Writer Starting.")
message = str(input("Enter your message: "))
filename = str(input("Enter file name: "))
if filename[-4:] != ".txt":
file... |
# 1. Modify the program so that it prints "Ouack" and "Quack" but leaves the other names the same.
def ducklings():
prefixes = 'JKLMNOPQ'
suffix = 'ack'
for letter in prefixes:
if letter == 'O' or letter == 'Q':
# uses f literal
print( f"{letter}u{suffix}")
else:
... |
import math
def countdown(n):
if n <= 0:
print('Blastoff!')
else:
print(n)
countdown(n-1)
# Write a new recursive function countup that expects a negative argument and counts “up” from that
# number. Output from running the function should look something like this:
# >>> coun... |
'''
93. Restore IP Addresses
Given a string containing only digits, restore it by returning all possible valid IP address combinations.
For example:
Given "25525511135",
return ["255.255.11.135", "255.255.111.35"]. (Order does not matter)
'''
class Solution:
def restoreIpAddresses(self, s):
"""
... |
#coding=utf-8
'''
41. First Missing Positive
Given an unsorted integer array, find the smallest missing positive integer.
Example 1:
Input: [1,2,0]
Output: 3
Example 2:
Input: [3,4,-1,1]
Output: 2
Example 3:
Input: [7,8,9,11,12]
Output: 1
Note:
Your algorithm should run in O(n) time and uses constant extra space... |
#coding=utf-8
'''
136. Single Number
Given a non-empty array of integers, every element appears twice except for one. Find that single one.
Note:
Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?
Example 1:
Input: [2,2,1]
Output: 1
Example 2:
Input: [4,1,... |
#coding=utf-8
'''
Given a non-empty string s and a dictionary wordDict containing a list of non-empty words, determine if s can be segmented into a space-separated sequence of one or more dictionary words.
Note:
The same word in the dictionary may be reused multiple times in the segmentation.
You may assume the dic... |
#coding=utf-8
'''
127. Word Ladder
Given two words (beginWord and endWord), and a dictionary's word list, find the length of shortest transformation sequence from beginWord to endWord, such that:
Only one letter can be changed at a time.
Each transformed word must exist in the word list. Note that beginWord is not a... |
#coding=utf-8
'''
141. Linked List Cycle
Given a linked list, determine if it has a cycle in it.
Follow up:
Can you solve it without using extra space?
'''
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(o... |
#coding=utf-8
'''
118. Pascal's Triangle
Given numRows, generate the first numRows of Pascal's triangle.
For example, given numRows = 5,
Return
[
[1],
[1,1],
[1,2,1],
[1,3,3,1],
[1,4,6,4,1]
]
'''
class Solution:
def generate(self, numRows):
"""
:type numRows: int
:rtype: ... |
# coding=utf-8
'''
7. Reverse Integer
Reverse digits of an integer.
Example1: x = 123, return 321
Example2: x = -123, return -321
'''
class Solution(object):
def reverse(self, x):
"""
:type x: int
:rtype: int
"""
if x == 0 or not -1*(2**32) <= x <= 2**32 ... |
def list_to_number(digits):
num = 0
num_of_digits = len(digits)
for i in digits:
print(i)
num += (10 ** num_of_digits) * digits[i]
#print(num)
num_of_digits -= 1
return num
print(list_to_number([2, 3, 6, 8]))
|
import random
class Fight:
def __init__(self, fight_hero, fight_orc):
self.fight_hero = fight_hero
self.fight_orc = fight_orc
def flip_coin(self):
if random.random() < 0.5:
return self.fight_hero
else:
return self.fight_orc
def simulate_fight(self,... |
import unittest
from count_words import count_words
class TestCountWords(unittest.TestCase):
def test_count_one_word(self):
self.assertEqual({"apple": 1}, count_words(["apple"]))
def test_count_more_words(self):
self.assertEqual({"apple": 2}, count_words(["apple", "apple"]))
def test_cou... |
#This program creates a list of three employees using a class
import Cox_employee
def main():
#Get list of Employees
employees = make_list()
#Display data in list
print('Here is the list of employees:')
display_list(employees)
def make_list():
#Make empty list
emp_list = []
#Get S... |
#This program calculates acres from a given square foot measurement of land
#Takes square foot value from user
feet = input("How many square feet is the tract of land? ")
#Converts square feet to acres
acres = float(feet)/43560
#Prints converted amount of acres
print("You have", format(acres, '.2f')," acres of land.... |
#This program tells the user if they are over, under or have made their budget
#Get budget
budget = float(input("Enter your monthly budget: "))
#Set total variable
total = 0.00
#Set control variable
keep_going = 'y'
#Get series of expenses
while keep_going == 'y':
#Get expense
number = float(input('Enter a... |
# Import raindrops function
from main import raindrops
# Import unittest
import unittest
# Create class to apply testing
class Tests(unittest.TestCase):
# Example tests
def test_examples(self):
self.assertEqual(raindrops(28), "Plong")
self.assertEqual(raindrops(30), "PlingPlang")
self.assertEqual(raindrops(3... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Feb 8 21:08:27 2021
@author: zachary
"""
import random
# def validate_input(value_type, prompt, error_message, invalid_type_message, lower = None, upper = None):
# val = input(prompt)
# if type(val) is value_type:
# if lower and uppe... |
'''
Created on Dec 11, 2016
@author: vbera
'''
x1,v1,x2,v2 = input().strip().split(' ')
x1,v1,x2,v2 = [int(x1),int(v1),int(x2),int(v2)]
kangaroo1 = False
kangaroo2 = False
if x1==x2:
print("YES")
else:
if v1 > v2:
kangaroo1 = True
else:
kangaroo2 = True
if kangaroo1:
whi... |
'''
Created on Nov 3, 2016
@author: vbera
'''
import re
def recurssion(no):
ans = 0
if no == 0:
return 1
elif no >= 3:
ans = ans + recurssion(no - 3)
ans = ans + recurssion(no - 2)
ans = ans + recurssion(no - 1)
elif no >= 2:
ans = ans + recurssion(no - 2)
... |
'''
Created on Feb 8, 2017
@author: vbera
'''
def maxProfit(priceList, maxPriceIndex):
profit = 0
for i in range(0, maxPriceIndex):
profit += priceList[maxPriceIndex] - priceList[i]
return profit
def getMaxIndex(priceList):
maxPrice = 0
maxPriceIndex = 0
i = 0
for price in priceLis... |
def pentagonalN( n ):
return int( n * ( 3 * n - 1 ) // 2 )
def genPentagons( n ):
pentagons = []
for i in range( 1 , n + 1 ):
pentagons += [ pentagonalN( i ) ]
return pentagons
def findMin():
pents = genPentagons( 10000 )
pentSet = set( pents )
for i1 in range( len( pents ) ... |
from functools import reduce
from operator import mul
def genPrimes( max ):
primes = [2]
for i in range( 3, max, 2 ):
if 0 not in [ i % k for k in primes ]:
primes += [ i ]
# for k in primes:
# if i % k == 0:
# print( i, k )
# break
... |
import math
def nthPentagon( n ):
return int ( n * ( 3 * n - 1 ) // 2 )
def isHexagonal( n ):
triangle = ( math.sqrt( 8 * n + 1 ) - 1 ) / 2
return triangle == int( triangle ) and int( triangle ) % 2 == 1
def findSecondTriPenHex():
i = 166
while True:
if isHexagonal( nthPentagon( i ) ):... |
def relPrime( vals, check ):
# print( vals, check )
for val in vals:
if check < val * val:
return True
if check % val == 0:
return False
return True
def genPrimes( max ):
primes = [2]
for i in range( 3, max, 2 ):
if relPrime( primes, i ):
... |
__author__ = 'jriley'
#
'''
We only need to do a few more things to the data to get it ready for logistic regression.
* Create a new file called 'logistic_regression.py'. For this lesson, we're going to need pandas and statsmodels.
* Load the data.
* Add a column to your dataframe indicating whether the interest rate ... |
from random import randint
from typing import List
from error.exepciones import IndiceInvalido, AporteInvalido, PrestamoInvalido, CantidadDineroInvalida
from mundo.funciones import verificarFecha, obtenerInteres
class Fecha:
"""Clase para manejar de una manera mas ordenada las fechas.
Attributes:
... |
import numpy as np
from random import shuffle
def softmax_loss_naive(W, X, y, reg):
"""
Softmax loss function, naive implementation (with loops)
Inputs have dimension D, there are C classes, and we operate on minibatches
of N examples.
Inputs:
- W: A numpy array of shape (D, C) containing weights.
- X:... |
#Collatz Conjecture -
#Start with a number n > 1. Find the number of steps it takes to reach one using the following process:
#If n is even, divide it by 2. If n is odd, multiply it by 3 and add 1
#picking a number, could have been thru an random int generation
num = int(input("please select a number > 1 "))
#init... |
#!/usr/bin/env python
# coding=utf-8
print(u"哈哈哈")
classmates = ['Michael', 'Bob', 'Tracy']
print classmates
print len(classmates)
print classmates[0]
print classmates[1]
print classmates[2]
# 取最后一个
print classmates[-1]
classmates.append("Adam")
print classmates
classmates.insert(1, "Jack")
print classmates
prin... |
#연도를 입력으로 받아 윤년인지 아닌지를 학인
y = eval(input("년도:"))
if (y % 4 == 0 and y % 100 != 0) or y % 400 == 0:
print(y, "윤년")
else:
print(y, "결과 없음")
# 피타고라스의 수
def a(a, b, c) :
if(a*a + b*b == c*c) :
return True
else :
return False
def pita() :
for a in range(1, 1000) :
for b in rang... |
my_number = 7
user_answer = int(input("Guess my number: \n"))
if user_answer == my_number:
print("Wow correct!")
elif user_answer < my_number:
print("Too low.")
else:
print("Too high.")
|
name = input("What is your name?\n")
if len(name) > 3:
print("Your name is long enough.")
if len(name) > 15:
print("That is way too long.")
else:
print(f"Welcome {name}") |
class Person:
def __init__(self, name, age, height="normal"):
print(f'You\'ve created a new instance of person')
self.name = name
self.age = age
self.height = height
# instantiate that act of creating an instance. object is the instance of a class.
# attribute
rob = Person('Rob', 31... |
name = input("What is your name?\n")
num = len(name)
if num > 3 and num < 15: # and operator both statement need to be true
if num == 4:
print("Perfect Length")
else:
print("It's an ok length.")
print(f"Welcome {name}!")
else:
print(f"{num} is not a good number of characters.... |
import math
pose_mat = [[],[],[]]
pose_mat[0] = [float(e) for e in input()[1:-3].split(", ")]
pose_mat[1] = [float(e) for e in input()[1:-3].split(", ")]
pose_mat[2] = [float(e) for e in input()[1:-3].split(", ")]
# pose_mat[2] = [float(e) for e in input().split()]
print(pose_mat)
def findangle(pose_mat):
yaw = 1... |
## Day 2 Homework
## Q1
'''
list1 = ['İstanbul','Ankara','Balıkesir','Bitlis','Konya','Rize','Kocaeli','Aydın']
L = len(list1) # lenght of the list1
Lm = int(L/2)
i = 0
listFH = list1[:Lm] #First Half of the list1
listSH = list1[Lm:L] #Second Half of the list1
print(listFH)
print(listSH)
while(i<Lm): ## i<4
li... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Jan 10 11:48:25 2019
@author: harriet
"""
#Given 3 int values, a b c, return their sum. However, if one of the values is 13 then it does not count towards the sum and values to its right do not count. So for example, if b is 13, then both b and c do n... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Jan 10 11:51:42 2019
@author: harriet
"""
#Given an array of ints, return True if the array contains a 2 next to a 2 somewhere.
#
#
#has22([1, 2, 2]) → True
#has22([1, 2, 1, 2]) → False
#has22([2, 1, 2]) → False
def has22(nums):
for i in range (0,... |
# -*- coding: utf-8 -*-
"""
Created on Tue Dec 18 16:43:07 2018
@author: 612383249
"""
#Given an int array length 2, return True if it contains a 2 or a 3.
#
#
#has23([2, 5]) → True
#has23([4, 3]) → True
#has23([4, 5]) → False
def has23(nums):
if nums[0] == 2 or nums[0] == 3:
return True
eli... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Dec 15 14:58:21 2018
@author: harriet
"""
#
#Given an "out" string length 4, such as "<<>>", and a word, return a new string where the word is in the middle of the out string, e.g. "<<word>>".
#
#
#make_out_word('<<>>', 'Yay') → '<<Yay>>'
#make_out_wor... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Jan 10 11:50:24 2019
@author: harriet
"""
#Return the "centered" average of an array of ints, which we'll say is the mean average of the values, except ignoring the largest and smallest values in the array. If there are multiple copies of the smallest ... |
# This program will write values from a function to a specified file
from math import *
def main():
# Get the file name from the user
filename = raw_input("Enter a filename: ")
# Create the file and open it for writing
filename = open(filename, 'w')
# Write the x and y values to the fil... |
def convert():
celsius = input("Enter the tempurature in Celsius: ")
ferenheight = (9.0/5.0) * celsius + 32
print "The tempurature in Farenheight is", ferenheight
convert()
|
#This program draws a pizza with n number of slices
#Written by David Pick
from graphics import *
from math import *
def pizza(center, radius, numslices):
win = GraphWin()
pizza = Circle(center, radius)
pizza.draw(win)
for i in range(numslices):
x = int(pizza.getCenter().getX() ... |
class T:
"""True"""
def _and(self, other):
return other
def _or(self, other):
return self
def _not(self):
return F()
def _if(self, consequent, alternate):
return consequent()
def __str__(self):
return "True"
class F:
"""False""... |
q=[]
def InsQueue(passenger):
a=input("enter passenger name")
passenger.append(a)
rear=len(passenger)-1
return passenger
def DelQueue(passenger):
if passenger==[]:
return 'underflow'
else:
passenger.pop(0)
if len(passenger)==0:
rear=front=None
r... |
# -*- coding: UTF-8 -*-
"""Classes for generating logarithmic triangle tilings, based on:
https://www.mathartfun.com/FathauerBridges2021v1.pdf
"""
#+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++#
import os
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.patches imp... |
from corpus import tokenize
from collections import defaultdict
import re
import subprocess
"""
Created by Alex Calderwood in 2018
Turns a list of english word tokens into a list of pronunciations according to the CMU pronunciation dictionary.
"""
CMU_DICT = "../corpus/cmudict/cmudict.dict"
SUFFIX = re.compile('\(... |
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def reverse(self,curr,prev=None) :
if curr==None : return prev
next=curr.next
curr.next=prev
return self.reverse(ne... |
# 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 get_balance(self,root) :
if root==None :
return [0,True]
if root.left==None and root.rig... |
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def rotateRight(self, head, k):
"""
:type head: ListNode
:type k: int
:rtype: ListNode
"""
if head==N... |
def mean(values):
"""
finds the mean value of values
:param values: the numbers to use for calculations
:return: the mean
"""
return sum(values) / len(values)
def median(values):
"""
finds the median of values
:param values: the numbers to use for calculations
:return: the medi... |
class Solution:
"""
https://leetcode-cn.com/explore/learn/card/array-and-string/198/introduction-to-array/770/
给定一个整数类型的数组 nums,请编写一个能够返回数组“中心索引”的方法。
我们是这样定义数组中心索引的:数组中心索引的左侧所有元素相加的和等于右侧所有元素相加的和。
如果数组不存在中心索引,那么我们应该返回 -1。如果数组有多个中心索引,那么我们应该返回最靠近左边的那一个。
"""
def pivotIndex(self, nums):
... |
def func(list):
for i in range(len(list)):
if i < len(list)-2:
print(list[i] + ' ' +',',end = ' ')
#return list[i] + ' ' +','
elif i == len(list)-2:
print(list[len(list)-2] + ' ' + 'and', end = ' ')
#return list[len(list)-2] + 'and' + ' '
elif ... |
#! /usr/bin/env python3
import re,pyperclip
len_re = re.compile(r'.{8,}') #[a-zA-Z0-9]{8,}避免非法字符
a_re = re.compile(r'[a-z].*[A-Z]|[A-Z].*[a-z]')
num_re = re.compile(r'\d')
def checkPW(PW):
if len_re.search(PW) and a_re.search(PW) and num_re.search(PW):
print('your password is safe')
else:
prin... |
# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def isSymmetric(self, root: TreeNode) -> bool:
# Passing a null to the function? Return True if tree is not initialized
if not root... |
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode:
recursive = False
if not recursive:
# n: the number of nodes between rear and fro... |
# POS Assignment w/ Classes
# Operates a POS system with cash register and inventory functionalities with python classes
# Jerick Liu
# 01/25/2021
from Menu import Menu
from FindProduct import FindProduct
from Inventory import InventoryMenu as Inv
from Item import Item, Shopping
from FileManager import FileManager as ... |
import pandas_datareader as pdr
import datetime
import matplotlib.pyplot as plt
#tickers for all the stocks I'm watching
tickers = ['EOS.AX', 'WES.AX', 'BHP.AX']
ask = input("What stock do you want to check? ")
#function to return the stock price for the stocks.
def shareprice(ticker):
stock = pdr.get_data_yahoo... |
# -*- coding: utf-8 -*-
"""
Created on Sat Jul 24 09:55:57 2021
@author: hp
"""
str='ABCD'
length=4
for i in range(length):
for j in range(length-i-1):
print(" ",end="")
for j in range(i+1):
print(str[j],end=" ")
print()
for i in range(length):
for j in range(i):
print(" ",end... |
"""Todo List web app
1. need pages
* Terms of Use
* Privacy
* About Us
All of these are gonna be placed in footer
2. Add Signup and Signin process + logout
3. login -> user specific dashboard (using redis)
4. create a new list or click on any existing list
5. There are tasks in the list. Need to add fu... |
print('Compara duas String')
texto1 = input('Informe o primeiro texto: ')
texto2 = input('Informe o segundo texto: ')
tamanho1 = len(texto1)
tamanho2 = len(texto2)
sao_iguais = texto1.lower() == texto2.lower()
def imprimir(texto1,texto2):
print(f'String 1: {texto1}')
print(f'String 2: {texto2}')
print(f'ta... |
def nome_mes(mes):
numero_mes = int(mes)
if numero_mes < 1 or numero_mes > 12:
return 'mês inválido'
meses = ['jan', 'fev', 'mar', 'abr', 'mai', 'jun', 'jun',
'jul','ago','set','out','nov''dez']
return meses[numero_mes-1]
def eh_data_valida(data): #fazer as validações para as da... |
#003
#"Now I need a drink, alcoholic of course, after the heavy lectures involving quantum mechanics."
#という文を単語に分解し,各単語の(アルファベットの)文字数を先頭から出現順に並べたリストを作成せよ
#s = 'Now I need a drink, alcoholic of course, after the heavy lectures involving quantum mechanics.'
#l = s.split()
#def a(s): return len(s)-
#sentense =... |
"""
007
引数x, y, zを受け取り「x時のyはz」という文字列を返す関数を実装せよ.
さらに,x=12, y="気温", z=22.4として,実行結果を確認せよ.
"""
def s(x,y,z): return "{}時の{}は{}".format(x,y,z)
print(s(12,"気温",22.4))
#12時の気温は22.4
|
#!/usr/bin/python
#coding=utf-8
#汽车管理界面菜单
#yufeng on 2018/3/9
from com.yufeng.classlearning.carsmanager.CarService import CarService
def menu():
print(' 【汽车租赁系统】')
print('---------------------------------')
print(' 1.汽车信息添加')
print(' 2.汽车信息浏览')
print(' 3.租车')
print(' 4.还车')
... |
#!/usr/bin/python
#coding=utf-8
#python中if else的使用
name= input("请输入姓名:")
if name=='刘志峰':
print("刘志峰\n")
elif name=='叶想林':
print("叶想林\n")
else:
print("不认识\n")
print("判断完毕\n") |
#!/usr/bin/python
#Filename:func_param.py
def printMax(a,b):
if a>b:
print (a,'is maximum')
else:
print (b,'is maximum')
printMax(3,4) # directly give literal values
x=5
y=7
printMax(x,y) #givevariables as arguments
|
import csv
import numpy as np
from random import randint
import matplotlib.pyplot as plt
# binaryLoss returns the average binary loss on the data given the weight vector
# @param input_data is a matrix where the last column is the class (1,2 or 3)
# and columns [0:n-1] is the feature vector
# @param weight is the wei... |
# This program solves a NxN maze
import numpy as np
import time
from os import system
class MazeSolver:
def __init__(self,array2D,startx,starty,endx,endy):
self.grid = array2D
self.grid_length = len(self.grid)
self.startx = startx
self.starty = starty
self.endx = endx
... |
"""
Welcome to Tic Tac Toe!
Please input an answer:
An answer of "!STARTAI" will play against the computer.
An answer of "!START2P" will start a game for two players.
An answer of "!QUIT" will quit the game.
"""
#Version 0.2
#TODO:
#split game logic from input-output logic
#Add a gamestate class that allows for simp... |
from GeometricObject import GeometricObject
import math
class Circle(GeometricObject):
def __init__(self,radius,color,filled):
super().__init__(color,filled)
self.__radius = radius
def getRadius(self):
return self.__radius
def setRadius(self,radius):
self.__radius = ... |
# -*- coding: utf-8 -*-
from pymongo import MongoClient
import pprint
from bson.son import SON
# Connect to the MongoDB, change the connection string per your MongoDB environment
client = MongoClient(port=27017)
# Set the db object to point to the business database
db=client.business
# Showcasing the count() method of ... |
import logging
class SeaMap:
""" Class for processing a file with sea battle map """
# todo: make better exceptions
def __init__(self, map_path: str, ship: str, empty: str):
self.__map_path = map_path
self.__ship_sign = ship
self.__empty_sign = empty
self.number_of_ships = 0... |
def TheRabbitsFoot(s, encode):
a = s
flag = encode
if(flag == False):
lengh = len(a.replace(' ', ''))
string = [[]]
j = 0
y = 1
for i in a:
if(i == ' '):
string.append([])
j += 1
y += 1
if(i != ' ... |
#Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be:
#1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
#By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms.
#Oh c... |
a,b = input().split(" ")
a = input().split(" ")
b = input().split(" ")
flag = 1
# for i in b :
# if i not in a :
# flag = 0
# break
# else :
# a.remove(i)
# if flag :
# print ("Yes")
# else :
# print ("No")
# creating a hash table
a_hash_table = {}
b_hash_table = {}
for i in a :
a_hash_table[i] = a.count(... |
import numpy as np
import math
#using the least squares method make a linear fit to the data
x= [0,1,2,3]
y= [0, 2, 6 , 12]
weight = [1,1,1,1]
f=lambda x: a*x**2+b*x
f_a= lambda x: x**2
f_b= lambda x: x
def calcB(x, y, weight):
B_1=0
B_2=0
for i in range(len(x)):
B_1 += weight[i]*y[i]*f_a(x... |
#Leia o peso em kg e altura da pessoa e mostre seu IMC#
altura = float(input('Qual sua altura? '))
peso = float(input('Qual seu peso em Kg? '))
imc = peso / (altura**2)
if imc <18.5:
print('Abaixo do peso')
elif imc>=18.5 and imc<25:
print('Peso normal')
elif imc>=25 and imc<=30:
print('Sobrepeso')
elif imc... |
# faça um programa que leia os valores dos catetos e calcule a hipotenusa #
import math
co = float(input('Comprimento do cateto oposto: '))
ca = float(input('Comprimento do cateto adjacente: '))
hi = math.hypot(co,ca)
print('A hipotenusa vale {:.2f}'.format(hi)) |
# Faça um programa que leia o nome da pessoa e mostre boas vindas #
nome = input("Qual o seu nome: ")
print("Boas vindas,", nome) |
def area(l,c):
a = l*c
print('A area vale {:.2f} m²'.format(a))
# principal
print('Contole de Terreno')
print('-'*20)
l = float(input('Largura (m): '))
c = float(input('Comprimento (m): '))
area(l,c) |
#Faça a tabuada de um número escolhido pelo usuario usando o laço for#
num = int(input('Digite um número para ver sua tabuda: '))
for c in range(1,11):
print('{} x {} = {}'.format(num,c,num*c)) |
# escreva uma expressão e veja se ela está correta ou errada #
expressao = (input('Digite uma expressão matemática: '))
lista = []
for i in expressao:
if i == '(' or i ==')':
lista.append(i)
check = 0
for j in lista:
if j == '(':
check += 1
elif j == ')':
check -= 1
if check < ... |
aluno = dict()
aluno['nome']= str(input('Nome: '))
aluno['media'] = float(input('Media: '))
if aluno['media']>=7:
aluno['situação'] = 'Aprovado'
elif 5<= aluno['media'] <7:
aluno['situação'] = 'Recuperação'
else:
aluno['situação'] = 'Reprovado'
print('=-'*30)
for k,v in aluno.items():
print('- {} é igu... |
# Analise dados de 4 pessoas #
somaIdade = 0
maior = 0
n = ''
quantidade = 0
for c in range(0,4):
print('----- {}° PESSOA -----'.format(c+1))
nome = input('Nome: ')
idade = float(input('Idade: '))
sexo = input('Sexo [M/F]: ').upper()
somaIdade += idade
if sexo == 'M':
if c == 1:
... |
# Faça um programa que leia um número qualquer e mostre seu fatorial #
n = int(input('Digite um número para calcular seu Fatorial: '))
c = n
total = 1
while c > 1:
total = total * c
c = c-1
print('O fatorial de {}! é {} '.format(n,total)) |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from runner.koan import *
import re
class AboutRegex(Koan):
"""
This koans are based on the Ben's book: Regular Expressions in 10 minutes.
I found this book very useful so I decided to write a koans in order to practice everything I had learned from it.... |
# Little Bob loves chocolate, and he goes to a store with $N$N in his pocket. The price of each chocolate is $C$C. The store offers a discount: for every MM wrappers he gives to the store, he gets one chocolate for free. How many chocolates does Bob get to eat?
#
# Input Format:
# The first line contains the number of ... |
class Heap(object):
def __init__(self, is_min=True):
self.items = []
self.is_min = is_min
def insert(self, k):
self.items.append(k)
child_index = len(self.items) - 1
parent_index = self.get_parent_index(child_index)
if not self.is_child(child_index, parent_inde... |
'''
Sample Input
3
{[()]}
{[(])}
{{[[(())]]}}
Sample Output
YES
NO
YES
'''
OPEN = ('{', '(', '[')
CLOSE = ('}', ')', ']')
PAIRS = (('{', '}'), ('(', ')'), ('[', ']'))
def is_matched(expression):
s = Stack()
for x in expression:
if x in OPEN:
s.push(x)
elif x in CLOSE:
... |
'''
Input (stdin)
2
1 2 3 4 5 6 7
Your Output (stdout)
Yes
Expected Output
Yes
Case 6
Input
4
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 16 18 19 20 21 22 23 24 25 26 27 28 29 30 31
Output
No
Case 1
Input
4
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
Output
No
Case 3
Input
2
1 2 2 ... |
def fib(n):
if n == 1 or n == 0:
return 1
else:
return fib(n - 1) + fib(n - 2)
f = [0, 1] + [None]*100
def fib1(n):
print 'getting fib1 of %d' %(n)
if f[n] is None:
f[n] = fib1(n-1) + fib1(n-2)
return f[n]
def main():
print('123')
print(fib1(8))
|
import random
class Ant:
def __init__(self, start_x, start_y):
"""
Creates an ant.
:param start_x: the starting x coord
:param start_y: the starting y coord
"""
self.x = start_x
self.y = start_y
self.state = 'empty'
def change_state(self)... |
def addition(a, b):
a = int(a)
b = int(b)
c = a + b
return c
def subtraction(a, b):
a = int(a)
b = int(b)
c = b - a
return c
def multiplication(a, b):
a = int(a)
b = int(b)
c = a * b
return c
def division(a, b):
a = int(a)
b = int(b)
c = b / a
c = ro... |
#!/usr/bin/env python
"""
run_length.py
Python script for the Python "Run Length Encoding", 'exercism' exercise.
Implement run-length encoding and decoding.
Run-length encoding (RLE) is a simple form of data compression, where runs
(consecutive data elements) are replaced by just one data value and count.
Created b... |
#!/usr/bin/env python
"""
series.py
Python script for the Python "Series", 'exercism' exercise.
A program that will take a string of digits and give you all the contiguous substrings of length `n` in that string.
Created by: shamdela
Date: 07/10/2016
"""
def slices(digits, series):
if series == 0 or ser... |
#!/usr/bin/env python
"""
scrabble_score.py
Python script for the "Scrabble Score", 'exercism' exercise.
A program that given a word, computes the scrabble score for that word.
Created by: shamdela
Date: 28/11/2016
"""
import re
SCORE_DICT = {'a': 1, 'e': 1, 'i': 1, 'o': 1, 'u': 1, 'l': 1, 'n': 1, 'r': 1, 's'... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.