text
stringlengths
37
1.41M
""" network.py ~~~~~~~~~~ A module to implement the stochastic gradient descent learning algorithm for a feedforward neural network. Gradients are calculated using backpropagation. Note that I have focused on making the code simple, easily readable, and easily modifiable. It is not optimized, and omits many...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu Feb 15 09:14:05 2018 @author: huyu """ # A.List # create a list containing 4 strings. l1 = ['This','is','a','list'] # print the 3rd item of l1 print (l1[2]) #print the 1st and 2nd item in the list using [:] print (l1[0:2]) #Add a new string with text “...
# -*- coding: utf-8 -*- """ Created on Wed May 13 10:53:38 2020 @author: Liam """ class Board: def __init__(self, sideLength): self.sideLength=sideLength self.length=sideLength*sideLength self.array=[] for i in range(0,sideLength): for j in range(0, sideLength): ...
class Vehicle: owner = None def __init__(self, type, model, price): self.type = type self.model = model self.price = price def buy(self, money, owner): if money < self.price: return "Sorry, not enough money" elif Vehicle.owner: re...
biscuits = input().split(", ") command = input() while not command == "Eat": action = command.split() if action[0] == "Update-Any": for i in range(len(biscuits)): if biscuits[i] == action[1]: biscuits[i] = "Out of stock" if action[0] == "Remove": bis = ...
n = int(input()) current = 1 current_is_bigger_than_n = False for row in range(1, n + 1): for col in range(1, row + 1): print(f"{str(current)}", end = ' ') current += 1 if current > n: current_is_bigger_than_n = True break if current_is_bigger_than_n: ...
usernames = input().split(", ") isValid = True valid_usernames = [] for username in range(len(usernames)): isValid = True if 3 > len(usernames[username]) or len(usernames[username]) > 16: isValid = False for symbol in usernames[username]: if symbol.isnumeric() == False and symbol.i...
needed_money = float(input()) money_in_hand = float(input()) spending_days = 0 total_days = 0 while money_in_hand < needed_money and spending_days < 5: action = input() current_money = float(input()) total_days += 1 if action == "save": money_in_hand += current_money spending...
month = input() count_of_nights = int(input()) studio = 0 apartment = 0 #May, June, July, August, September или October if month == "May" or month == "October": studio = 50 apartment = 65 if 14 >= count_of_nights > 7: studio *= 0.95 if count_of_nights > 14: studio *= 0.70 ...
#directory = input() #n = 0 #a = 0 #for symbol in range(0, len(directory), 1): # if directory[symbol] == ".": # n = symbol # elif directory[symbol] == "\\": # a = symbol #extension = "" #for symbol in range(n + 1, len(directory), 1): # extension += directory[symbol] #file_name = "" ...
hour_of_exam = int(input()) minutes_of_exam = int(input()) hour_of_arrival = int(input()) minutes_of_arrival = int(input()) exam_in_minutes = hour_of_exam * 60 + minutes_of_exam arrival_in_minutes = hour_of_arrival * 60 + minutes_of_arrival if arrival_in_minutes > exam_in_minutes: print("Late") if exam_in_m...
import re text = input() pattern1 = r"([:]{2}|[*]{2})([A-Z]{1}[a-z]{2,})(\1)" pattern2 = r"\d" emoji_dict = re.findall(pattern1, text) cool_emojis = [] cool_threshold = 1 cool_threshold_list = re.findall(pattern2, text) for number in cool_threshold_list: cool_threshold *= int(number) for emoji i...
# Developer Drachev.N print('Добро пожаловать в квест - игру "The Witcher:Once in Brokelon"!') print('Вы готовы погрузиться в мир, где убийство и коварство это обычное явление, а доброта считается слабостью?') print('В мир, где от вашего выбора будет решаться чья-то жизнь или судьба?') ans_1 = str.lower(input('Готовы?(...
class Say: NUM_TO_WORD = { 1000000000: 'billion', 1000000: 'million', 1000: 'thousand', 90: 'ninety', 80: 'eighty', 70: 'seventy', 60: 'sixty', 50: 'fifty', 40: 'forty', 30: 'thirty', 20: 'twenty', 19: 'nineteen', ...
import unittest from phone import Phone class PhoneTest(unittest.TestCase): def test_cleans_number(self): number = Phone("(123) 456-7890").number self.assertEqual("1234567890", number) def test_cleans_number_with_dots(self): number = Phone("123.456.7890").number self.assertEq...
def word_count(phrase): # Remove whitespace and \n and toss into array words = phrase.strip().replace("\n", " ").split(" ") # Remove empty strings words = filter(None, words) # Initialize new dict for count of occurences count = {} for word in words: count[word] = 1 if word not in...
class Clock: def __init__(self, hours, mins): self.hours = hours self.mins = mins self.fixup() def __eq__(self, other): return self.hours == other.hours and self.mins == other.mins def __str__(self): return (self.format_hours() + ':' + self.format_mi...
class Board: EMPTY_BOARD = ["_" * 8 for _ in range(8)] def __init__(self, white_coords, black_coords): self.white_coords = white_coords self.black_coords = black_coords if not self.valid_coords(): raise ValueError self.board = self.generate_board() def generate...
class Minesweeper: MINE = "*" SPACE = " " CORNER = "+" VERTICAL_EDGE = "|" HORIZONTAL_EDGE = "-" @classmethod def board(cls, inp): if not cls.valid(inp): raise ValueError return cls.solve(inp) # Split rows (String -> List) and operate on board in place ...
def on_square(x): return 2 ** (x - 1) def total_after(x): return 1 if x == 1 else on_square(x) + total_after(x - 1)
def append(list_a, list_b): appended = [] for element in list_a: appended.append(element) # Not sure if using .append here is cheating for element in list_b: appended.append(element) return appended def concat(lists): concatenated = [] for l in lists: concatenated = ap...
''' matches(ticket, winners) reports how well a lottery ticket did test_matches(matches) reports whether a matches() function works as assigned. ''' def matches(ticket, winner): ''' returns the number of numbers that are in both ticket and winner ticket and winner are each a list of five unique in...
inLines = [] while True: userInput = str(input()) if (userInput): inLines.append(userInput.upper()) else: break for sentence in inLines: print (sentence)
def squareOddNumber(userInputList): userInputList = list(set(userInputList)) userInputList.sort() answerList = [] for i in range(0,len(userInputList)): if(userInputList[i]%2!=0): answerList.append(str(userInputList[i]**2)) else: pass return answerList...
# coding: utf-8 # In[25]: import tkinter import tkinter.messagebox # In[27]: def msgbox(): tkinter.messagebox.showinfo(title="xuehao",message=xuehao.get()) root = tkinter.Tk() button = tkinter.Button(root,text='点击弹出',command=msgbox) button.place(x=60,y=120,height=30,width=80) xuehao = tkinter.StringVar(...
#!/usr/bin/python import unittest, json, httplib, urllib, httplib, base64 class QueryHandler: """ This class is the abstract query handler for raw HTTP queries. """ endpoint = '' apiversion = '' apikey = '' username = '' password = '' def __init__(self, endpoint, apiversion, apikey...
#http://www.codewars.com/kata/54da539698b8a2ad76000228/train/python def isValidWalk(walk): v, g = 0, 0 if len(walk) == 10: for d in walk: if d == 'n': g += 1 elif d == 's': g -= 1 elif d == 'w': v += 1 else: ...
from node import Node def reverse_to(list, to, include): cursor = list new_list = None condition = True while condition: if cursor is to: condition = False if not include: break else: cursor = Node(cursor.value) next_i...
from unittest import TestCase from towers_of_hanoi import moveDisks def add_n_items_to_tower(n, tower): for i in range(n, 0, -1): tower.append(i) class TestTowersOfHanoi(TestCase): def test_1_item(self): tower1, tower2, tower3 = [], [], [] add_n_items_to_tower(1, tower1) moveD...
#!/usr/bin/python # Cheat maatrix columns and lines if some element is 0 def cheat_matrix(matrix): rows = [False] * len(matrix) columns = [False] * len(matrix[0]) for i in range(len(matrix)): for j in range(len(matrix[0])): if matrix[i][j] == 0: rows[i] = True ...
def sort(stack): buffer = [] if len(stack) == 0: return while len(stack) > 0: buffer.append(stack.pop()) while len(buffer) > 0: item = buffer.pop() moved_items = 0 while len(stack) and stack[-1] < item: buffer.append(stack.pop()) moved...
class Node: def __init__(self, value): self.value = value self.next = None def add_node(self, value): current_node = self while current_node.next != None: current_node = current_node.next current_node.next = Node(value) return current_node
##assigning elements to different lists l_name = input("Enter different list name").split() print(l_name) for i in range(len(l_name)): l_name[i] = input("Enter elements for each list").split() for i in l_name: print(i) ##Accessing element from tuple tup1 = tuple(l_name[0]) print(tup1) n = int(input("Enter ind...
# -*- coding: utf-8 -*- import math def num(val): new = [] for x in val: new.append(math.sqrt(x)) return new if __name__ == '__main__': val = [2, 4, 9, 16, 25] print(num(val)) print(list(map(math.sqrt, val))) print([math.sqrt(a) for a in val]) print([pow(a, .5) for a in val]) ...
# -*-coding: utf-8 -*- def copyDict(old_dict): new_dict = {} for key in old_dict.keys(): new_dict[key] = old_dict[key] return new_dict def addDict(d1, d2): new_dict = {} for key in d1.keys(): new_dict[key] = d1[key] for key in d2.keys(): new_dict[key] = d2[key] re...
import os import platform import sys def text_to_speech(tosay): if platform.system().lower() == "linux": os.system("echo " + tosay + "| espeak -s 100") elif platform.system().lower() == "darwin": os.system("echo " + tosay + "| say") else: print("Don't know how to speech synthasize o...
import string lower=string.ascii_lowercase def encode(plain_text): text = plain_text.lower() cipher = "".join([lower[-(lower.find(c)+1)] if c in lower else c if c.isnumeric() else "" for c in text]) cipher = " ".join([(cipher[i:i+5]) for i in range(0, len(cipher), 5)]) return cipher def decode(cipher...
class School: students={} def __init__(self): self.students={} def add_student(self, name, grade): if grade not in self.students.keys(): self.students[grade]=[] self.students[grade].append(name) def roster(self): list=[] for key in sorted(self.studen...
# randArray = [323,748,2346,9,45.04,425.3,2346,2790] # randArray.sort(reverse=True) # print(randArray) # smallArray = randArray[:3] # print(smallArray) # # if 2346 in smallArray: # print(2346 in smallArray) # smallArray.remove(2346) # else: # print(False) # print(smallArray) # if 2346 in smallArray: # p...
'''Collection of functions to output the extracted parameters into the format specified by the user''' import pandas as pd from code_files import strings def output(parameters, evaluations, solutions, filepath): headers = ["Parameter Name", "Parameter Value", "Parameter Evaluation", "Parameter Solution"] allV...
#!/usr/bin/python3 """ Contain the fucntion that find if this are the same class """ def is_same_class(obj, a_class): """ We received the object and the class to comparate """ return type(obj) == a_class
#!/bin/usr/python3 """ Class for proves the things Rectangle""" import unittest from models.base import Base from models.rectangle import Rectangle class TestBaseClass(unittest.TestCase): """ The class does the test of the Rectangle Args: unittest.TestCase: Inherits the methods for proves the te...
#!/usr/bin/python3 """ The module receive two arguments and say the name complete concatenate """ def say_my_name(first_name, last_name=""): """ Function receives the argument and return name_Complete = first_name + last_name """ if type(first_name) is not str: """ Verify if is string """ ...
#!/usr/bin/python3 """ All class to JSON """ class Student: """ Contain the definition about student """ def __init__(self, first_name, last_name, age): """ Constructor of the Student Initializes values first_nmae, last_name and age""" self.first_name = first_name ...
#!/usr/bin/python3 """ Square class """ from models.rectangle import Rectangle class Square(Rectangle): """ Square class that inherits of the Rectangle class that in turn inherits of the Base class Args: Rectangle (Class): Class that inherits the attributes and methods """ def...
def bin_search(x, L): low = 0 high = len(L) while low != high: mid = (low+high)//2 if x > L[mid]: low = mid + 1 else: high = mid return low
from tkinter import * s = "Result:\n" x = ([14, 16], ("apple", "banana"), [3.2, 5.6], {0: True, 1: False}) for r in range(len(x)): s += str(type(x[r])) + "\n" for c in range(len(x[r])): s += "x[" + str(r) + "][" + str(c) + "] = " + str(x[r][c]) + "\n" s += "\n" y = [{0: "dog", 1: "cat"...
from movie import Movie class User: def __init__(self, name): self.name = name self.movies = [] def __repr__(self): return "<user {}>".format(self.name) def add_movie(self): name=input("Enter the name of movie: ") genre = input("Enter the genre of movie: ...
import re f = open('c:/riker.txt', 'r'); text =f.read() sentenceEnders = re.compile(r""" # Split sentences on whitespace between them. (?: # Group for two positive lookbehinds. (?<=[.!?]) # Either an end of sentence punct, | (?<=[.!?]['"]) # or end of s...
characters = ['t','a','c','o'] output = '' length = len(characters) i = 0 while (i < length): output = output + characters[i] i = i + 1 length = length * -1 i = -2 while (i >= length): output = output + characters[i] i = i - 1 print(output)
name = input("What is your dog's name? ") age = input("What is your dog's age? ") dog_age = int(age) * 7 print("Your dog " + name + " is", dog_age, "years old in human years")
n = int(input("Enter the value:")) sum = 0 while (n != 0): print(n) sum += n n -= 1 print("The sum is: ", sum)
#coding: utf8 lletra=raw_input("introdueix una lletra: ") if lletra in ("a","e","i","o","u","A","E","I","O","U"): print ("És una vocal") else: print ("És una consonant")
#/usr/bin/env python #-*- coding:utf-8 -*- x=2 y=3 print id(x) print id(y) x=y print id(x) print id(y) name = raw_input('请输入你的名字:') age = int(raw_input("age:")) job = raw_input('job:') salary = raw_input('salary:') print ''' Personal information of %s: Name: %s Age: %d Job: %s Salary: %s ---------...
"""Methods for counting the number of syllables in a string.""" import re from collections import defaultdict from typing import Dict, Iterable, Set # TODO: document this. _OVERRIDES = { '1ST': 1, '2ND': 2, '3': 1, '3RD': 1, '8': 1, 'AB': 2, 'ALEMBIC': 3, 'CABLEWAY': 3, 'CARTWHEELIN...
import requests import json def Main(): def get_route_from_int(userRoute): # Getting the json formatURL = requests.get(routesURL) json_data = json.loads(formatURL.content) # Iterating through the data until a match is found for data in json_data: route = data["...
class Node: def __init__(self,data): self.data=data self.next=None class LinkedList(): def __init__(self): self.head = None def getIntersectionNode( headA, headB): curA, curB = headA, headB lenA, lenB = 0, 0 while curA is not None: lenA += 1 ...
from Inheritance.mix_it_06.technology.technology import Technology class Laptop(Technology): def __init__(self, memory: float, memory_taken: float): super().__init__(memory, memory_taken) def install_software(self, software, software_memory): try: self.get_capacity(self.memory, se...
from abc import abstractmethod from Polymorphism.wild_farm.animals.animal import Animal, Bird from Polymorphism.wild_farm.food import Meat class Owl(Bird): def __init__(self, name, weight, wing_size): super().__init__(name, weight, wing_size) def make_sound(self): return "Hoot Hoot" def ...
from abc import abstractmethod from Polymorphism.wild_farm.animals.animal import Animal, Mammal from Polymorphism.wild_farm.animals.birds import Owl, Hen from Polymorphism.wild_farm.food import Meat, Food, Vegetable, Fruit class Mouse(Mammal): def __init__(self, name, weight, living_region): super().__ini...
from txt_reader import import_and_create_dictionary, import_and_create_accounts from user_actions import signup, login, change_password, update, transfer, delete_account def main(): bank = import_and_create_dictionary("bank.txt") user_accounts, log_in = import_and_create_accounts("user.txt") # returns dictio...
# if int(input("값을 입력하세요:")) % 2 < 1: # print("짝수입니다") # else: # print("홀수입니다") # #파이썬 삼항 연산자 # print("짝수입니다.") if int(input("값을 입력하세요:")) % 2 ==0 else print("홀수입니다.") # cnt = 10 # print("count down!") # while cnt > 0: # print(cnt) # cnt -= 1 # #break # else: # print("끝!") # for char in "Pyt...
# 리스트 정렬 num_list = [2, 11, 3, 5, 7] # num_list.sort() # num_list.sort(reverse=True) # num_list.reverse() num_list2 = sorted(num_list) # num_list.extend(num_list2) print(num_list) print(num_list2) # 리스트 연산 print(num_list + num_list2) print(num_list * 3)
#!/usr/bin/python import sys cache = {} def climbing_stairs(n, cache = cache): if n in cache: return cache[n] elif n == 0: return 1 elif n == 1: result = climbing_stairs(n - 1) cache[n] = result return result elif n == 2: result = climbing_stairs(n - 1) + climbing_stairs(n - ...
#Create a program that asks the user for a number and then #prints out a list of all the divisors of that number. #If you don’t know what a divisor is, it is a number that divides evenly #into another number. For example, 13 is a divisor of 26 because 26 / 13 has #no remainder.) numb = int(input("Give me a number: "))...
#!/usr/bin/env python3 colors = ["red","blue","green","yellow","brown","black"] months = ( "Jan","Feb","Mar","Apr","May","Jun", "Jul","Aug","Sep","Oct","Nov","Dec", ) for c in enumerate(colors): print("{0} {1}".format(*c)) print() for num,month in enumerate( months, 1 ): print("{...
#!/usr/bin/env python3 while True: c = input('Enter Celsius temp: ') if c.lower() == 'q': break c = float(c) f = ((9 * c) / 5 ) + 32 print('{0:.1f} C is {1:.1f} F\n'.format(c,f))
#!/usr/bin/env python3 import re fs = "apple banana artichoke cherry date enchilada appetizer" r = re.compile(r"\b(a[a-z]+)(\s*)") # match words that start with 'a' def replace_it(m): # group 1 is the 'a' word, group 2 is space after it return "'" + m.group(1) + "'" + m.group(2) print(r.sub(repla...
#!/usr/bin/env python3 northam = [ "US","El Salvador","Mexico","Canada" ] europe = [ "Germany","France","Bulgaria","Estonia","Wales"] africa = [ "Benin","Kenya","Egypt","Morocco"] earth = [ northam,europe,africa ] venus = [] mars = [] print("earth[1]",earth[1]) print("earth[1][2]",earth[1][2]) solarsys...
#!/usr/bin/env python3 airports = { 'IAD':"Dulles",'RDU':"Raleigh-Durham", "DCA":"Reagan", "BWI":"Baltimore/Washington", "EWR":"Newark","ABQ":"Albuquerque", "GDB":"Granite Falls" } print("*** raw") for abbr in airports: print("{0:3s} {1:<20s}".format(abbr,airports[abbr])) print() print("*** sorted (u...
#PYNPUT #This library allows you to control and monitor input devices. import pynput from pynput.keyboard import Key, Listener count = 0 key_list = [] #Saving inputs in Input.txt file def write_file(key_list): with open("Input.txt", "a") as f: for key in key_list: sp = str(key).r...
''' gas = 45 # in litres while gas>0: print("vroom") gas = gas - 1 if gas ==10: #on a reserve tank . cannot use your reserve print("Fill up!") #break continue ages = [18, 21, 16, 12] for age in ages: if age >=18: print("come on in") ...
def selection_sort(items): for step in range(len(items)): print(step) for location items range(step,len(items)): print(location) if items[location]<items[step]: items[location]=items[step] items[step]=item[location] print(items) x=[3,2,1,7,6,9] selection_sort(x) print(x)...
from tkinter import * from tkinter import messagebox ourframe = Tk() ourframe.geometry("500x500") ourframe.title("Error Handling") def verify(): user_password1 = {"zena": "123", "chel": "234", "marc": "666", "eth": "555", "bavu": "777", "vik": "456"} username = myentry1.get() password = myentry2.get() ...
from tkinter import * from tkinter import messagebox ourframe2 = Tk() def status(): ourframe2 = Tk() ourframe2.geometry("300x500") ourframe2.title("Error handling") label3= Label(ourframe2, text="Please enter amount in your account") label3.pack() entry3 = Entry(ourframe2) entry3.pack() def check_message...
import math import random import numpy import time points = [] def generate_point(): """ Generates a point in the first quadrant """ x = random.uniform(0, 1) y = random.uniform(0, 1) point = (x,y) points.append(point) return point def calculate_length(point): """ Calculates t...
# Code likho jisse 12 se 421 tak saare numbers ka "total" calculate kare. # i=1 # total=0 # while i<421: # number=int(input("enter the number")) # total=sum+i # print(sum) # i=i+1 # num=0 # sum=0 # while num<10: # number=int(input("enter the number")) # sum=sum+number # print(sum) # n...
# Get to know list # A list is an ORDERED structure of a bunch of other objects. Let's take a look. FRUIT = ["apple", "banana", "orange"] # Now, the variable FRUIT represents a `list` of three different kinds of fruits. Let's check the first one. When you want to index a list to get the `nth` object, use `[index]` t...
# Additional operators # plus.... variableA = 10 + 20 # minus... variableB = 30 - 15 # multiply... variableC = 20 * 3 # divide... variableD = 24/6 # change order of operation, do addition first. variableE = 3*(4+2) # compare two values and let's see what are the results print(3 > 5) # this is clearly wrong. va...
#! /usr/bin/env python import binascii #imports for database access """ import sqlite3 import os """ """ This code is to checks the username and password author: Timothy Moore Version: 02/07/2019 """ def compare(username, password): f = open('users', "r")#find the user information u = f.readline().rstrip() p = f...
def distance(strand_a, strand_b): if len(strand_b) != len(strand_a): raise ValueError("length doesn't match") distance = 0 for i in range(len(strand_a)): if strand_a[i] != strand_b[i]: distance += 1 return distance
# def reverse(text): # return text[::-1] # def reverse(text): # reversed_string = [] # for i in range(len(text) -1, -1, -1): # reversed_string += text[i] # return ''.join(reversed_string) def reverse(text): return ''.join([i for i in reversed(text)])
def prime(nth): if nth < 1: raise ValueError("not prime") primes = [2] number = 3 while len(primes) != nth: if is_prime(number): primes.append(number) number += 2 return primes[-1] def is_prime(number): for i in range(2, number): if number % i == 0: ...
i = 0 listaNumeros = [] while i == 0: num = int(input("Digite um numero: ")) listaNumeros.append(num) i = int(input("Para continuar digite 0, para sair qualquer outro valor: ")) print(listaNumeros) def medida(lista): total = 0 for i in lista: total += i total /= int(len(lista)) re...
array = input() count = int(array[0]) for i in range(1, len(array)): num = int(array[i]) if num <= 1 or count <= 1: count += num else: count = count * num print(count)
def solution(nums): answer = 0 leng = len(set(nums)) if len(nums) // 2 > leng: return leng else: return len(nums) // 2
graph = [[0]*5]*5 graph[0][0] = 1 print(graph) graph2 = [[0 for _ in range(5)] for _ in range(5)] # for i in range(5): # for j in range(5): # graph2[i].append(0) print(graph2)
food_times = [3,1,2] for i in range(len(food_times)): food_times[i] = food_times[i] - 1 print(food_times)
T = int(input()) for i in range(T): stack = [] a=input() for j in a: if j == '(': stack.append(j) elif j == ')': if stack: stack.pop() else: # 스택에 괄호가 없을경우 NO print("NO") break else: # break문으로 끊기지 않고 수행...
temperature = eval(input("Enter the temperature in Fahrenheit between -58 and 41: ")) windSpeed = eval(input("Enter the wind speed in miles per hour: ")) t = 35.74 + 0.6215 * temperature - 35.75 * windSpeed ** 0.16 + 0.4275 * temperature * windSpeed ** 0.16 if windSpeed >= 2 and -58 < temperature < 41: print("The ...
number = int(input("Enter an integer, the input ends if it is 0: ")) total = 0 countPos = 0 countNeg = 0 count = 0 if number == 0: print("You didn't enter any number") else: while number != 0: if number > 0: countPos += 1 else: countNeg += 1 count += 1 t...
print("Enter a, b, c:") a = eval(input()) b = eval(input()) c = eval(input()) discriminant = b ** 2 - 4 * a * c if(discriminant > 0): r1 = (- b + (b ** 2 - 4 * a * c) ** 0.5) / 2 * a r2 = (- b - (b ** 2 - 4 * a * c) ** 0.5) / 2 * a print("The roots are", r1, "and", r2) elif(discriminant == 0): r = - b ...
import random import time correctCount = 0 count = 0 NUMBER_OF_QUESTIONS = 10 startTime = time.time() while count < NUMBER_OF_QUESTIONS: number1 = random.randint(1, 15) number2 = random.randint(1, 15) answer = eval(input("What is "+ str(number1) + " + " + str(number2) + "? ")) if number1 + number2 =...
print("Enter weight and price for package 1: ") weight1 = eval(input()) price1 = eval(input()) print("Enter weight and price for package 2: ") weight2 = eval(input()) price2 = eval(input()) if weight1 / price1 < weight2 / price2: print("Package 1 has the better price") else: print("Package 2 has the better pr...
number = int(input("Enter an integer: ")) print("10 divisible by 5 and 6?", number % 5 == 0 and number % 6 == 0) print("10 divisible by 5 or 6?", number % 5 == 0 or number % 6 == 0) print("10 divisible by 5 or 6, but not both?", (number % 5 == 0 or number % 6 == 0) and not(number % 5 == 0 and number % 6 == 0))
# Fibonacci numbers module # Print the Fibonnaci series up to n def fib(n): ''' Write Fibonnacci series up to n and print the result''' a, b = 0, 1 while a < n: print(a, end= ' ') a, b = b, a+b print() # Fibonacci numbers module # Return the Fibbonaci series up to n as result def fib2(n...
# Substracts module # Return the subtracted value of both arguments def substract2Number(x: int, y: int): ''' Substract value of 2 number''' return x - y
# Substracts module # Returns the sum of the values ​​of the two arguments def sum2Number(x: int, y: int): ''' Sum value of 2 number ''' return x + y
class Person: def __init__(self, fname, lname): self.firstName = fname self.lastName = lname print("First Name: {}, Last Name: {}".format(self.firstName, self.lastName)) class Student: def __init__(self, year): self.graduationYear = year print("Graduation Year: {}".forma...
def func1(*arg): minimal = min(arg) maximal = max(arg) return minimal, maximal print(func1(1, 2, 3, 4, 5)) def func2(string = str(), case = True): if case: return string.upper() else: return string.casefold() print(func2('downcase', True)) print(func2('UPPERCASE', False)) def func3...