text stringlengths 37 1.41M |
|---|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Aug 23 22:59:00 2017
@author: habiba
script that converts Celsius to Fahrenheit and
creates a text file and stores the converted values inside the text file
Write a program that converted Celsius degrees to Fahrenheit
Consider the following list:
tem... |
import math
#l=[1,2,None,None,None,8,10,9,None,None,8]
def fillNone(num_list):
#this function find where None value start and where end
#and pass start and end index,None count to setMean function with list
start_none=False
count=0
for i in range(0,len(num_list)):
if num_list[i]==None and... |
salario = float(input('Quanto de salario voce ganha atualmente? R$'))
a = salario + (salario * 15/100)
print(f'O aumento salarial foi de 15%, entao voce recebera no proximo pagamento {a}')
|
dia = int(input('Quantos dias ficou com o carro?'))
valor1 = dia * 60
km = float(input('Quantos km rodou desde que pegou o carro?'))
valor2 = (km * 0.15)
conta_final = valor1 + valor2
print(f'Por dias usados o valor fica em {valor1}R$, em km rodado {valor2:.0F}R$, voce precisa pagar {conta_final:.0F}R$')
|
def maybe_return_el_at_tuple(tupla: tuple, el):
return tupla.index(el)
def return_two_tuples(tupla: tuple):
len_tuple = int(len(tupla)/2)
return tupla[0:len_tuple], tupla[len_tuple:int(len_tuple*2)]
def remove_el_tuple(tupla: tuple, el):
lista = list(tupla)
lista.remove(el)
new_tuple = tuple... |
import requests
from bs4 import BeautifulSoup
import pandas as pd
url = "https://fgopassos.github.io/pagina_exemplo/estadosCentroOeste.html"
requisicao = requests.get(url)
if requisicao.status_code != 200:
requisicao.raise_for_status()
else:
print("Conectado com Sucesso")
html = requisicao.text
soup = Beauti... |
"""
Usando Python, faça o que se pede (código e printscreen)
"""
# a - Crie uma lista vazia
list = []
# b - Adicione os elementos: 1, 2, 3, 4 e 5, usando append()
list.append(1)
list.append(2)
list.append(3)
list.append(4)
list.append(5)
# c - Imprima a lista;
print(list)
# d - Agora, remova os elementos 3... |
def potencia(a, b):
return (a**b)
n1 = int(input("insira um numero inteiro: "))
n2 = int(input("insira um numero inteiro: "))
if n1 and n2 >= 0:
print('O resultado é', potencia(n1, n2))
else:
print("Digite numeros inteiros positivos")
|
luna=[28,29,30,31]
n=int(input("n="))
if n in luna:
if n==luna[0]:
print("Februarie")
elif n==luna[2]:
print("Aprilie,Iunie,Septembrie,Noiembrie")
elif n==luna[3]:
print("Ianuarie,Martie,Mai,Julie,August,Octombrie,Decembrie")
elif (n==luna[1]):
anul=int(input("a... |
#Written by Paul Wallace March 8th, 2016
class Writer:
"""
Method to write n (num_addresses) addresses to a new file while incrementing
"""
def writeAddresses(self, num_addresses, old_file_name, new_file_name):
#initialize constants to avoid hard coding
ONE = 1
TWO = 2
... |
sum = 0
for i in range(1,1000) :
if(i%3==0 or i%5==0) :
sum = sum + i
print sum
|
from collections import Sized, Hashable, Iterable, Container
class Vertex(object):
"""
Represent a Vertex of a Graph. Each Vertex has a name and may be connected
to unlimited amount of other Vertices.
"""
name = None
def __init__(self, name):
super(Vertex, self).__init__()
... |
from collections import defaultdict
global time
class Node:
def __init__(self,name):
self.name = name
self.ChildNodes = []
self.predecessorNode = None
self.start = 0
self.finish = 0
def DFS(Nodes,s):
global time
time = 0
for node_name in ['s','t','u', 'w', 'v', 'y', 'x', 'z']: #Nodes.keys():
if Node... |
"""annotator_distance.py - statistical significance of distance between genomic segments
=====================================================================================
Purpose
-------
The script :file:`annotator_distance.py` computes the statististical
significance of the association between segments on a geno... |
'''
r_table2scatter.py - R based plots and stats
============================================
:Author: Andreas Heger
:Release: $Id$
:Date: |today|
:Tags: Python
Purpose
-------
This script reads a table from a file or stdin.
It can compute various stats (correlations, ...)
and/or plot the data using R.
Usage
-----... |
import mrs_strings as Strings
import csv
import os
# reades the original csv - reads the MRS keys and values
def read_series_MRS_keys_values(path):
with open(path, 'rb') as csvinput:
reader = csv.reader(csvinput)
# read the headers row.First time we do reader.next we get the first row
k... |
from datetime import datetime
if __name__ == '__main__':
date1 = datetime.strptime("2016-09-01", "%Y-%m-%d")
date2 = datetime.strptime("2016-09-02", "%Y-%m-%d")
print (date1-date2).days
|
# Determinar la cantidad de dígitos de un número ingresado
import math
def digitos(n):
if n < 0:
n *= -1
if n != 0:
return math.floor(math.log10(n)) + 1
return 1
try:
n = int(input('Ingrese un número entero: '))
print('El número', n, 'tiene', digitos(n), 'dígitos')
except ValueE... |
# Implementar la clase Persona que cumpla las siguientes condiciones:
# Atributos:
# - nombre.
# - edad.
# - sexo (H hombre, M mujer).
# - peso.
# - altura.
# Métodos:
# - es_mayor_edad(): indica si es mayor de edad, devuelve un booleano.
# - print_data(): imprime por pantalla toda la información del objeto.
# - genera... |
# Escribir una función mas_larga() que tome una lista de palabras y devuelva la más larga
def mas_larga(palabras):
larga = ''
for p in palabras:
if len(p) > len(larga):
larga = p
return larga
assert mas_larga(['hola', 'mundo', 'cadena', 'palabra']) == 'palabra'
assert mas_larga(['pal... |
import random
mylist=[] # Generate random number on the list
x = int(input("Masukkan jumlah data yang akan diiterasi: "))
for i in range(x):
mylist.append(random.randrange(1,200))
def maxima(list_a):
indexing_length = len(list_a)-1 #[1,2,3,4,5==> tdk bisa dibandingkan karena paling kanan]
sorted = False
... |
barang = {}
pilih1 = ""
while pilih1 != "5" :
print("===========LIST DATA BARANG===========")
print("1. Cetak isi daftar barang\n2. Menambahkan data ke daftar barang\n3. Menghapus data dari daftar barang\n4. Mengubah data dalam daftar barang\n5. Exit")
print("\n")
pilih1 = input("Masukkan pilihan a... |
a=10
b=82
if a>b:
print("A is greater")
else:
print("B is greater.")
# Key Value
fees={'Java':10000,'Python':12000,'Android':15000}
print("Java fees @ out institute is :-",end="")
print(fees.get("Java","invalid"))
print(fees.get('java','invalid'))
print(f"{a} and {b} are 2 numbers")
print(a,"... |
"""Ladybug analysis period class."""
from .dt import DateTime
from datetime import datetime, timedelta
class AnalysisPeriod(object):
"""Ladybug Analysis Period.
A continuous analysis period between two days of the year between certain hours
Attributes:
stMonth: An integer between 1-12 for starti... |
import turtle
class Bullet_Handler():
def __init__(self):
self.bullet_list = []
def create_bullet(self, move_speed, is_enemy):
bullet = Bullet(move_speed, is_enemy)
return bullet
def advance_bullet(self):
for bullet in self.bullet_list:
bullet.forward(bullet.... |
#PROGRAM TO GENERATE AN APPROPRIATE GREETING
name = input("Enter your name: ")
#T_O_D stands for time of the day(either morning, afternoon or night)
T_O_D = (input("What time of the day is it: "))
if T_O_D >= 6:00 and T_O_D < 12:00:
print("Hi " + name + " and good " + T_O_D)
elif T_O_D == "afternoon":
... |
"""
Задача 36. Создать класс Транспортное средство и его потомков - классы Поезд и Самолет.
В родительском классе должно быть определено минимум 1 конструктор, 3 атрибута и 1 метод.
В классах-потомках должны быть добавлены минимум по 1 новому методу и по 1 новому атрибуту.
"""
class Vehicle():
EXTRA_CHARGE = 4
... |
import math
print('''Написать функцию решения квадратного уравнения.
def solve_quadratic_equation(a, b, c):
# always returns 2(!) values: either 2 roots, 1 root and None or 2 Nones
''')
def solved_equation(a, b, c):
print('Найдем решение квадратного уранвения: a*pow(x, 2) + b*x + c = 0')
a = float(a)
... |
import string
import random
def password():
pwd = ""
limits = [3, 3, 2]
for i in range(len(limits)):
delta = random.randint(1, limits[i] - 1)
limits[i] -= delta
limits[random.randint(0, len(limits) - 1)] += delta
sources = [ string.ascii_lowercase,
string.asc... |
import random
print("""Задача №12. Для проверки остаточных знаний учеников после летних каникул,
учитель младших классов решил начинать каждый урок с того, чтобы задавать каждому ученику пример из таблицы умножения,
но в классе 15 человек, а примеры среди них не должны повторяться. В помощь учителю напишите программу... |
print('''Условия задачи:
Два поезда движутся на скорости V1 и V2 навстречу друг другу. Между ними 10 км. пути. Через 4 км пути первый поезд
может свернуть на запасной путь. При заданных скоростях узнать столкнутся ли поезда.
def have_trains_crashed(v1, v2): # returns boolean value ''')
def have_trains_crashed(v1, v... |
import re
def statement_syntax(text):
if_pattern = r'if\(.+\)(\n)*{(\n)?.+(\n)?}'
while_pattern = r'while\(.+\)(\n)*{(\n)?.+(\n)?}'
for_pattern = r'for\((.+=.+);(.+[\<\>]\=?.+);(.+);?\)(\n)*{(\n)?.+(\n)?}'
if 'if' in text:
if re.search(if_pattern, text):
pass
else:
... |
"""
Implementation of the class `Field`.
"""
import os
import numpy
from matplotlib import pyplot, cm
from mpl_toolkits.axes_grid1.inset_locator import inset_axes
class Field(object):
"""
Contains information about a 2D field (pressure for example) on a structured
Cartesian grid.
"""
def __init__(self, x... |
"""
PptxConstructor is the user interface to create the presentation file.
The steps are described as follows:
(1) Specifying the layout of the presentation file (width, height,...)
(2) Adding object by using add_object() method:
add_object(data, object_type, object_format, slide_page, location)
data: str or p... |
import random
from abc import ABCMeta, abstractmethod
class AttackStrategy:
__metaclass__ = ABCMeta
@abstractmethod
def select_squad(self, army):
"""A choice of a squad according to a strategy.
Args:
army: Army.
"""
pass
class Random(AttackStrategy):
"""... |
"""
ex02, task C. Bubble sort.
"""
def bubble_sort(data):
"""
Takes a list or tuple of sortable elements and sorts it by the "Bubble sort" method.
:param data: list or tuple
:return: sorted list
"""
if type(data) == tuple:
data = list(data)
sorted_data = data
for i in range(l... |
# -*- coding: utf-8 -*-
"""
ex04 task A: two random number generator classes.
"""
__author__ = 'Åshild Grøtan'
__email__ = 'ashild.grotan@nmbu.no'
class LCGRand:
""" Implements a linear congruential generator (LCG) to generate
random numbers.
"""
def __init__(self, seed):
self.random = seed
... |
# coding=utf-8
class testcase(object):
def get_add(self, a, b):
return a+b
class Subject(object):
def __init__(self, subject):
self.subject1 = subject
self.subject2 = 'cpp'
def __getattribute__(self, item):
if item=="subject1":
return "review python"
... |
# фунция которая добавляет компании новый локомотив (мощность, габариты) и сохранить в pickle
# создать функцию, которая читает все тепловозы этой компании в список
import pickle
FILE_name = 'File'
def write_Train(*kwargs):
lok = []
name = str(input('Vvedite nazvanie poezda'))
pwr = str(input('Vvedite mos... |
"""
Calculates statistics like most wins by a franchise, most wins by a coach, most
mvps by player based on Super Bowl data.
"""
import csv
from collections import Counter
from collections import namedtuple
legacy_franchises = {
"Indianapolis Colts": "Baltimore Colts",
"Los Angeles Chargers": "San Diego Charg... |
print("hello world");
#숫자형 자료형
print(4096)
#사칙연산
print(1 + 2)
print(3 ** 4)
#제곱, 몫, 나머지 연산자
print(1 ** 2)
print(3 // 4)
print(5 % 6)
# 변수
my_int = 1
my_str = 'python'
my_bool = True
my_list = [1, 2, 3]
print(my_bool)
#복합 할당 연산자 : += -+ *= /=
count = 0
count += 1
count -= 5
count *= 2
print(count);
#뱐수 이름
my_int1... |
import matplotlib.pyplot as plt
import numpy as np
from common.data_handler.artificial_regression import linear_2d
class linear_regression:
def __init__(self):
pass
def fit(self,x,y):
x = np.array(x)
y = np.array(y)
mux = np.mean(x)
muy = np.mean(y)
self.m = ... |
from bs4 import BeautifulSoup
import requests
from PyDictionary import PyDictionary
import random
# a dictionary to get synonyms of words in the menu
dictionary=PyDictionary()
# a function to return the daily menu in dictionary {'lunch': ..., 'dinner': ...} form
def get_menu():
site_response = requests.get("https... |
from datetime import datetime
# Class to create tweets.
class Tweet:
# Method ot assign initial values.
def __init__(self, name, text):
self.__author = name
self.__text = text
self.__age = datetime.now()
def get_author(self):
return self.__author
def get_text(self):
... |
from Tweet import Tweet
from datetime import datetime
import math
import pickle
def open_old_tweets():
try:
tweet_file = open("tweets.pickle", 'rb')
Tweets = pickle.load(tweet_file)
tweet_file.close()
return Tweets
except:
Tweets = []
return Tweets
def tweet_... |
"""
file: student_placer.py
language: python3
author: mal3941@g.rit.edu Moisés Lora Pérez
class: CSCI 141-03
"""
from building import *
from student import *
from room import *
from rooms import *
from floors import *
def readStudents(filename):
"""
This function opens the filename and return... |
"""
file: olympics_simpl.py
language: python3
author: mal3941@g.rit.edu Moisés Lora Pérez
class: CSCI 141-03
description: This program counts the number of gold medals in a given year and also counts the number of
medals that a certain athlete has been awarded.".
"""
def goldMedalinYear(year, filename):
... |
from myStack import *
def read_file(filename):
"""
This function opens the filename and returns the list of puzzles.
:param filename: textfile inputed
:return: puzzleList
"""
file = open(filename)
puzzleList = []
for currentLine in file:
puzzleList += currentLine.split(... |
"""
file: pycount.py
language: python3
author: sps@cs.rit.edu Sean Strout
description: Word Count Program for CS 141 Lecture
This version uses the built-in dict type.
"""
def word_count(filename):
"""Report on the frequency of different words in the
file named by the argument.
"""
d = ... |
"""
file: vlc.py
author: mal3941@g.rit.edu Moises Lora Perez
class: CSCI 141-03
"""
from rit_lib import *
from array_heap import *
from math import *
class SymbolObject( struct ):
"""
Represents a the symbol object.
:slot name (str): The name of the symbol.
:slot frequency (int): The symbo... |
from collections import Counter
def findDuplicate(nums):
ldupl = [i for i, cnt in Counter(nums).items() if cnt > 1]
return ldupl
def main():
T=int(input())
while(T>0):
n=int(input())
arr=[int(x) for x in input().strip().split()]
... |
class Solution(object):
def subtractProductAndSum(self, n):
"""
:type n: int
:rtype: int
"""
sum = 0
pro=1
for digit in str(n):
sum += int(digit)
pro *= int(digit)
return (pro-sum)
if __name__ == '__main__':
tc =... |
class shape:
def __init__(self, breadth, length):
self.b = breadth
self.l = length
def area(self):
area = self.b * self.l
print(area)
class rect(shape):
pass
class square(shape):
pass
print("enter the same value if square else different ")
s = rect(2, 13)
s.a... |
#!/usr/bin/python
"""
Project Euler
Problem 7
What is the 10001st prime number?
Example:
>>> p7(6)
13
"""
from primework import euler_sieve
def p7(n=10001):
i = 150000
p = euler_sieve(i)
while len(p) < n:
i *= 2
p = euler_sieve(i)
return p[n-1]
if __name__ == '__main__':
import doctest
doctest.testmod()
... |
from pathlib import Path
path = Path(__file__).resolve()
path = path.parent
file_path = path / "number_phone.txt"
def choice():
print('Главное меню\n'
'1. Зарегистрировать нового пользователя\n'
'2. Вывести список новых пользователей\n'
'3. Выход\n')
num_c = input('Сделайте выбор... |
#Recursividad
# def fibo(n):
# if n > 1:
# return fibo(n-1) + fibo(n-2)
# elif n==1 or n == 0:
# return 1
# elif n < 0:
# print('Valor inválido')
# print(fibo(16))
#Ejemplos
# Cuenta regresiva
# def cuenta_regresiva(num):
# num -= 1
# if num > 0:
# print(f'{num}')... |
# Importing specific functions from a module is possible.
from math import sqrt
# Entire module can be imported as well.
import math
# Some functions are available by default.
a = [1, 2, 3]
len(a)
# "sqrt" function can be called upon specific to get its square root.
sqrt(4)
# Number "pi" can be accessed via "math"... |
# Andrew Li
# 1824794
print("Birthday Calculator")
print("Please enter all values numerically.\n")
current_day = int(input("Enter current day: ")) # asks user for date input and converts to int
current_month = int(input("Enter current month: "))
current_year = int(input("Enter current year: "))
prin... |
"""A simple program to create a GUI to communicate with an Arduino and toggle an LED on and off.
Created to demonstrate how to use Python with tkinter to create a GUI.
- Colin Diehl
"""
from tkinter import * #import the modules for the GUI
import serial #and the serial communications
PORT = "COM5"
ser = serial... |
#The rules used by Pig Latin are as follows:
#If a word begins with a vowel, just as "yay" to the end. For example, "out" is translated into "outyay".
#If it begins with a consonant, then we take all consonants before the first vowel and we put them on the end of the word.
# For example, "which" is translated into "... |
import Utils
def do_Jarvis(point_list):
"""
Jarvis March method to solve Convex Hull
:param point_list: set of Utils.Points
:return: hull_list: list of Utils.Points on hull
"""
hull_list = [Utils.get_lowest_point(point_list)]
for hull_point in hull_list:
next_point = point_list[0]
... |
class Node:
def __init__(self,data):
self.__data=data
self.__next=None
def get_data(self):
return self.__data
def set_data(self,data):
self.__data=data
def get_next(self):
return self.__next
def set_next(self,next_node):
... |
# 1. Create a dictionary called zodiac with the following inforation.
# Each key is the name of the zodiac
# zodiac = {
# "Aries" : "The Warrior",
# "Taurus" : "The Builder",
# "Gemini" : "The Messenger",
# "Cancer" : "The Mother",
# "Leo" : "The King",
# "Virgo" : "The ... |
# Created by: Aden Rao
# Created on: March 2nd, 2019
# This program you put in the diameter of a circle and it will calculate the area and circumference of the circle.
# Input for the user to put the diameter in
diameter = int(input( ' enter the diameter: '))
# Math calculations and formulas
import math
... |
# Automatic scheduler for CMU PreCollege Program
import sys
import math
# Class to handle times.
class TimeStamp:
# Reference day in order to keep track of which day each TimeStamp is
# The first day of the year 2000 was a Saturday (6 = Saturday)
referenceYear = 2000
referenceDay = 6
# Dictionar... |
# coding: utf-8
# wallet = 5000
# computer_price = 900
# # vérifier que le prix de l'ordinateur est inférieur a 1000e
# if computer_price < 1000:
# print("le prix de l'ordinateur est inférieur à 1000")
# else:
# print("le prix de l'ordinateur est supérieur à 1000")
# while wallet > computer_price:
# print("... |
i=9
j=1
while j<=9:
print(j*' '+i*'* ')
i=i-2
j=j+2
i=3
j=7
while i<=9:
print(j*' ' + i*"* ")
i=i+2
j=j-2
|
__author__ = 'Orka'
import random
class MovieRandom(object):
def __init__(self, movie_list):
self.movie_list = movie_list
def return_random_movie(self):
if type(self.movie_list) is list:
list_length = len(self.movie_list)
random_number = random.randrange(lis... |
"""
For this week's exercise I want you to write a function that accepts a sequence (a list for example) and returns a new iterable (anything you can loop over) with adjacent duplicate values removed.
For example:
>>> compact([1, 1, 1])
[1]
>>> compact([1, 1, 2, 2, 3, 2])
[1, 2, 3, 2]
>>> compact([])
[]
There are two... |
def start():
print ("You are trapped in a room. ", end="")
room0()
def process_user_movement(description, doors):
#Print description of room
print(description, end=" ")
#Print available doors
print("There are %s doors in the room:" %len(doors))
for key in doors.keys():
print (str(k... |
def calculate_total_cost(default_tax_rate, state_abbr, cost):
""" Calculate an item cost by adding tax appropriate for state.
For example::
>>> calculate_total_cost(5, "CA", 20)
21.4
>>> calculate_total_cost(10, "AK", 10)
11.0
>>> calculate_total_cost("", "ME", 10)
... |
def init(_maxcount=20):
#Initiate scoreboard
global scoreboard
global maxcount
scoreboard = []
maxcount = _maxcount
def addScore(name, score, descend = True):
#Add score to scoreboard
global scoreboard
scoreboard.append((name,score))
scoreboard = sorted(scoreboard, key=lambda scoreb... |
#Made for the sole purpose of GCI 2019
import sys
import os
import socket
ip = input("Enter IP: ")
z=0
try:
m1= int(input("Enter starting port:"))
m2=int(input("Enter the last port:"))
if m2<m1:
print("Please enter a valid range")
elif m2>m1:
for i in range(m1,m2+1):
... |
for i in range(1,10):
for j in range(1,i + 1):
print(i, "*", j, "=", i*j, end=" ")
print(end="\n")
|
class ConsoleInterface:
def __init__(self, quiz):
self.__quiz = quiz
def run(self):
while self.__quiz.has_next_question():
question = self.__quiz.get_next_question()
answer = input(question + ' (True/False): ')
correct = self.__quiz.check_answer(answer)
if correct:
print('Y... |
#!/usr/bin/env python3
# *
# * *
# * * *
# * * * *
# * * * * *
# * * * *
# * * *
# * *
# *
count = 5
for i in range(count):
for j in range(i):
print("*",end = "") #end = "" disables newline
print("")
print("*****")
for i in range(count,0,-1):#range([start,] stop [, step]) -> range object
... |
#!/usr/bin/env python3
import re
#regex lib
pwd = (input("Enter your pass: "))
if (len(pwd)>8 and re.search("[a-z]",pwd) and re.search("[A-Z]",pwd)):
print("valid pass")
else:
print("Invalid pass") |
# What is the difference between these two pieces of code?
list1 = [1,2,3,4,5]
list2 = [1,2,3,4,5]
def proc(mylist):
mylist = mylist + [6, 7]
#return mylist
#print proc(list1)
def proc2(mylist):
mylist.append(6)
mylist.append(7)
#return mylist
#print proc2(list1)
# Can you explain the result... |
'''
list1 = [0, 1, 2]
list1 += [3, 0.5, 9]
list1.sort()
list1.reverse()
print list1
list1.append(10)
list2 = [3, 4, 5]
list1.append(list2)
list3 = list1 + list2
print list1
#print list2
#print list3
'''
import random
print "Random number generated: " + str(random.randint(0,10)) |
# Given your birthday and the current date, calculate your age
# in days. Compensate for leap days. Assume that the birthday
# and current date are correct dates (and no time travel).
# Simply put, if you were born 1 Jan 2012 and todays date is
# 2 Jan 2012 you are 1 day old.
# IMPORTANT: You don't need to solve t... |
from random import randint
def random_verb():
random_num = randint(0, 1)
if random_num == 0:
return "run"
else:
return "kayak"
#print random_verb()
def random_noun():
random_num = randint(0, 1)
if random_num == 0:
return "sofa"
else:
return "llama"
#pri... |
# Wednesday, December 7, 13:16, Odense, Denmark
# Define a procedure, median, that takes three
# numbers as its inputs, and returns the median
# of the three numbers.
# Make sure your procedure has a return statement.
def bigger(a,b):
if a > b:
return a
else:
return b
def biggest(a,b,c):
... |
class Ingredient(object):
def __init__(self, name, weight):
self.name = name
self.weight = weight
class Pizza(object):
dough = ''
sauce = ''
Ingredients = []
def __init__(self, dough, sauce, price):
self.dough = dough
self.sauce = sauce
self.price = price
... |
# Составьте программу relativelyp rime . ру, получающую один аргумент командной строки n и
# выводящую таблицу n х n, где • устанавливается в строке i и столбце j, если
# наибольший общий делитель i и j составляет 1 (i и j являются относительно простыми множителями),
# и пробел в противном случае.
import s... |
# В отличие от гармонических чисел, сумма последовательности 1/12 + 1/22 + + ... + 1/п2 действительно сходится к
# константе при п, стремящемся к бесконечности. (Поскольку эта константа -тr2/6, данная формула используется для вычисления
# значения числа л.) Какой из следующих циклов for вычисляет эту сумму?
# Подр... |
# Предположим, что х и у имеют тип float и представляют координаты (х, у) точки на Декартовой плоскости.
# Составьте выражение для вычисления расстояния ОТ ЭТОЙ ТОЧКИ ДО ИСХОДНОЙ.
import math
x = 3.0
y = 4.0
# т.к. точка исходная, то ее координаты (0,0)
print(math.sqrt(x**2 + y**2)) |
# Студент-физик получил неожиданный результат при использовании кода force = G • mass1 • mass2 / radius * radius
# для вычисления значения по формуле F = Gm1m2/r2• Объясните проблему и исправьте код.
G = 10
mass1 = mass2 = 5
radius = 10
forceFstCase = G * mass1 * mass2 / radius**2 #1 вариант решения
forceSndCase = (... |
# Составьте программу, получающую два положительных целых числа в аргументах командной строки
# и выводящую False, если любой из них больше или равен сумме двух других, и True в противном случае.
# (Примечание: этот код проверяет, могут ли эти три числа быть длинами сторон некоего треугольника.)
import sys
if ... |
# Составьте программу, вычисляющую произведение
# двух квадратных матриц логических переменных,
# используя оператор оr вместо + и оператор and вместо *·
import random
arraySize = 4
def fillMatrixWithRandomBoolValues(array):
array.clear()
for i in range(0, arraySize):
tmp = []
for i in... |
# Переделайте программу tenhellos. ру, объединив ее с программой hellos.ру
# так, чтобы она получала в аргументе командной строки количество выводимых строк.
# Можно считать, что аргумент меньше 1 ООО. Подсказка: чтобы решить,
# когда применять st, nd, rd или th при выводе i-го
# сообщения Hello, используйте выраж... |
#!/usr/bin/python3
""" Coins module """
def makeChange(coins, total):
""" Function to determine the fewest number of coins """
if total == 0:
return 0
coins.sort(reverse=True)
sum = 0
i = 0
c = 0
num_coins = len(coins)
while sum < total and i < num_coins:
while coins[i]... |
# Crie uma função que receba os valores do nome,
# idade e e-mail de uma pessoa e guarde-os em um
# dicionário com as chaves ‘nome’, ‘idade’ e ‘email’,
# respectivamente. Sua função deve retornar esse dicionário.
nome = input('Qual seu nome?')
idade = input('Qual a sua idade?')
email = input('Digite seu e-mail:')
d... |
#Faça um programa que peça um número e mostre se ele é positivo ou negativo.
x = input('Poderia digitar um número agora?'+ '\n * Digite 1 = SIM ou 2 = NÃO *\n')
if x == '1':
n = int(input('Digite um número:'))
if n>=0:
print ("positivo")
else:
print ("negativo")
else:
print('Fec... |
#Faça um programa que peça um valor monetário e aumente-o em 15%. Seu programa deve imprimir a mensagem “O novo valor é [valor]”.
x = float(input('Digite um valor monetário:'))
y = x*0.15 resp = x + y
print('O novo valor é de:', resp)
|
# Faça uma função que recebe o valor do raio de um círculo e
# retorna o valor do comprimento de sua circunferência: C = 2*pi*r.
import math
raio = 10
def circunferencia(raio):
circu = 2*(math.pi)*raio
return circu
print(circunferencia(raio)) |
# Faça uma função que recebe valores a, b e c, resolve a equação quadrática a*x**2 + b*x + c = 0 e retorna:
# a. o valor de Δ onde Δ = b**2- 4*a*c
# b. uma tupla com o valor do ponto de mínimo ou máximo: x_m = -b/(2*a) e y_m = -Δ/(4*a);
# c. uma lista contendo as raízes (a lista pode ser vazia, caso Δ<0; pode conter ap... |
# Agora faça uma função que recebe uma palavra e diz se ela é um palíndromo, ou seja, se ela é igual a ela mesma ao contrário.
# Dica: Use a função do exercício 6.
frase = input("Qual a frase? ").upper().replace(" ", "")
if frase == frase[::-1]:
print("A frase é um palíndromo")
else:
print("A frase não é um pa... |
#Faça um programa em que o usuário tem que adivinhar o número escolhido pelo computador. O computador deve sortear um número inteiro de 1 a 5 e pedir para o usuário tentar descobrir qual o número sorteado. Após o usuário digitar sua resposta, o programa deve dizer se ele acertou ou não. Dica: para sortear um número, vo... |
# Crie uma classe Quadrado, filha da classe Retângulo do exercício 2.
class Retangulo:
def __init__(self, lado_a, lado_b):
self.lado_a = lado_a
self.lado_b = lado_b
def area(self):
x = self.lado_a * self.lado_b
return print(f'A área do retângulo é de {x}')
class Quadr... |
# Crie uma classe Televisor cujos atributos são:
# a. fabricante;
# b. modelo;
# c. canal atual;
# d. lista de canais; e
# e. volume.
# Faça métodos para aumentar/diminuir volume, trocar o canal e sintonizar um novo canal,
# que adiciona um novo canal à lista de canais (somente se esse canal não estiver nessa lista).... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.