text
stringlengths
37
1.41M
''' Key Charecteristics: 1) A straddle is an options strategy involving the purchase of both a put and call option for the same expiration date and strike price on the same underlying. 2) The strategy is profitable only when the stock either rises or falls from the strike price by more than the total premium paid. 3) ...
def bubble_sort(array): ''' array -> int array Sorting by doing adjacent comparisons repeatedly through the array, until everything is sorted ''' to_be_sorted = len(array) - 1 while to_be_sorted > 0: for i in range(to_be_sorted): if array[i] > array [i+1]: ...
import random if __name__ == "__main__": print("Enter N to exit dice simulation otherwise Enter Y") while input() != 'N': b = random.randrange(1, 7) print(b) print("Do you want to continue?")
#!usr/env/bin python class ShoppingCart(object): items_inCart={} #global dictionary def __init__(self,customer_name): self.customer_name =customer_name #add items in cart def add_items(self,product,price): if product in self.items_inCart: print "Item already in Cart." else: self.items...
fname = input("Enter file name: ") fh = open(fname) fr = fh.read() print(fr.upper().rstrip())
""" program for file operations """ def test_read(): fd = open('sample_file.txt') print(type(fd)) contents = fd.read() print(contents) print(type(contents)) fd.close() def test_readn(bytes=20): fd = open('sample_file.txt') print(type(fd)) contents = fd.read(bytes) ...
## operator overloading ## 5 + 6 # x =10 # print(type(x)) # print(dir(x)) # # ## top level func '+' __add__ # print(5+'aa') class Box: def __init__(self,length,breadth): self.length = length self.breadth = breadth def __add__(self, other): new_length = 0 new_b...
## sets are data structure . Unordered collection of items ## Sets are mutable ## THey are heterogenous. string,int,float,bool ## they cannot contain another list or dict ## they do not contain duplicates. ## create empty sets. numbers = set() print(type(numbers)) print(len(numbers)) numbers = {1,...
#!/bin/python3 import math import os import random import re import sys # Complete the stepPerms function below. def stepPerms(n): if n <= 3: return 2 ** (n-1) s1 = 1 s2 = 2 s3 = 4 for i in range(4, n+1): s1, s2, s3 = s2, s3, s1+s2+s3 % (10**10 + 7) return s3 if __name__ == '_...
# minim valeur d un tableau def minim(T): min=T[0] for i in T : if i<min: min=i print("le valeur minimal est",min) T = [3, 5, 8, 13, 19, 2, 6] minim(T) # max valeur d un tableau def maxim(T): max =T[0] for i in T: if i>max: max=i print("le max est",max) T = [3, ...
text= input() total=0 for letter in text: if letter=="a": total+=1 elif letter=="e": total+=2 elif letter=="i": total+=3 elif letter=="o": total+=4 elif letter=="u": total+=5 print(total)
city = input() sales = float(input()) comission = 0 if city == "Sofia": if sales >= 0 and sales <= 500: comission = (5 / 100) * sales print('{0:.2f}'.format(comission)) elif sales > 500 and sales <= 1000: comission = (7 / 100) * sales print('{0:.2f}'.format(comission)) elif...
command = input() success = False total_steps = 0 while command != "Going home": steps_made = int(command) total_steps += steps_made if total_steps >= 10000: difference = total_steps - 10000 success = True break command = input() if success: print("Goal reached! Good job!"...
import sys n=int(input()) OddSum=0 OddMin=sys.maxsize OddMax=-sys.maxsize EvenSum=0 EvenMin=sys.maxsize EvenMax=-sys.maxsize for i in range(1,n+1): number=float(input()) if i%2==0: EvenSum+=number if number<EvenMin: EvenMin=number if number>EvenMax: EvenMax=nu...
cake_width = int(input()) cake_height = int(input()) cake_volume = cake_width * cake_height total_pieces = 0 failed = True command = input() while command != "STOP": pieces = int(command) total_pieces += pieces if total_pieces > cake_volume: print(f"No more cake left! You need {total_pieces - ca...
# Escreva uma função que receba uma lista de nomes e retorne uma lista com a string "Sr. " adicionada ao início de cada nome. def adiciona_sr(lista): return list(map(lambda string: 'Sr. ' + string, lista)) # Escreva uma função que, dada uma lista de números, calcule 3n*2 + 2/n + 1 para cada número n da lista. def op...
resultaat1 = int(input("Resultaat eerste test op 20: ")) resultaat2 = int(input("Resultaat tweede test op 20: ")) resultaat3 = int(input("Resultaat derde test op 20: ")) totale_resultaat = (resultaat1 + resultaat2 + resultaat3) / 3 * 100 if totale_resultaat < 60: uitslag = "onvoldoende" elif totale_resultaat < 70...
naam = input("Naam: ") voornaam = input("Voornaam: ") nieuwe_naam = voornaam[0].upper() + ". " + naam[0].upper() + naam[1:] print(nieuwe_naam)
positieve_getallen = [] negatieve_getallen = [] kleinste_getal = 0 for i in range(0, 10): getal = int(input("Getal")) if getal >= 0: positieve_getallen.append(getal) else: negatieve_getallen.append(getal) for i in range(0, len(negatieve_getallen)): if negatieve_getallen[i] < kleinste_...
aantal_afgelegde_km = float(input("Aantal afgelegde km per jaar")) verbruik = float(input("Verbruik")) prijsBrandstof = float(input("Prijs brandstof")) totale_prijs = ((aantal_afgelegde_km / 100) * verbruik) * prijsBrandstof kostprijs_per_km = totale_prijs / aantal_afgelegde_km print("De totale prijs is: ", totale_pr...
geheel_getal = int(input("Geef een geheel getal in.")) for i in range(1, 21): print(i, "x", geheel_getal, "=", i * geheel_getal) # format .format print({':2'} 'x' {':2'} = {:4}.format(i, "x", geheel_getal, "=", i * geheel_getal)) )
# burgerlijke_staat = int(input("Geef de burgerlijke staat (1. ongehuwd 2. gehuwd 3. weduwe): ")) # # if burgerlijke_staat == 1: # lidgeld = 25 # elif burgerlijke_staat == 2: # lidgeld = 20 # else: # lidgeld = 15 # # print("Het jaarlijks lidgeld bedraagt", lidgeld, "euro") # burgerlijke_staat = int(input(...
"""" use adjacency list to represent the graph e.g. (a)-(c) (b)-(c)-(e) (c)-(b)-(e) (d)-(c) (e)-(c) (f) above: first element in array is vertex then defines the edges from the vertex of value first element """ from _collections import defaultdict import matplotlib.pyplot as plt import networkx as nx class Undirecte...
#If we list all the natural numbers below 10 that are multiples of 3 or 5, #we get 3, 5, 6 and 9. #The sum of these multiples is 23. #Find the sum of all the multiples of 3 or 5 below 1000. start = 999 total = 0 while start != 0: if (start % 5 == 0) or (start % 3 == 0): total = total + start start = ...
# Computing a cartesian product itertools.product # Auteur : Sébastien Combéfis # Version : October 11, 2020 from itertools import product import timeit REPEATS = 100 def pairs_1(a, b): return [(i, j) for i in a for j in b] def pairs_2(a, b): return list(product(a, b)) def measure_time(name, params): t...
# Counting the frequency of letters in a word # Author: Sébastien Combéfis # Version: August 9, 2020 import collections import timeit REPEATS = 100 def frequencies_1(word): freq = {} for c in word: if c not in freq: freq[c] = 0 freq[c] += 1 return freq def frequencies_2(word)...
# Capitalising the first letter of every word in a sentence # Author: Sébastien Combéfis # Version: August 9, 2020 import timeit REPEATS = 100 def wordcapital_1(s): result = [] for w in s.split(' '): result.append(w.capitalize()) return ' '.join(result) def wordcapital_2(s): result = [] ...
# Sum the values in a list with the sum predefined function # Auteur : Sébastien Combéfis # Version : October 10, 2020 import timeit REPEATS = 100 def sumint_1(data): result = 0 for d in data: result += d return result def sumint_2(data): return sum(data) def measure_time(name, params): ...
from queue import PriorityQueue as pq class PriorityQueue: def __init__(self, mode): self.queue = pq() self.mode = mode def put(self, h_cost, g_cost, data): if self.mode == 0: self.queue.put((h_cost + g_cost, g_cost, data)) elif self.mode == 1: ...
#A prisoner is trapped in a cell containing five doors. #The first door leads to a tunnel which returns to his cell after three days of travel. #The second leads to a tunnel which returns him to his cell after a single day of travel. #The third door leads him immediately to freedom. #The fourth door leads to a tunne...
from turtle import * from random import randrange def matrix_to_graph(list1, length): g = dict() for i in range(length): g[i] = [] for index in range(length): for i in range(length): if list1[index][i] == 1 and index != i: g[index].append(i) return g position = {} def draw(g): penup() visted = [] g...
import sqlite3 from sqlite3 import Error def create_connection(db_file): conn = None try: conn = sqlite3.connect(db_file) except Error as e: print(e) return conn def create_planos(conn, plano): sql = ''' INSERT INTO planos(descricao,minutos) VALUES(?,?) ''' cur ...
t = (5,'program', 1+3j) # t[1] = 'program' print("t[1] = ", t[1]) # t[0:3] = (5, 'program', (1+3j)) print("t[0:3] = ", t[0:3]) # Generates error # Tuples are immutable # Tuples are used to write-protect data and are usually faster than list as it cannot change dynamically. t[0] = 10
#!/usr/bin/python import psycopg2 import sys from config import config #First, read database connection parameters from the database.ini file. #Next, create a new database connection by calling the connect() function. #Then, create a new cursor and execute an SQL statement to get the PostgreSQL database version. #Afte...
import pandas as pd titanic = pd.read_csv('http://biostat.mc.vanderbilt.edu/wiki/pub/Main/DataSets/titanic.txt') #分离数据特征与预测目标 y = titanic['survived'] X = titanic.drop(['row.names','name','survived'],axis = 1) #对缺失数据进行填充 X['age'].fillna(X['age'].mean(),inplace = True) X.fillna('UNKNOWN',inplace = True) from sklearn.cr...
import random as r x_range = [0,10] y_range = [0,10] class Turtle: def __init__(self): #初始化体力 self.power = 100 #初始化乌龟位置 self.x = r.randint(x_range[0],x_range[1]) self.y = r.randint(y_range[0],y_range[1]) def move(self): turtle_x = self.x + r.choice([-2,-1,1,2])...
count = 3 password = '2333' while count: passwd=input('请输入四位数字密码:') if passwd == password: print('密码通过') break elif '*' in passwd: print('密码中含*号,你还有%d次机会' % count) continue else: print('密码错误,你还有%d次机会' % count) count -=1
# Author: Md Shoaib # Date: 28/02/2021 # WAP to to find remainder when a number is divided by 2 remainder = input("Enter a number which you want to remainder: ") remainder = int(remainder) result = remainder%2 result = int(result) print("Remainder of your number is: ", result)
""" lec 4 dict and tuple """ my_tuple = 'a', 'b', 'c', 'd', 'e' print(my_tuple) my_2nd_tuple = ('a','b','c','d','e') print(my_2nd_tuple) not_a_tuple = ('a') print(type(not_a_tuple)) is_a_tuple = ('a',) print(type(is_a_tuple)) print(my_tuple[1:3]) my_car = { 'color':'red', 'maker':'toyota', 'year'...
import random Num1 = round(random.random() * 10) Num2 = round(random.random() * 10) rand_num = int(Num1 * Num2) num = int(input("Guess a number between 0 and 100")) tries = 1 if(num == rand_num): print("Congradulations! you win!") while((num != rand_num) and (tries < 3)): if (num < rand_num): ...
''' Simulate a M/M/1 queueing model ''' import random as r import sys import math as m import statistics as stat # Generate Exponential Random Variable def exporv (rate): return (-1/rate)*(m.log(r.random())) # Check argument and print hint message def checkArg () : if len(sys.argv) != 4 : print ("\n\tUsage : ...
''' Estudo do loop FOR e Dicionario ''' sl_faculdade = {'sala1': 'ADS A', 'sala2': 'SI A'} print('Dicionario das Salas:', sl_faculdade) for chave in sl_faculdade: # membership print(sl_faculdade[chave]) # imprime os valores das chaves # print(len(sl_faculdade)) lista = ['vitor', 'gabi', 'ale'] new_dict = {} ...
''' ════════════════════════════════════════════════════════════════════════════════ Instituição : Faculdade Impacta Tecnologia Curso : Análise e Desenvolvimento de Sistemas | Banco de Dados Disciplina : Linguagem de Programação 1 Autor : Professor Lucio Nunes de Lira ══════════════════════...
from typing import Union, List, Dict Number = Union[int, float] __alunos__ = ["vitor.teixeira@aluno.faculdadeimpacta.com.br", "gabriel.neves@aluno.faculdadeimpacta.com.br"] class Cliente(): """ Classe Cliente do Banco """ def __init__(self, nome: str, telefone: int, email: str): ...
def conta_passo (n): cont = 0 while n != 1: if (n % 2 == 0 ): cont += 1 n = n//2 else: cont +=1 n = 3*n+1 return cont
import streamlit as st import pandas import pandas as pd import numpy st.title('UI Parts Sample') st.subheader('Slider') x = st.slider('x') st.write(x, 'squared is', x * x) st.subheader('Slider With Default Value') hour_to_filter = st.slider('hour', 0, 23, 17) # min: 0h, max: 23h, default: 17h st.subheader('Checkbo...
import re def print_intro(): """Show intro and instructions to user.""" print('Let\'s play madlibs. I\'ll ask you to provide some words based on a prompt. When you\'ve given all your answers, I\'ll tell you a story.') def get_template_text(template_filename): """Get the template text from file and retur...
# Handling missing data import numpy as np import pandas as pd if __name__ == "__main__": # Create Dataframe print("-- Original Frame --") df = pd.DataFrame({"A":[1,2,np.nan], "B":[5,np.nan,np.nan], "C":[1,2,3]}) print(df) # Drop missing values print("-- Drop rows with missing values --") ...
# Using recommender systems to recommend films import pandas as pd import numpy as np import matplotlib.pyplot as plt import seaborn as sns if __name__ == "__main__": # Data df = pd.read_csv("Recommender Systems/u.data", sep="\t", names=["user_id", "item_id", "rating", "timestamp"]) titles = pd.read_csv("R...
# Linear Regression with SKLearn import pandas as pd import numpy as np import matplotlib.pyplot as plt import seaborn as sns from sklearn.model_selection import train_test_split from sklearn.linear_model import LinearRegression from sklearn import metrics if __name__ == "__main__": # Data df = pd.read_csv("Sk...
''' NAVHW_038: Draw a flowchart to input a number and check whether the entered number is a perfect number or not. (A perfect number - the sum of the factors less than n is equal to the number Example- 6 - 1+2+3 = 6) Sample Input: 6 Sample Output: Perfect number Sample Input: 5 Sample Output: Not a perfect nu...
''' NAVHW_006:: Write a program to take a number as input from the user and print “Bingo” - If the number is even and >200 “Ringo” - If the number is odd and <200 “CodeChef” - for any other number ''' n=int(input("number")) if n%2==0: if n>200: print("Bingo") else: print("CodeChef") else: if n<200: print("R...
''' NAVHW_014:: Write a program to input three angles of a triangle and check if that triangle is possible to form? [hint: Sum of all the angles must be equal to 180 degrees] ''' a=int(input("first angle")) b=int(input("second angle")) c=int(input("third angle")) if a!=0 and b!=0 and c!=0 and a+b+c==180: if a+b+c==18...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Fri Apr 27 15:11:51 2018 @author: qk """ #konkat.py def konkat(*strs): """ it will return the argument, that not string """ result = [] for st in strs: if not isinstance(st, str): result.append(st) return result...
'''Player class represents a player for the game and contains the hand that the user has and the score also has special type dealer''' class Player(): # score = 0 #the players hand score # hand = [] #contains the hand of the player # name = '' #The player's name # isDealer = False #setup player declar...
import pandas as pd ### ### Load Data Set ### path='clean_data.csv' df=pd.read_csv( 'clean_data.csv') data = df # Drop rows with missing column data ### ### Convert Data Into List Of Dict Records ### data = data.to_dict(orient='records') ### ### Seperate Target and Outcome Features ### from sklearn.feature_extr...
# Randomly fills a grid of size 10 x 10 with 0s and 1s # and computes the number of paths that go from from a point (x1, y1) # to a point (x2, y2) -- a path consisting of horizontally or # vertically adjacent 1s --, visiting every point on the path once only. # # Written by Ivan Teong and Eric Martin for COMP9021 imp...
# Draws a dodecadon with the colour of each sector alternating red and blue. # # Written by Eric Martin for COMP9021 from turtle import * edge_length = 100 angle = 30 def draw_triangle(i, colour): color(colour) begin_fill() goto(vertices[i]) goto(vertices[i + 1]) # A shortcut for: go to the origi...
# Merged questions for banknotes question print("Input pairs of the form 'value : number'\n" " to indicate that you have 'number' many banknotes of face value 'value'.") print('Input these pairs one per line, with a blank line to indicate end of input.\n') face_quantity = [] while True: # if there is any input...
# A particular case of general trees: tries # # Written by Eric Martin for COMP9021 from binary_tree import * class Trie: def __init__(self): self.is_word = False self.extensions = {} def add_word(self, word): current_trie = self for c in word: if c not in current_...
# Represents a second-order equation as a class with # a, b, c, root_1 and root_2 as data. # By default, a is set to 1 and b and c are set to 0. # The parameters can be changed with the update_parameters() function. # Whether the parameters are changed when the equation is created # or by a call to the update_parameter...
# Reads from a file named tree.txt, containing numbers expected to be organised as a tree, # a number at a depth of N in the tree being preceded with N tabs in the file. # The file can also contain any number of lines with nothing but blank lines. # Uses the module general_tree.py to build the tree represented in the f...
# Checks whether an expression can be generated by the following grammar, # and in case the answer is yes, evaluates the expression and displays its value. # EXPRESSION --> TERM SUM_OPERATOR EXPRESSION # EXPRESSION --> TERM # TERM --> FACTOR MULT_OPERATOR TERM # ...
# Prints out the representation of a positive number in base 2, # using two recursive procedures, one of which is tail-recursive. # # Written by Eric Martin for COMP9021 from math import log, floor def print_binary_representation_1(n): _print_binary_representation_1(n) print() def _print_binary_represe...
available = int(input('Input available digits: ')) desired = int(input('Input desired sum: ')) def solve(available, desired): # if desired sum is negative if desired < 0: return 0 # no available digits left after % at each additional level of recursion tree (at bottom of tree) if available == 0...
# Prints out a conversion table of temperatures from Fahrenheit # to Celsius degrees, with the former ranging from 0 to 300 in steps of 20. # # Written by Eric Martin for COMP9021 min_temperature = 0 max_temperature = 300 step = 20 print('Fahrenheit\tCelsius') for fahrenheit in range(min_temperature, max_temperature ...
# Written by Eric Martin for COMP9021 from linked_list import * class ExtendedLinkedList(LinkedList): def __init__(self, L = None): super().__init__(L) def rearrange(self): node = self.head length = 1 index_of_smallest_value = 0 smallest_value = node.value whil...
# Generates a list of 20 random integers between 0 and 99, # prints out the list, computes the maximum element of the list, # and prints it out. # # Written by Eric Martin for COMP9021 from random import randint # Start with an empty list. L = [] # Randomly generate 20 integers between 0 and 99, and # add every new o...
# git print("Smoke ______, everyday!") # # How many votes did you get? # my_votes = int(input("How many votes did you get in the election? ")) # # Total votes in the election # total_votes = int(input("What is the total votes in the election? ")) # # Calculate the percentage of votes you received. # percentage_votes =...
import random from time import sleep """ Crea un tablero del juego Memorice """ def Boards(cards) : #Se crea un tablero vacío. Por temas de orden cada fila va a tener un máximo arbitrario de 6 cartas width = 6 #Para saber cuántas filas crear hay ver si el número n es divisible por 6 if cards/6 == i...
#AND --- TRUE only and only if both the inputs are true (1). age = int(input("Enter a age")) if age<=0: print("Invalid Input") exit() if age==18 or age==19: print("Just an adult") elif age<18 and age>=6: print("Just a teenager") elif age<6: print("Just a kiddo") else: print("ADULT")
import numpy as np import matplotlib.pyplot as plt from linearRegression import * from regressionTree import * from knn import * if __name__ == "__main__": input_file = 'Marine_Clean.csv' test_file = 'TestCase.csv' print("-----------------------------------------------------------------------------------")...
# Test Script list = ["Betty", "Tina", "Rolla", "Neville", "Devil", "Änna", "Willy", "Spaz", "Pajina", "Nanna", "Bongo Bus"] for i in list: print i print the end
''' 3 Usando o Thonny, escreva um programa em Python que leia três números inteiros , n1, n2 e n3, e os imprima em ordem crescente. ''' n1 = int(input("Entre com o primeiro número:")) n2 = int(input("Entre com o segundo número:")) n3 = int(input("Entre com o terceiro número:")) lista = [n1,n2,n3] print(sorted(lista, ...
""" Usando a biblioteca Pygame, escreva um programa que desenha 1 quadrado amarelo de tamanho 50 na tela em posição aleatória. """ import pygame import random pygame.init() pygame.display.set_caption("--Assessment questão 7 YacovR.--") size = width, heitgh = 800, 600 screen = pygame.display.set_mode(size) green = (3...
# verifies whether the string a user enters is a valid # day. The valid_day() function takes as # input a String, and returns either a valid # Int or None. If the passed in String is # not a valid day, return None. # If it is a valid day, then return # the day as an Int, not a String. Don't # worry about months ...
# importing DNA class from DNA_class import DNA # If the string is longer than 1000 characters # the user will be prompted to enter a string again while True: dna_string = input('Please insert your DNA string. Note: your string cannot be longer than 1000 characters').upper() if len(dna_string) > 1000: ...
# ------ # neccessary imports import random as rd # used to set colors and ships' locations randomly import pygame # used to display ships import save # used to save ships import chat # used to display error messages import math # used to round numbers import copy # idk why but it has to stay from playfie...
""" Специальные методы сравнения объектов классов """ class Rectangle: def __init__(self, a, b): self.a = a self.b = b @property def area(self): return self.a * self.b def __eq__(self, other): if isinstance(other, Rectangle): return self.a == other.a and se...
""" Магический метод __bool__ """ class Point: def __init__(self, x, y): self.x = x self.y = y def __len__(self): return abs(self.x - self.y) def __bool__(self): return self.x != 0 or self.y != 0 p1 = Point(1, 5) print(bool(p1)) p2 = Point(0, 0) print(bool(p2)) p3 = Point...
""" Создайте класс Money, у которого есть: """ class Money: def __init__(self, dollars, cents): self.total_cents = dollars * 100 + cents @property def dollars(self): return self.total_cents // 100 @property def cents(self): return self.total_cents % 100 @dollars.sette...
""" """ class Square: def __init__(self, s): self.__side = s self.__area = None self.__perimetr = None @property def side(self): return self.__side @side.setter def side(self, value): self.__side = value self.__area = None self.__perimetr =...
""" Вспомним нашего приятеля с предыдущих уроков: класс Vector. Ваша задача создать класс Vector, который хранит в себе вектор целых чисел. У класса Vector есть: """ class Vector: def __init__(self, *args): self.values = sorted(list(filter(lambda x: type(x) == int, args))) def __str__(self): ...
""" """ class Cat: breed = 'pers' def hello(*args): print('Hello world from kitty', args) def show_breed(self): print(f'my breed is {self.breed}') def show_name(self): if hasattr(self, 'name'): print(f'my name is {self.name}') else: print('Noth...
#!/usr/bin/python radius=48 pie=3.14285714286 volume=(4.0/3.0)*pie*(radius*radius*radius) print("volume of the sphere="+str(volume))
#parte1 #funciones #definicion de funciones def f_mu(mu,x): return mu*x*(1-x) #ejecuta la funcion print(f_mu(2,0.8)) #conversion F a K #se define la fucnion def FaK(F): return (F+459.67)*(5/9) #ejecutar la funcion F=int(input("\nTemperatura en F: ")) K=FaK(F) print(f"Temperatur en K: {K}")
#graficando con python y matplotlib import numpy as np import matplotlib.pyplot as plt #establece el dominio x=np.linspace(-2,2,50) #funcion y=x**2 #grafica basica plt.plot(x,y) plt.show() #dos elementos en una grafica #establecer el dominio t=np.linspace(0,100,1000) #funciones f1=np.exp(-0.1*t)*np.cos(t) f2=np.cos(...
''' In Python, you can make a program to display the multiplication table of any number. The following program displays the multiplication table (from 1 to 10) according to the user input. ''' print("Python Program to Display the multiplication Table:") num = int(input("Show the multiplication table of:")) for i in r...
''' Armstrong number: A number is called Armstrong number if it is equal to the sum of the cubes of its own digits. For example: 153 is an Armstrong number since 153 = 1*1*1 + 5*5*5 + 3*3*3. The Armstrong number is also known as narcissistic number. ''' num = int(input("Enter a number:")) sum = 0 temp = num while tem...
''' In this program, we need to print the duplicate elements present in the array. This can be done through two loops. The first loop will select an element and the second loop will iteration through the array by comparing the selected element with other elements. If a match is found, print the duplicate element. '''...
''' Variable swapping: In computer programming, swapping two variables specifies the mutual exchange of values of the variables. It is generally done by using a temporary variable. ''' print("Python variable swap program:") x = input("Enter the value of x: ") y = input("Enter the value of y: ") #create a temporary var...
''' In this program, we need to calculate the sum of all the elements of an array. This can be solved by looping through the array and add the value of the element in each iteration to variable sum. ''' arr = [40,20,30,10,50,60,70] sum = 0 for i in range(0,len(arr)): sum += arr[i] print(sum) ...
''' In this program, we need to print the elements of the array in reverse order that is; the last element should be displayed first, followed by second last element and so on ''' arr = [10,20,30,40,50,60,70] print("First way to do it:") for i in range(-1,-len(arr)-1,-1): print(arr[i]) ''' or we can reverse the arra...
import tensorflow as tf import numpy as np from tensorflow.examples.tutorials.mnist import input_data import os def model(x): ''' Creates the model and returns it. Note: There is no training or preprocessing specific operations here RETURNS: ''' x_reshape=tf.reshape(x, [-1, 28, 28, 1]) w...
""" Author: Shiyu Cheng (23329948) ISTA 350 Hw7 SL: Jacob Heller Date: 4/20/20 Summary: Intro to web scrapping. Grabs the data you need from the web, put it into an html parser, and save the result into a file. """ from bs4 import BeautifulSoup import requests, zlib, gzip, os, json def get_soup(url=None, fname=None...
""" Program: nicelist.py Author: Carol Ann Killeen Date: 9/10/19 This program will allow the user to add people's names to one of two text files. One for "nice" people and one for "naughty" people. The user can continue to add people until a STOP command is issued. The files will use "append mode" so the program...
#sort program students = [ "Kendra", "Mary", "Kameron", "Austin", "Leighton", "JaeMin", "Alivia", "Bryan", "Michael", "Lucas", "Matt" ] def sort(obj): arrays = [] for entry in obj: sort = entry sorted_array = [] for entry in sort: x = entry ...
#IO sorter def sort(obj): arrays = [] for sort in obj: sorted_array = [] for entry in sort: x = entry if sorted_array != []: for entry in sorted_array: if x < entry: sorted_array.insert(sorted_array.i...
import time excercises = 3 c = 0 while c < excercises: #minute to prepare n = 60 while n > 0: print n time.sleep(1) n -= 1 #workout r = 8 while r > 0: print 'ROUND ' + str(9 - r) #work n = 20 print 'WORK' while n > 0: ...
def foo(lst): """ >>> x = [1, 2, 3, 4, 5, 6] >>> foo(x) [0, 6, 20] """ return [lst[i] * i for i in range(len(lst)) if i % 2 == 0] # ---------------------------------------------------------------------- def tree(root, branches=[]): for branch in branches: assert is_tree(branch), "b...