text
stringlengths
37
1.41M
def sum_numbers(nums: [int ot float]) -> int or float: 'Computes the sum of the numbers in the given list' total = 0 for num in nums: total += num return total
# sum_recursive.py # # ICS 32A Fall 2019 # Code Example # # This module contains a function capable of summing the numbers in a # "nested list of integers". A nested list of integers, by our definition # from lecture, is a list in which each element is either: # # * an integer # * a nested list of integers # # T...
import project5_faller import pygame # We'll define some global constants, to introduce names for what would # otherwise be "magic numbers" in our code. Naming constant values with # something that says what they're going to be used for is a good habit # to get into. (People read programs, and it helps if they under...
#outputs a list of characters from a string without having two of the same characters next to eachother #case sensitive def uniqueToList(iterable): output = [] for i in range(len(iterable)): if output == []: output.append(iterable[i]) elif iterable[i-1] != iterable[i]: ...
import math def swap(i1,i2,ar): temp = ar[i2] ar[i2] = ar[i1] ar[i1] = temp return N = int( input()) amari = (N % 30) % 5 first = (N % 30) //5 cards = [] for i in range(6): cards.append((first + i )%6 + 1 ) for i in range(amari): i1 = i%5 i2 = i%5 + 1 temp = cards[i2] cards[i2]...
temp = input().split(" ") a = temp[0] b = temp[1] c = temp[2] a = int(a) b = int(b) c = int(c) if (c> a and c<b) or (c < a and c>b): print("Yes") else: print("No")
import pandas as pd df = pd.read_csv('D:\\Ashu\\python\\Pandas\\weather.csv') #print(df) max_t = df['Temperature'].max() print('Max Temperature is: %s ' %(max_t)) date_rain = df['EST'][df['Events'] == 'Rain'] print('\nDate on which it Rained are: \n %s' %(date_rain)) df.fillna(0, inplace=True) avg_windspeed = df['Wi...
import turtle t = turtle.Pen() y = input("Enter your favorite color.") for x in range(100): t.pencolor(y) t.circle(x) t.left(91)
import pi #Que tenga una expresión .pyc significa que después de la primera ejecución, el programa Python utilizará el .pyc compilado al importar. t_upla = (10,100,1000,10000,100000,1000000,10000000) def f(): lista = [] for j in range (0,len(t_upla)): Pi = pi.g(t_upla[j]) lista = lista + [Pi] print lis...
# this is a string # alice,elise,hello def to_list(the_string): if ',' in the_string: return the_string.split(',') if ' ' in the_string: return the_string.split() return [the_string] the_string = input("Enter the string: ") the_list = to_list(the_string) print(the_list)
nums_of_trips = int(input()) cities = [] for x in range(nums_of_trips): num_of_cities = int(input()) cities = [] for y in range(num_of_cities): city_name = input() cities.append(city_name) print(len(set(cities)))
# Constants to be used in the implementation DIM = 5 POSITION = 'o' EMPTY = 'x' LEFT = 'l' RIGHT = 'r' UP = 'u' DOWN = 'd' QUIT = 'q' def get_move(): ''' Returns a move corresponding to the user input direction ''' move = input('Move: ') if move not in [LEFT, RIGHT, UP, DOWN]: return QUIT els...
x, y, n = input().split() x = int(x) y = int(y) n = int(n) for j in range(1, n + 1): if j % x == 0 and j % y == 0: print("FizzBuzz") elif j % x == 0: print("Fizz") elif j % y == 0: print("Buzz") else: print(j)
my_list = [int(x) for x in input("enter numbers plz: ").split()] lowest_num = my_list[0] for num in my_list: if num < lowest_num: lowest_num = num else: pass print(lowest_num) print(my_list)
for y in range(1, 11): for x in range(1, 11): print("{:>5d}".format(x * y), end="") print("")
class Person(object): def __init__(self, name="", username="", ssn=0): self.name = name self.username = username self.ssn = ssn def get_name(self): return self.name def get_user_name(self): return self.username def get_ssn(self): return self.ssn class...
a_str = input("Please enter a number") b_str = input("Please enter a number") a_int = int(a_str) b_int = int(b_str) qoutient = a_int // b_int remainder = a_int % b_int print( "Qoutient:", qoutient, "remainder:", remainder)
def mutate_list(a_list, index_num, v): ''' Inserts v at index index_num in a_list''' a_list.insert(index_num, v) def remove_ch(a_list, index_num): ''' Removes character at index_num from a_list''' a_list.pop(index_num) def get_list(): ''' Reads in values for a list and returns the list ...
m = int(input("input a number")) n = int(input("input a numer ")) def computeHCF(a, b): if m > n: smaller = n else: smaller = m for i in range(1, smaller+1): if((m % i == 0) and (n % i == 0)): hcf = i return hcf print(computeHCF)
with open("words.txt", "r") as rf: for line in rf: replace = line.replace('. ', '\n') stripped = replace.strip() print(stripped, end=" ") with open("sentences.txt", "w") as w: stripped = replace.strip() w.write(stripped) with open("words.txt", 'r+') as f: text = f.re...
import random import string def get_word_string(filename): try: with open(filename, 'r') as file: word_string = '' for line in file: word_string += line return word_string except FileNotFoundError: print('{} {} {}'.format("File", filename, "n...
def board_dimension(): while True: try: dimension = int(input("Input dimension of the board: ")) if dimension < 3: continue board = [[] for _ in range(dimension)] length = dimension**2 for i in range(1, length + 1): ...
import time def open_file(): """ Prompts the user for a file name. Returns the corresponding file stream or None if file not found """ try: file_name = input("Enter file name: ") data = [] filestream = open(file_name, "r") for line in filestream: if line...
my_list = [] size = int(input("Enter the size of the list: ")) for x in range(size): num = int(input("Enter a number to put in the list: ")) my_list.append(num) sum_of_list = sum(my_list) length_of_list = len(my_list) average_of_list = sum_of_list / length_of_list print("the average of the list is", average...
def populate_list(my_list): word = input("Enter value to be added to list: ") while word.lower() != 'exit': my_list.append(word) word = input("Enter value to be added to list: ") def triple_list(initial_list): return initial_list * 3 initial_list = [] populate_list(initial_list) new_...
def resume(): x = input("Continue: ") if x != 'y': exit() def stock(): while True: try: shares = input("Enter number of shares: ") calculate_total_value(shares) break except ValueError: print("Invalid price!") def calculate_total_va...
def open_file(file): try: sales_list = [] with open(file, "r") as data: for line in data.readlines(): sale = [] for num in line.split(): if num.isdigit(): sale.append(int(num)) if sale: ...
# Function definitions start here def open_file(filename): try: file_stream = open(filename, "r") return file_stream except FileNotFoundError: print() def get_longest_word(file_stream): data = file_stream.readlines() my_word = "a" for word in data: # Read a file lin...
top_num = int(input("Upper number for the range: ")) sum = 0 for i in range(1, top_num): sum =0 for j in range(1, i): if (i % j == 0): sum += j if (sum == i): print(i)
sentence = input("Enter a sentence: ") digits = 0 l = 0 for c in sentence: if c.isdigit(): digits += 1 else: pass lower_case = 0 upper_case = 0 for c in sentence: if(c.islower()): lower_case += 1 elif(c.isupper()): upper_case += 1 #fann ekki betri leið til...
print("Program Perulangan Bertingkat") print() for kolom in range(0, 10): for baris in range(10): print('%3d'%(kolom+baris), end=' ') print(' ')
# coding: utf-8 """ Código inicial usado na Lista de Exercícios 1 do curso "Objetos Pythonicos" de Luciano Ramalho, Python.pro.br. from __future__ import division """ class Contador(object): def __init__(self): self.ocorrencias = {} def incrementar(self, item): qtd = self.ocorrencias.get(ite...
from sys import stdin def find(parent, x): if parent[x] != x: parent[x] = find(parent, parent[x]) return parent[x] def union(parent, a, b): a = find(parent, a) b = find(parent, b) if a < b: parent[b] = a else: parent[a] = b n, m = map(int, stdin.readline().split(' ')) parent = [] ...
from sys import stdin def binary_search(arr, t, s, e): arr.sort() m = (s + e) // 2 if s > e: return None if arr[m] == t: return m elif arr[m] > t: return binary_search(arr, t, s, m-1) else: return binary_search(arr, t, m+1, e) n = int(stdin.readline().rstrip()) ...
# !/usr/bin/env-python # -*- coding: utf-8 -*- import pygame # -COLORES negro = ( 0 , 0 , 0 ) blanco = ( 255 , 255 , 255 ) rojo = ( 200 , 0 , 0 ) verde = ( 0 , 200 , 00 ) azul = ( 0 , 0 , 200 ) amarillo = ( 255 , 255 , 0 ) # -VENTANA tamaño = ancho,alto = 300,500 # Ta...
# Find the min and max value for each column def dataset_minmax(dataset): minmax=list() for i in range (len(dataset[0])): col_values=[row[i] for row in dataset] value_min = min(col_values) value_max = max(col_values) minmax.append([value_min, value_max]) return minmax # ...
from arrangeBoard import arrange_board from queue import Queue import copy import time class Problem(object): def __init__(self, initial): self.initial = initial # values = return values that can be used # used = return list of values that already bee used def filter_values(self, values, used...
""" Automate the Boring Stuff Chapter 1 """ print('Hello, world!') print('What is your name?') # ask for their name myName = input() print('It is good to meet you' + myName) print('The length of your name is:') print(len(myName)) print('What is your age?') # ask for their age myAge = input() print('You wil...
alphabet = {"A":".-","B":"-...","C":"-.-.","D":"-..","E":".","F":"..-.","G":"--.","H":"....","I":"..","J":".---","K":"-.-","L":".-..","M":"--","N":"-.","O":"---","P":".--.","Q":"--.-","R":".-.","S":"...","T":"-","U":"..-","V":"...-","W":".--","X":"-..-","Y":"-.--","Z":"--.."} def splitWord(word): return [char for ...
# переменная объекта через self # переменная класса через имя класса class Robot: ''' Здесь живут роботы ''' population = 0 __privateVar = 79 def __init__(self, name): ''' Инициализация данных ''' self.name = name print('\nInitialization {0}'.format(self.name)) Robot.population += 1 def __de...
service =input("Please enter bill level of service (bad, fair, good) ") if service == "bad": tip=0.10 elif service == "fair": tip=0.15 elif service == "good": tip=0.2 else: print("Please enter exactly bad, fair, good ") bill =int(input("Please enter bill amount. $")) people =int(input("Please ...
import math def sieve(limit): limit += 1 primes = set([x for x in range(2, limit)]) #deleting all multiples of 2 cross_off(primes, 2, limit) #iterating over odd numbers until sqrt of limit for i in range(3, math.ceil(math.sqrt(limit)), 2): cross_off(primes, i, limit) return list(pr...
def timeConversion(s): # # Write your code here. new = s[:8] if s[8:] == 'AM': if new[:2] == '12': return '00' + new[2:] return new else: hours = str(int( + 12)) if hours == 24: hours = 0 return hours + new[2:] result = time...
# Globals for the bearings # Change the values as you see fit NORTH = 0 EAST = 1 SOUTH = 2 WEST = 3 class Robot(object): def __init__(self, bearing=NORTH, x=0, y=0): self.coordinates = (x, y) self.bearing = bearing def turn_right(self): self.bearing = (self.bearing + 1) % 4 def t...
def isPrime(n): if n==2 or n==3: return True if n%2==0 or n<2: return False for i in range(3,int(n**0.5)+1,2): # only odd numbers if n%i==0: return False return True print(isPrime(98)) print(isPrime(100)) print(isPrime(99))
from BinarySearchTree import BinarySearchTree def isBST(root, mini, maxi): if not root: return True if mini and root.data <= mini or maxi and root.data > maxi: return False if not isBST(root.left, mini, root.data) or not isBST(root.right, root.data, maxi): return False ...
# Complete the largestRectangle function below. def largestRectangle(h): biggest = 0 stack = [[0, 0]] for index in range(1, len(h)): if array = [8979, 4570, 6436, 5083, 7780, 3269, 5400, 7579, 2324, 2116] print('Area -> ', largestRectangle(array))
class Node: def __init__(self, val): self.data = val self.children = [] def addChild(self, node): self.children.append(node) def routeBetweenNodes(root, goal): visited = set() queue = [] queue.append(root) while len(queue) > 0: node = queue.pop(0) if nod...
''' # Sample code to perform I/O: name = input() # Reading input from STDIN print('Hi, %s.' % name) # Writing output to STDOUT # Warning: Printing unwanted or ill-formatted data to output will cause the test cases to fail ''' from collections import Counter def arrange_stud(students, capaci...
# -*- coding: utf-8 -*- """ Created on Sun Apr 25 16:36:55 2021 @author: González """ #%% Igualdad print('¿Se cumpe que 2 == 2? \n', 2 == 3) # Desigualdad print('¿Se cumple que 2 != 2 \n', 2 != 3) #%% Comparar magnitudes print("¿Se cumple que 2 > 3\n", 2 > 3) print("¿Se cumple que 2 < 3\n", 2 < 3) print("¿Se cumple...
# -*- coding: utf-8 -*- """ Created on Mon Apr 26 05:11:33 2021 @author: González """ compras = ['Huevo','Leche','Queso','Jabón'] precio = [15,24,20,10] print(f'EL {compras[0]} tiene un valor de {precio[0]}') # Mutabilidad # Las listas tienen la característica de permitirnos modificar el valor de alguno de sus elem...
#!/usr/bin/python3 ''' function to handle open and read files ''' def number_of_lines(filename=""): ''' function to count lines in a file ''' with open(filename, encoding='utf-8') as f: count = 0 for line in f: count += 1 return count
#!/usr/bin/env python # coding: utf-8 # In[3]: ## Isacc Huang, Programming Homework 1, MATH128A ## This is Problem 2 import matplotlib.pyplot as plt import numpy as np import math def f(x): return np.sqrt(1+x) def a(n): x=1 while n > 1: y = n*...
def try_password(number, allow_large_groups): number, last_digit = divmod(number, 10) in_large_group = False found_potential_pair = False found_pair = False last_one_matched = False while number > 0: number, temp = divmod(number, 10) if temp > last_digit: return Fals...
import os import sqlite3 import SimpleHTTPServer from os import system as sys def addTable(cursor, table_name, key_names_csv): cursor.execute('''CREATE TABLE ''' + table_name + ''' (''' + key_names_csv.join(',') + ''')''') def addRow(cursor, table_name, vals_csv): """ Str-vals must be embrac...
#global keyword def spam1() : #define function eggs = "cheesy eggs" # declare eggs local global meat #declare variable as global in scope meat = "h...
def print_formatted(n): alignment = len(bin(n)[2:]) for num in range(1, n + 1): n_dec = str(num) n_oct = oct(num)[2:] n_hex = hex(num)[2:].upper() n_bin = bin(num)[2:] print(n_dec.rjust(alignment), n_oct.rjust(alignment), n_hex.rjust(alignment), n_bin.rjust(alignment)) if...
stu = [] for _ in range(int(input())): name = input() score = float(input()) stu.append([name, score]) stu = sorted(stu, key = lambda x: x[1]) second_lowest_score = sorted(list(set([x[1] for x in stu])))[1] desired_stu = [] for stu in stu: if stu[1] == second_lowest_...
class BinarySearch(list): """ Class to search for a value using binary search """ def __init__(self, a, b) -> None: """ Constructor for the class Args: a: length of list b: step """ super().__init__() self.a = a self.b = b ...
import pandas as pd import numpy as np from sklearn.model_selection import train_test_split from sklearn.linear_model import LinearRegression import matplotlib.pyplot as plt ds=pd.read_csv('C:/Users/User/Downloads/1572467464_student_scores.csv') X=ds.iloc[:,:-1].values y=ds.iloc[:,1].values X_train,X_test,y...
import time import threading def println(arg): print(arg + "\n") def calc_square(numbers): println("Calculate the square of numbers: " + str(numbers)) for n in numbers: time.sleep(0.2) println("Square " + str(n*n)) def calc_cube(numbers): println("Calculate the cube of numbers: " + str(...
import time import multiprocessing #armazenando o resultado (global) def calc_square(numbers, result, v): v.value = 5.68 for idx, n in enumerate(numbers): print("Square " + str(n*n)) result[idx] = n*n if __name__ == "__main__": arr = [2,3,8,9] # vetor result = multiprocessing.Array('i',...
from random import random m1 = int(input("Введите первое целое число: ")) m2 = int(input("Введите второе целое число: ")) n = int(random() * (m2 - m1 + 1)) + m1 print(n) m1 = float(input("Введите первое вещественное число: ")) m2 = float(input("Введите второе вещественное число: ")) n = random() * (m2 - m1) + m1 prin...
""" Robot Rover """ def faceLeft(current_direction): if current_direction == "North": current_direction = "West" elif current_direction == "West": current_direction = "South" elif current_direction == "South": current_direction = "East" else: current_direction = "North" ...
""" Reference: [1] https://pytorch.org/tutorials/beginner/transformer_tutorial.html """ import numpy as np import torch from torch import nn import torch.nn.functional as F from torch.nn.init import xavier_uniform_, kaiming_normal_ from torch.nn import TransformerEncoder, TransformerEncoderLayer class Positional_Enco...
from collections import * class Ulist(UserList): def __add__(self, other): if isinstance(other, UserList): return self.__class__(self.data + other.data) elif isinstance(other, type(self.data)): return self.__class__(self.data + other) else: ret...
MENU = { "espresso": { "ingredients": { "water": 50, "coffee": 18, }, "cost": 1.5, }, "latte": { "ingredients": { "water": 200, "milk": 150, "coffee": 24, }, "cost": 2.5, }, "cappuccino": { ...
#!/usr/bin/env python #note it appears that list from blackboard gives weird string #output a csv file with group name taken from github from copy import deepcopy from random import randint def get_rand_seat_number(seatlist): #print seatlist index=randint(0,len(seatlist)-1) rand=deepcopy(seatlist[index]) seatlist.r...
# There are comments with the names of # the required functions to build. # Please paste your solution underneath # the appropriate comment. # search def search(array, query): if len(array) == 0: return False if query == array[0]: return True else: return search(array[1:], query) ...
#!/usr/bin/python #food_choice.py #by: trent patterson #Sets the names for the items name1 = 'Pizza'; name2 = 'Chicken Fingers'; name3 = 'Cheeseburger'; name4 = 'Hot Dog'; #Sets the prices for the items cost1 = '4.99'; cost2 = '6.99'; cost3 = '5.99'; cost4 = '3.99'; print("What would you like to order?") #Prints t...
#!/bin/env python2.7 """ Reads graph structures and values from text files. Author: Ali Hajimirza (ali@alihm.net) """ import numpy as np from scipy.sparse import * import scipy import sys def count_nodes(f): """ Counts the number of nodes in a file. Each line corresponds to a node. Thus, the number of nod...
import tkinter as tk import tkinter.font as tkFont calculator = tk.Tk() calc_input = tk.StringVar() merge = {} calculator.title('Calculator') fontStyle = tkFont.Font(family = "Helvetica ", size = 12) # Need separate frames for a display, and the buttons display_frame = tk.Frame(calculator) display_frame.pack()...
import random ENDINGS=['no', 'nope','bye','stop','goodbye','never mind'] CONFIRMS=['yes','yeah','absolutely'] MISTAKE_THRESHOLD=.3 def getGoalFromHuman(dummy_list): # location= random.choice(list(dummy_list.keys())) # import pdb; pdb.set_trace() # greet the user and get the goal location response=inpu...
def power(x): if x**2>=50: print('{}的平方为:{},不小于50,继续'.format(x,x**2)) else: print('{}的平方为:{},小于50,退出'.format(x,x**2)) quit() while True: x=int(input('输入数字:')) power(x)
x=int(input('请输入一个数x:')) y=int(input('请输入一个数y:')) z=int(input('请输入一个数z:')) if x>y: x,y=y,x if x>z: x,z=z,x if y>z: y,z=z,y print(x,y,z)
import turtle turtle.screensize() turtle.pensize() turtle.pencolor("black") turtle.setheading(90) primespeed= 1 for k in range(2): for j in range(60): if j < 30: primespeed += 0.2 else: primespeed -= 0.2 turtle.forward(primespeed) t...
n=int(input('请输入要计算的整数:')) a=1 x=0 for i in range(1,n+1): num=i for j in range(i-1,0,-1): num*=j x+=num print(x)
#Parameters and Arguements in function #Parameters are used to define the function #Arguements are used to call the function. The actual values to the function are provided by the arguements. #Parameters def say_hello(name, emoji): print(f'Hello {name}{emoji}') #Arguements say_hello('Antara', '^_^') say_hello('Juli...
#Iterables #Iterable is an object or a collection that can be iterated over. # sets, lists, tuples, dictionary, string are iterables. These are iterable because they can be iterated.Iterated means we can go one by one to check the collection. #Iterable is the object or item, iterate is the action over iterable. #We...
# These are positional Arguements ''' def say_hello(name, emoji): print(f'Hello {name}{emoji}') #Arguements say_hello('Antara', '^_^') ''' #Default Parameters: #Default parameters will provide the default values even if any arguements are not passed while calling the function. ''' def say_hello(name='Darth Vader'...
# Counter # This program will print the total sum of the items in the list my_list = [1,2,3,4,5,6,7,8,9,10] counter = 0 for item in my_list: counter = counter + item print(counter)
#Ternary Operators # This operator is a way to mke your code more cleaner. This operator is also called Conditional Expressions. # condition_if_true if condition else condition_if_false is_friend = False can_message = "message is allowed" if is_friend else "can't send message" print(can_message)
import random global DD class Card: def __init__(self,rank,suit): self.rank = rank self.suit= suit def __repr__(self): return "Card("+self.rank+","+self.suit+")" class Deck: rank = ["2","3","4","5","6","7","8","9","10","J","Q","K","A"] suit = [ "\u2660...
from reverse_string import reverse_string from reverse_number import reverse_number from reverse_digits import reverse_digits def main (): my_string = "Hello world" print("Ma string:", my_string) my_reverse_string = reverse_string(my_string) print("Ma string inversée:", my_reverse_string) my_number = -1234 prin...
def calculator(number1, number2, operator): if operator == '*': return number1 * number2 elif operator == '+': return number1 + number2 elif operator == '**': return number1 ** number2 elif operator == '/': if number2 == 0: return False return number1 / number2 elif operator == '//': if number2 == 0...
""" File: largest_digit.py Name: ---------------------------------- This file recursively prints the biggest digit in 5 different integers, 12345, 281, 6, -111, -9453 If your implementation is correct, you should see 5, 8, 6, 1, 9 on Console. """ def main(): print(find_largest_digit(12345)) # 5 print(find_larg...
# Project Euler # Utility Functions from math import sqrt, ceil def create_prime_array(up_to_num): sieve = [True] * (up_to_num + 1) prime_array = [] for prime in range(2, up_to_num + 1): if sieve[prime]: prime_array.append(prime) for i in range(prime, up_to_num + 1, prime):...
# Project Euler # Problem 36: Double-base Palindromes def is_palindrome(num_str): if num_str == num_str[::-1]: return True return False if __name__=="__main__": double_palindromes = [] for n in range(1_000_000): if is_palindrome(str(n)): binary = bin(n) if is_pa...
# Project Euler # Problem 17: Number Letter Counts def count_letters(nums): count = 0 for num in nums: for letter in num.casefold(): if letter.isalpha(): count += 1 if 'hundred ' in num.casefold(): count += 3 return count if __name__ == "__...
# Project Euler # Problem 32: Pandigital Primes def solve(): products = set() digit_set = set('123456789') for x in range(1, 100): for y in range(100, 10_000): digits = str(x) + str(y) + str(x*y) if len(digits) == 9 and set(digits) == digit_set: products...
# Project Euler # Problem 47: Distinct Prime Factors def create_prime_array(up_to_num): sieve = [True] * (up_to_num + 1) prime_array = [] for n in range(2, up_to_num + 1): if sieve[n]: prime_array.append(n) for i in range(n, up_to_num + 1, n): sieve[i] = Fals...
# Project Euler # Problem 12: Highly Divisible Triangular Number from time import perf_counter from math import sqrt, ceil def next_triangle(): n, tri_num = 0, 0 while True: n += 1 tri_num += n yield tri_num def create_prime_array(up_to_num): sieve = [True] * (up_to_num + 1) p...
import pygame class Paddle(pygame.sprite.Sprite): """A class to handle the pong paddle""" def __init__(self, pong_game, x): """Create the paddle at the given x position""" super().__init__() # Screen attributes self.screen = pong_game.screen self.screen_rect =...
import time # times of retries num_retries = 3 # loop for retries for i in range(num_retries): try: # code to try result = 1 / 0 print("Result:", result) # a specific type of the error/exception is required here except ZeroDivisionError: # catch exceptions ...
#iterator is an object that contains a countable number of values #python containers are all iterable #__iter__() and __next__() are built-in functions for iterators mytuple = ("apple", "banana", "cherry") myiter = iter(mytuple) print(next(myiter)) print(next(myiter)) print(next(myiter)) #string is also i...
#Arithmetic(Assignment) Operators #= x = 1 print("x = ", x) print() #addition +(=) x = 2 y = 8 print("x + y =", x+y) print() #subtraction -(=) print("y - x =", y - x) print() #multiplication *(=) y*=x print("x * y =", y) print() #division /(=) y /= x print("y / x =", '{:1.0f}...
roman = { "M" : 1000, "D" : 500, "C" : 100, "L" : 50, "X" : 10, "V" : 5, "I" : 1 } def add_numerals(num1, num2): global roman no1 = list(num1) no2 = list(num2) for i in range(len(no1)): no1[i] = roman[no1[i]] for j in range(len(no2)): ...
import itertools as it def sequence_equals(cmpf, l_seq, r_seq): ''' >>> import operator as op >>> sequence_equals(op.eq, range(3), range(3)) True >>> sequence_equals(op.eq, range(3), range(4)) False >>> sequence_equals(op.eq, [], []) True >>> sequence_equals(op.eq, range(3), []) ...
# taking input of name from the use import streamlit as st import pickle import requests movies_list = pickle.load(open('movies.pkl','rb')) movies_l = movies_list['title'].values similarity = pickle.load(open('similarity.pkl','rb')) st.title("Movie Recommendation System") option = st.selectbox( 'Select a movie...
try: num = int(input('Enter a number between 1-30: ')) num1 = 30//num if num > 30: raise ValueError(num) except ZeroDivisionError as err: print(err, "You can't divide by Zero.") except ValueError as err: print(err, num, "Bad Value!, Enter a number between 1-30") except: print("Invalid In...