text
stringlengths
37
1.41M
""" 10-6. Addition: One common problem when prompting for numerical input occurs when people provide text instead of numbers. When you try to convert the input to an int, you’ll get a TypeError. Write a program that prompts for two numbers. Add them together and print the result. Catch the TypeError if either input...
""" 2-6. Famous Quote 2: Repeat Exercise 2-5, but this time store the famous person’s name in a variable called famous_person. Then compose your message and store it in a new variable called message. Print your message. """ famous_person = "Srinivasa Ramanujan" message = "An equation for me has no meaning, unless it...
""" 3-7. Shrinking Guest List: You just found out that your new dinner table won’t arrive in time for the dinner, and you have space for only two guests. • Start with your program from Exercise 3-6. Add a new line that prints a message saying that you can invite only two people for dinner. • Use pop() to remove ...
""" 9-13. OrderedDict Rewrite: Start with Exercise 6-4 (page 108), where you used a standard dictionary to represent a glossary. Rewrite the program using the OrderedDict class and make sure the order of the output matches the order in which key-value pairs were added to the dictionary. """ from collections import...
""" 6-1. Person: Use a dictionary to store information about a person you know. Store their first name, last name, age, and the city in which they live. You should have keys such as first_name, last_name, age, and city. Print each piece of information stored in your dictionary. """ samuel = {"first_name": "samuel"...
""" 6-10. Favorite Numbers: Modify your program from Exercise 6-2 (page 102) so each person can have more than one favorite number. Then print each person’s name along with their favorite numbers. """ favorite_numbers = { "marie": [5, 6], "elliot": [14, 12], "samuel": [16, 3], "jerry": [19, 20, 21],...
b = True n = '' def checkIfSmallerThan1(a): if a < 1: return True else: return False while b == True: n = (input('Please enter a number bigger than 1: ')) try: n = int(n) except ValueError: print('Please enter a number bigger than 1:') else: b = checkIfSmallerThan1(n...
n = '' n = (input('Please enter a string: ')) def inverseWords(a): str1 = '' str2 = '' i = 0 c = False while i < len(a): if a[i] != ' ': str1 = str1 + a[i] i = i + 1 else: i = i + 1 c = True str2 = ' '+ str2 if c ...
# -------------- # USER INSTRUCTIONS # # Now you will put everything together. # # First make sure that your sense and move functions # work as expected for the test cases provided at the # bottom of the previous two programming assignments. # Once you are satisfied, copy your sense and move # definitions into the robo...
# Create a DOCUMENTED function with an explicit name and variables def Ingredients4Pancakes(pan, out=dict): # The """ """ syntax encloses the function documentation # It is automatically returnes by the ? syntax in the console """ Return the ingredients to make pan pancakes When fed a number of p...
list1=[] list2=[] a=int(input("Enter element to be assigned to first position")) list1.append(a); a=int(input("Enter element to be assigned to second position")) list1.append(a); x=list1[0]; list2.append(x); print("Second list is",list2)
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Mar 11 17:27:12 2019 @author: saskiajackson """ import numpy as np import matplotlib.pyplot as plt print( '-------------------------------TO RUN THE CODE-------------------------------') #below each function are a set of commented out lines that call t...
""" Create an implementation of the following: A line of credit product. This is like a credit card except theres no card. It should work like this: - Have a built in APR and credit limit - Be able to draw ( take out money ) and make payments. - Keep track of principal balance and interest on the line of credi...
import entity from utils import Point, rand def move_north(agent=None, entities=None, environment=None): """ Behavior that causes an agent to move north one unit. :param agent: The agent to perform the behavior. :param entities: A list of entities in the simulation. :param environment: The envir...
from machine import Pin, ADC, PWM #importing Pin, ADC and PWM classes from time import sleep #importing sleep class led=PWM(Pin(14), 5000) #GPIO14 set as pin and 5000Hz as frequency potentiometer=ADC(Pin(12)) #creating potentiometer object potentiometer...
#!/usr/bin/env python # coding: utf-8 # # Repeat 노드 # In[9]: import numpy as np # # 순전파 # D = 8 # N = 7 # x = np.random.rand(1,D) # (1,8) # # x = np.random.rand(D,).reshape(1,-1) # (1,8) # print(x,x.shape) # print('-'*70) # y = np.repeat(x,N,axis=0) # 수직(행) 방향, axis=0 # print(y,y.shape) # (7, 8) # # In[15...
"""Create sequence of random numbers and plot with matplotlib.pyplot Instructions: to get true random numbers, you should import "numpy", a number-crunching package on which visual is based. Numpy has several subpackages including "linalg" for doing linear algebra and "random" for doing random number generation. To ...
import imdb import requests from bs4 import BeautifulSoup as bs from docx import Document from docx.shared import * document=Document() # Create the object that will be used to access the IMDb's database. ia = imdb.IMDb() # by default access the web. # Search for a movie (get a list of Movie objects...
from translate import Translator def main(): your_lang = str(input("Enter Your Language : ")) convert_lang = str(input("Translate " +your_lang+ " to : ")) words = str(input("Enter word to be converted to " +convert_lang + " : ")) translator = Translator(from_lang = your_lang,to_lang = ...
import random def welcome(): pass def pick(): with open('words.txt') as f: lines = f.readlines() word = random.choice(lines).strip() return word def guess(char, word, placeholder, attempts): p_list = list(placeholder) if char in word: for i in range(len(word)): ...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Feb 9 18:06:29 2021 """ def construct_ordered_binaries(n: int): if n == 1: return ['0', '1'] ordered_binaries_previous = construct_ordered_binaries(n - 1) ordered_binaries = ['0' + p for p in ordered_binaries_previous] + \ ...
def print_depth(data, lvl=1): if type(data) is not dict: return None for k, v in data.items(): print("{0} {1}".format(k, lvl)) if type(v) is dict: print_depth(v, lvl=lvl+1)
class TreeNode: def __init__(self, data, parent = None): self.data = data #data being the sugar in this case self.children = [] #list to store children tree nodes self.parent = parent #place to store parent if applicable self.depth = 0 #depth just refers to length of the structure def addOdd(self, sugar): ...
import datetime print('Is Today Monday?') today = datetime.date.today() if today.weekday() == 1: print('Yes.') else: print('No.')
def piramida_do_lewej(wysokosc): for poziom in range(wysokosc): print("#" * (2*poziom+1)) piramida_do_lewej(5) def piramida(wysokosc): for poziom in range(wysokosc): print((" " * (wysokosc-poziom)),"#" * (2*poziom+1)) piramida(5)
#!/usr/bin/env python import sys # input comes from STDIN (standard input) for line in sys.stdin: line = line.strip() s = line.split(",") country, market = line.split(",") results = [market, "1"] print("\t".join(results))
# based on the big 5 from experimentall psychology +evil/good +race relations def get_race_character(race): if race == "human": race_character = CHARACTER_HUMAN elif race == "elf": race_character = CHARACTER_ELF elif race == "dwarf": race_character = CHARACTER_DWARF elif race ==...
def computepay(h,r): h = float(h) r = float(r) if h>40: p = 40*r + ((h-40)*1.5*r) return p hrs = input("Enter Hours:") rate = input("Enter rate per hour:") p = computepay(hrs,rate) print("Pay",p)
from typing import Any, Dict, List, Set, Tuple object_1 = { "name": "John", "age": 30, "address": { "city": "New York", "state": "NY", "zip": "10001" } } object_2 = { "name": "John", "age": 30, "address": { "city": "Boston", "state": "MA", "zip": "02108" } } def deep_equals(o...
i=63 print(i) print('this is my test') r=input('please enter radius') r=float(r) a=3.14*r*r print('the area is ',a)
def do_calculation(): command=input("Enter your command") print("lets " + command + " some numbers") input1 = input("Number 1>") input2 = input("Number 2>") number1 = int(input1) number2 = int(input2) if command == "+": result = number1 + number2 elif command == "subtract": ...
from tkinter import * import tkinter.messagebox #you have to import messagebox because it is a submodule and submodules arent automatically imported base = Tk() #first parameter allows you to change window title tkinter.messagebox.showinfo("Joelle's Program", "Soy un ouevo") answer = tkinter.messagebox.askquestion("...
from tkinter import * def doNothing(): print("ok ok I won't...") # ------------ Main Menu ------------- # base = Tk() myMenu = Menu(base) base.config(menu=myMenu) # .config configures menu for you # parameter name is menu subMenu = Menu(myMenu) # subMenu goes INSIDE of menu myMenu.add_cascade(label="File", m...
n = 25 threshold = 0.001 approximation = n/2 # Start with some or other guess at the answer count = 0 while True: count += 1 better = float(approximation + n/approximation) / 2 if abs(approximation - better) < threshold: print("better %s" % better) break approximation = better pri...
def htoi(str): if str[0:2].lower() == "0x": str = str[2:] ret = 0 dig = len(str) for c in str: dig -= 1 add = 0 if 48 <= ord(c) and ord(c) <= 57: add = (ord(c) - 48) elif 65 <= ord(c) and ord(c) <= 70: add = (ord(c) - 55) elif 97 <= ord(c) and ord(c) <= 102: add = (ord(c) - 87) else: raise...
import homework08 l = int(input("请输入长度:")) w = int(input("请输入宽度:")) # 实例化类 r = homework08.Rectangle(l, w) # 求周长 r.get_perimeter() # 求面积 r.get_area()
class Solution: def Fibonacci(self, n): if n == 0: return 0 elif n == 1: return 1 else: res = [0]*(n+1) res[0] = 0 res[1] = 1 res[2] = 1 for i in range(2, n + 1): res[i] = res[i - 1] + res[i ...
value = input() try: type_value = type(value) if type_value == 'str': value = int(value) else: pass except ValueError: print('Буквы в цифры не преобразовать!') finally: print('Дошел до finally') # test # ghbdtn - error # 567 - all right print(value)
class PriorityQueue: def __init__(self,element): self.queue = [element] def add(self, element): i = 0 if self.isEmpty(): self.queue = [element] return while i < len(self.queue) and element[1] < self.queue[i][1]: i += 1 self.queue.i...
import turtle import keyboard class Lefthandrule(turtle.Turtle): def __init__(self, finish, walls): turtle.Turtle.__init__(self) self.shape("turtle") self.color("red") self.setheading(270) self.penup() self.speed(0) self.finish = finish self.walls = ...
import RPi.GPIO as GPIO #Import Raspberry Pi GPIO library import I2C_driver as LCD import time GPIO.setwarnings(False) #Ignore warning for now GPIO.setmode(GPIO.BOARD) #Use physical pin numbering LED=11 Switch =15 GPIO.setup(LED, GPIO.OUT, initial=GPIO.LOW) #Set pin 15 to be an input pin and set initial value to ...
def reverseString(string): print string[2:0:-1] return string[::-1] def main(): reverseString("HelloWorld") main()
import random games_played = 1 print("Welcome to my game! Here are the rules:") print("") print("You are an international student and your goal is to reach the CMUQ campus. In order to do so, you will have to pass from four stages. In each stage you will get to choose between two options, but only one of them is the ...
#loop_ex2.py from matplotlib.pyplot import * from numpy import * myvect= ['a','b',3] N = len(myvect) for i in range(N): item = myvect[i] print('i = '+str(i)) print('item = '+str(item)) for item in myvect: print(item) print('this is the end of the loop')
#grosspay.py #Michael McCann from matplotlib.pyplot import * from numpy import * Hours = int(input("Please enter the number of hours:")) RPH = int(input("please enter the rate per hour:")) if (Hours < 40): print('You worked less than 40 hours and your rate of pay is $'+str(RPH)+' per hour.') grosspay_under40= (Hou...
a = '*' #a = *號 for i in range(1,13,2): # i 從1開始 間隔2個 到13 有 1,3,5,7,9,11 print("{0:^11s}".format(a*i)) #有11隔空格可以讓a*i值放入 ^:置中的意思 for i in range(9,0,-2): print("{0:^11s}".format(a*i))
import matplotlib.pyplot as plt import numpy as np X = np.arange(0,10) Y1 = 0.05*X*X plt.ylim(0, 5) plt.plot(X, Y1, color='blue') plt.fill_between(X, Y1, color='red', alpha='0.5') plt.show()
def binary_search(array, item): start = 0 end = len(array) - 1 while start <= end: # 这两种写法是一样的,但 start + end 如果值很大容易溢出 # mid = (start + end) // 2 # 优化写法 mid = start + (end - start) // 2 if array[mid] == item: return True elif item < array[mid]: ...
class MyCircularDeque: def __init__(self, k: int): """ Initialize your data structure here. Set the size of the deque to be k. """ self._size = k self._len = 0 self._deque = [0] * self._size def insertFront(self, value: int) -> bool: """ Adds an...
# -*- coding: utf-8 -*- """ EE4483 Implement TWO different search algorithms to find x^1/3 of any real number. Note negative number too. (10 points) a. Please briefly explain the search strategies of the two algorithms. b. Prove that your algorithms guarantee to find the correct answer. c. Compare the two search algor...
# dado 3 numeros inteiros verificar se os 3 numeros podem formar um triangulo # eh triangulo se l1+l2 < l3, l1 + l3 < l2, l2 + l3 < l1 l1 = int(input("informe um lado do triangulo - 1\n")) l2 = int(input("informe um lado do triangulo - 2\n")) l3 = int(input("informe um lado do triangulo - 3\n")) if ((l1+l2) > l3 and (l...
import os from model.territory import Territory from model.county import County class Province(Territory): '''This is class representing province - inherit from Territory''' def __init__(self, name, types, number): self.list_of_county = [] self.number_of_province = number super().__in...
#!./env/bin/python3 import argparse import lsb_text as lsb import os from argparse import RawTextHelpFormatter __name__ = "__main__" usageExample = """ Examples about how to use this module:\n python lsb.py hide -f FILENAME -t TEXT It hide TEXT inside the a NEW_FILENAME file python lsb.py unhide -f FILENAME It unhid...
class ExtensionHandler: """ This class is used to detect the extension of a file. """ def __init__(self, input_file): self.input_file = input_file def get_extension(self): extension = self.input_file[::-1].split('.')[0][::-1].lower() return extension if len(extension) el...
# Complete the function to find the count of the most frequent item of an array. You can assume that input is an array of integers. For an empty array return 0 # Example # input array: [3, -1, -1, -1, 2, 3, -1, 3, -1, 2, 4, 9, 3] # ouptut: 5 def most_frequent_item_count(collection): counter = 0 for i in...
#calculating tip amount total = float(input("Enter the total amount: ")) tippercent=float(input("Enter the tip percentage: ")) # formatting the numbers into 2 decimal points tipamount =format((total * tippercent),".2f") print (f"The tip amount is {tipamount}")
# example for hypotenuse.py def calc(should_print=False): print(""" Name: Hypotenuse Length Operation : Finding length of the hypotenuse Inputs : a->int/float , b->int/float Outputs: c=>((a**2) + (b**2))**0.5 ->float Author : rajkumawat \n """) a = float(input("Enter a ...
# unpack คือการเอาของออกจาก list fruits = ["apple", "banana", "cherry"] # List same array ( x, y, z, ) = fruits print(x) print(y) print(z)
#print(5 + 3) # Prints: 8 #sum_value = 5 + 3 #print(sum_value) # Prints 8 #my_list = [] # Initialize an empty list #name = "John" # Initialize name variable to John #my_list = my_list + name # Adding the current my_list variable to the string name #print(my_list) # Prints: ['j','o','h','n'] #my_list = [1,2,3,4] # ...
class Point(object): __slots__ = ('x', 'y') def __init__(self, x, y): self.x = x self.y = y # def set(self, other): self.x = other.x self.y = other.y # def __copy__(self): return Point(self.x, self.y) # # + operator def __add__(self, other): return Point(self.x + othe...
# Ryan Soderberg # DS2000-Sec02 int_list = input("Enter a sorted list of integers each in the range (0-99): ").split( " " ) # Convert list of strings to list of integers int_list = [int(i) for i in int_list] # Calculate mean sum = 0 for i in int_list: sum += i mean = sum / len(int_list) # Calculate media...
import pandas as pd import plotly.express as px print(" Kyra is VERY lazy ! She works as an sports-science data visualizer. But she never completes her excel sheets manually! Her boss always complains about her. Will you help Kyra with her work by creating a simple Raw data to visualized data and automate the proce...
new_england_states = { 'Maine': 'ME', 'Vermont': 'VT', 'Massachusetts': 'MA', 'Connecticut': 'CT', 'Rhode Island': 'RI', 'New Hampshire': 'NH' } cities = { 'MA': 'Boston', 'NH': 'Manchester', 'CT': 'Hartford', 'VT': 'Burlington', 'ME': 'Portland', 'RI': 'Providence' } c...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sat Feb 11 00:04:11 2017 @author: pratyus """ def genPrimes(): yield 2 listOfPrimes = [2] currentNo = 3 while True: isPrime = True for x in listOfPrimes: if currentNo % x == 0: isPrime = False...
""" __author__ = 'Nicholas Widener' __author__ = 'Trent Weatherman' __version__ = 'October 2015' Vertex class reads in our graph and performs a depth first search on it and performs the transitive closure operation. Vertex class also checks for cycles in our graph. """ import sys from collections import defaultdict c...
""" Simple library for dealing with Dice Roll expressions You can define a dice roll expression and then get its value like this: d = DiceRollExpression("3d8") You'll get three random values between 1 and 8 presented in a list. E.g [3, 7, 2] @author James Ravenscroft """ import random from manalang import Ma...
# control statement # if statement temp = 40 if temp >= 40: print ("room is hot") age = 17 print ('voting system') if age > 17: print('congrats !!! you are eligible for voting') else: print('oh sorry!!! you are not eligible for voting process') age = 35 if ...
import math r = int(input()) def uclidean(r): area = math.pow(r,2)*math.pi print(round(area, 6)) def taxi(r): area = math.pow(r,2)*2 print(round(area,6)) uclidean(r) taxi(r)
from heapq import heappush, heappop import sys input = sys.stdin.readline #인접행렬이 아닌 인접 리스트 (딕트)를 사용하면 시간 초과가 일어나고 #이를 해결하기 위해서는 heap을 사용해야한다. # heapq는 항상 최소값만을 리턴 #BFS구현이랑 동일하지만 heap을 사용한다는 것만 다름 V,E = list(map(int,input().split(' '))) start = int(input()) graph = dict() for i in range(1,V+1): graph[i]=[] for i in ...
b = list(input()) def judge(): q=[] for i in b: if (i==')' or i==']') and not q: return False if i==')': val = q.pop() if val!='(': return False elif i==']': val = q.pop() if val!='[': return Fal...
import os.path from tempfile import gettempdir class File: def __init__(self, path, data=""): self.path = path if data: self.write(data) def __add__(self, file_to_sum): return File(os.path.join(gettempdir(), 'third.txt'), self.read() + file_to_sum.read()) def __str__(self): return self.path def __ite...
# Your code here import random import math from time import time def slowfun_too_slow(x, y): v = math.pow(x, y) v = math.factorial(v) v //= (x + y) v %= 982451653 return v dictionary = {} _s = time() def slowfun(x, y): """ Rewrite slowfun_too_slow() in here so that the program produc...
#part2 def number_of_bags_contained_in_color(color, contains_graph): contained = contains_graph[color] count = 0 i = 0 while i < len(contained): current_number, current_color = contained[i] count = count + current_number contained_by_current = contains_graph[current_color] ...
class Node: # --- Binary tree node --- # def __init__(self, data): self.data = data self.left = None self.right = None # --- Insert the data --- # def insert(self, data): if self.data: # --- Insert on the left if the value is smaller than the current value --- # if data < self.data: ...
""" Question 2 Write a Python program to accept the user's first and last name and then getting them printed in the the reverse order with a space between first name and last name """ def name(x,y): f_n = x[::-1] l_n = y[::-1] print(f_n + " " + l_n) first_name = input("Enter your first name") las...
# Clase que hará de modelo para la base de datos implemetada class Persona(object): #Contructor def __init__( self, idPersona, nombre, apellidoPaterno, apelidoMaterno, rut, observacion ): self.idPersona = idPersona self.nombre...
from PIL import Image, ImageFont, ImageDraw import textwrap, time def draw_text_and_border(border_colour, paragraph, expansion): width_text, height_text = draw.textsize(paragraph[0], font) current_width = (screen_width - width_text)/2 current_height = (screen_height - height_text)/2 - (screen_height/4) ...
# PROGRAMME Exercice4_POUR; # VARIABLE # N : ENTIER; # FACT : ENTIER; # DEBUT # ECRIRE ('Entrez la valeur de N : '); # LIRE(N); # TANT QUE (NON ENTIER(N) OU N <= 0) FAIRE # ECRIRE ('Erreur de saisie : "N" DOIT etre un entier positif, veuillez ressaisir'); # LIRE(N); # SI ...
def factorial(n): num = 1 while n >= 1: num = num * n n = n - 1 return num def main(m, n): limit = pow(10,9) + 7 if n < m: m, n = n, m n, m = n + m - 2, m - 1 num = factorial(n) / (factorial(m) * factorial(n - m)) print num % limit if __name__ == '__main__': tests_number = ...
cafe = '' max_c = 0 choice = ' ' while choice != 'MEOW': cafe = input().split() if cafe[0] == 'MEOW': break if int(cafe[1]) > max_c: choice = cafe[0] max_c = int(cafe[1]) print(choice)
initial = abs(int(input().strip())) final = abs(int(input().strip())) half = 0 while initial >= final: half += 1 initial /= 2 print(half * 12)
def what_to_do(instructions): size = len(instructions) say = 'Simon says' say_length = len(say) index = instructions.find(say) if index == 0: answer = 'I ' + instructions[say_length + 1:size] elif index == size - say_length: answer = 'I ' + instructions[0:index] else: ...
def check_email(string): if string.find(" ") > - 1: return False at = string.find('@') if at > 0: if string[at + 2:].find('.') > - 1: return True else: return False else: return False
import re import types from collections import Iterator def compress(clean): """ Trims leading and trailing whitespace Also compresses multiple spaces within a string """ if clean is None: return None clean = re.sub(r'[\r\n\t\xa0]', ' ', clean) clean = re.sub(r'&nbsp;?', ' ', clean...
#!/usr/bin/python # -*- coding: utf-8 -*- # 7. Diferencia entre el trafico total de entrada a Brodway frente al de salida. import sys num_of_columns = 0 primera_linea = True data = sys.stdin.readlines() for line in data: fila = line.split(',') # Parsing file attributes if primera_linea: firstLine ...
# Enter one line of comments ''' Enter Multiple Lines Of Comments ''' ############################################################################### ## NICE HEADERS ## #############################################################################...
import csv Total_Votes=0 CandidateList=[] Candidate_Votes={} csvpath = 'C:\\DATA ANALYSTICS\\3-Homework-Python\\Phyton-Challenge-master\\PyPoll\\Resources\\election_data.csv' output_path = "C:\DATA ANALYSTICS\\3-Homework-Python\\Phyton-Challenge-master\\PyBank\\Resources\Election_Votes.txt" with open(csvpath, newline...
from user import User import pyperclip import random from account import Account def create_user(user_name, password): ''' creates a new user ''' new_user = User(user_name, password) return new_user def save_user(user): ''' will save new_users ''' user.save_user() def find_user...
# This is a genetic algorithm to find the best solution to # find the highest point of f(x) = x^2, 0 <= x <= 31 from random import randint # Environment variables size = 4 # Total individuals on each generation mutation_odds = 1 # Odds to mutate generations = 5 # Total generations perfection = 31 # In our ...
import errno import functools import os import shutil import stat import tempfile import six import attr @attr.s class ActionDecorator(object): """ Composable action decorators. A ActionDecorator instance is a decorator which can be applied to functions and methods. It performs its action *before* c...
# -------------- # Code starts here # Create the lists class_1 = ['Geoffrey Hinton','Andrew Ng','Sebastian Raschka','Yoshua Bengio'] class_2 = ['Hilary Mason','Carla Gentry','Corinna Cortes'] # Concatenate both the strings new_class = class_1 + class_2 print(new_class) # Append the list new_class.append('...
import os, pdb, copy import filecmp from collections import Counter from dateutil.relativedelta import * from datetime import date, datetime def getData(file): # get a list of dictionary objects from the file #Input: file name #Ouput: return a list of dictionary objects where #the keys are from the first row in the d...
''' Question 11 Level 2 Question: Write a program which accepts a sequence of comma separated 4 digit binary numbers as its input and then check whether they are divisible by 5 or not. The numbers that are divisible by 5 are to be printed in a comma separated sequence. Example: 0100,0011,1010,1001 Then the output ...
''' Question 28 Level 1 Question: Define a function that can convert a integer into a string and print it in console. Hints: Use str() to convert a number to string. Programmer Comment: Examinner Comment: '''
from random import randint word_list = ["DOG", "CAT", "PIG", "ANT", "KEY", "EYE", "LIP", "BUS", "MAP", "ELF", "COW", "BAT", "HAT", "BED", "ICE"] clue_list = ["i am a pet that has four legs,you might hear me barking", "this is a feline whose lives can reach nine", ...
# Реализовать базовый класс Worker ( работник), в котором определить атрибуты: name, # surname, position ( должность), income ( доход). Последний атрибут должен быть # защищенным и ссылаться на словарь, содержащий элементы: оклад и премия, например, # {"wage": wage, "bonus": bonus}. Создать класс Position ( должность) ...
# Пользователь вводит месяц в виде целого числа от 1 до 12. Сообщить к какому времени года # относится месяц (зима, весна, лето, осень). Напишите решения через list и через dict. # Решение через list try: while True: month = int(input('Введите номер месяца от 1 до 12(если хотите завершить програму введите ...
# Реализовать программу работы с органическими клетками, состоящими из ячеек. Необходимо # создать класс Клетка. В его конструкторе инициализировать параметр, соответствующий # количеству ячеек клетки (целое число). В классе должны быть реализованы методы # перегрузки арифметических операторов: сложение ( __add__() ), ...
# Пользователь вводит строку из нескольких слов, разделённых пробелами. Вывести каждое # слово с новой строки. Строки необходимо пронумеровать. Если в слово длинное, выводить # только первые 10 букв в слове. my_list = input('Введите слова разделенные пробелом: ').split(" ") i = 1 for item in my_list: print(f"{i} ...
# programming exercises chapter 3 # exercise 2 # A program that calculates the cost per square inch of a pizza #changes for programming exercise 5, chapter 6 import math def pizzaAr(diameter): pizza = math.pi * (diameter/2)**2 return pizza def pizzaprice(price,pizza): pricepsq = price / pizza return pri...