text
stringlengths
37
1.41M
p = float(input('Enter Principle Amount : ')) t = int(input('Enter Time in years : ')) r = float(input('Enter Rate of Interest : ')) si=(p*t*r)/100 print("\nThe simple interest is:",si) a = p*(1+(r/100))**t ci = a-p print("\nThe annual compound interest is:",ci)
import heapq # A priority queue which allows custom sorting function # The main priority is the 'f' value. if two elements have the same f value- then sort by creation time. # lastly sort by the action priority as defined in the exercise class PriorityQueue: # constructor def __init__(self, f=lambda x...
""" Read file into texts and calls. It's ok if you don't understand how to read files. """ import csv with open('texts.csv', 'r') as f: reader = csv.reader(f) texts = list(reader) text1 = set() text2=set() for t in texts: text1.add(t[0]) text2.add(t[1]) with open('calls.csv', 'r') ...
#!/usr/bin/env python # coding: utf-8 # # Building a Trie in Python # # Before we start let us reiterate the key components of a Trie or Prefix Tree. A trie is a tree-like data structure that stores a dynamic set of strings. Tries are commonly used to facilitate operations like predictive text or autocomplete feature...
#!/usr/local/bin/python3 import random def primary(): #print("Keep it logically awesome.") (temporarily removed) f = open("quotes.txt") quotes = f.readlines() f.close() last = 13 rnd = random.randint(0, last) #The last signifies that the last variable hlds the highest indes for the array. Then our random...
#!/usr/bin/env /usr/bin/python36 from pprint import pprint input_data_file = "day11.data" def slurp_input(input_file): """ Read the input file. :param input_file: :return: A list of lists. Each list is a row of seats. """ my_seat_map = [] with open(input_file, 'r') as f: while (T...
#!/usr/bin/env /usr/bin/python36 def play_game_and_return_nth_number(start_numbers, nth_number): """ Play game according the rules of AoC2020, Day15a :param start_numbers: the list of starting numbers :param nth_number: how many iterations? :return: the value of the nth iteration """ previo...
def find_avg_year(years): sum = 0 for year in years: sum += year return int(sum/len(years)) def find_avg_year_short(years): return int(sum(years)/len(years)) list_of_cars =["Toyota", "Ford", "BMW", "Audi", "Benz"] list_of_models = ["Camry", "F150", "I8", "A4","S550"] car = { "make" : list_...
# Dictionary # Example of a dictionary my_personal_info = { "name" : "Alpha", "DOB" : "01/01/2020", "School" : "Hostos CC", "GPA" : 0.5 } # Dictionaries are known for their "key-value" pair system # Checking if a key exists in a dictionary if "name" in my_personal_info: print(my_personal_info...
# Finding the roots of a function between a specified region def f(x): return 2*x+1 def find_root(a,b): c=(a+b)/2 ans=f(c) while ans !=0: c=(a+b)/2 ans=f(c) if ans>0: b=c elif (ans<0): a=c else: return c lower=-5 upper=0 print(find_root(lower, upper))
print('Voer je naam in:') naam = input() print('Voer beginstation in:') beginstation = input() print('Voer eindstation in:') eindstation = input() invoerstring = (naam+beginstation+eindstation) lijst = [] def code(invoerstring): for letter in invoerstring: vertalen = chr(ord(letter) +3)# ingevoerde teken ...
import csv with open('namen', 'r') as namen: reader = csv.reader(namen, delimiter=';') for row in reader: print('{} heeft als beroep {}' .format(row[0], row[1]))
while True: print("Geef een string van vier letters:") woord = input() if len(woord) == 4: print('Inlezen van correcte string: %s is geslaagd' %(woord)) break else: lengte = len(woord) print('%s heeft %s letters' %(woord, lengte))
stations = ['Schagen', 'Heerhugowaard', 'Alkmaar', 'Castricum', 'Zaandam', 'Amsterdam', 'Sloterdijk', 'Amsterdam Centraal', 'Amsterdam Amstel', 'Utrecht Centraal', '\'s-Hertogenbosch', 'Eindhoven', 'Weert', 'Roermond', 'Sittard', 'Maastricht'] beginStation = input("Wat is je beginstation? :") if beginStation in statio...
# %% """ There is a large pile of socks that must be paired by color. Given an array of integers representing the color of each sock, determine how many pairs of socks with matching colors there are. Example ar = [10, 20, 20, 10, 10, 30, 50, 10, 20] output = 3 """ # %% from collections import Counter from math impor...
#%% n = 5 l = 1 for i in range(n): if(i%2 == 0): l *= 2 elif(i%2 == 1): l += 1 print(l)
#!/bin/python3 import math import os import random import re import sys # # Complete the 'bonAppetit' function below. # # The function accepts following parameters: # 1. INTEGER_ARRAY bill # 2. INTEGER k # 3. INTEGER b # def bonAppetit(bill, k, b): # Write your code here full_bill_sum = sum(bill) part...
#%% def generate_permutation(chosen_chars, og_string, permutations): ''' the if condition prevents the permutation of duplicates eg: aaaa or aaab, etc, since the continue statement if true ignores the lines below and 'continues' on to the next iteration So in 1st iteration a is selected as choice a...
# -*- coding: utf-8 -*- import json if __name__ == '__main__': text = """ [{"index": 0, "word": "刘德华", "label": "PERSON", "start": 0, "finger": 0, "end": 0}, {"index": 0, "word": "无间道", "label": "SHOW", "start": 0, "finger": 0, "end": 0}, {"index": 0, "word": "梁朝伟", "label": "PERSON", "start": 0, "finger": 0...
from random import randint 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", "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"] SPECIAL_CHARACTER = [",","!","@","#","$","%","^","&","...
nombre=input("ingresa tu nombre: ") edad=input("ingresa tu edad: ") print("tu nombre es: " + nombre) print("tu edad es: "+ edad)
"""A worked example with Fibonacci numbers, to demonstrate tail recursion in Python.""" # fibonacci, stack consuming def fib(n): if n == 0: return 1 return n * fib(n-1) # tail recursive style def fib2inner(n, accum): if n == 0: return accum return fib2inner(n - 1, n * accum) # would...
# Lab 6: Polynomial Functions Test # Section: CPE101-03 # Name: Claire Minahan # Instructor: S. Einakian # Filter Pattern # returns a list of all even values in the input list # list --> list def are_even(list1): list2 = [x for x in list1 if x%2 == 0] return list2 #print(are_even([2, 4, 7])) ...
# Project 1 # # Name: Claire Minahan # Instructor: S. Einakian # Section: CPE101-03 from projFuncs import* def main(): # Inputs pounds = input('How much do you weigh (pounds)? ') pounds = float(pounds) profDistance = input('How far away is your professor (meters)? ') profDistance = floa...
# Lab 9 # Name: Claire Minahan # Section: CPE101-03 # Instructor: S. Einakian from objects import* # returns the distance between two points #point point --> float def distance(point1, point2): dist = ((point1.x - point2.x)**2 + (point1.y - point2.y)**2)**(1/2) return dist # returns True when th...
# Lab 6: Polynomial Functions Test # Section: CPE101-03 # Name: Claire Minahan # Instructor: S. Einakian #Product # takes a nested list returns a list of integers such that each integer is a product of its inner list # list --> list def product(list1): tot = 1 list2 = [] for i in range(len(lis...
# CPE 101 Lab 4 # Name: Claire Minahan def main(): table_size = get_table_size() while table_size != 0: first = get_first() increment = get_increment() show_table(table_size, first, increment) table_size = get_table_size() # Obtain a valid table size from the user #int --> int def get_ta...
import os def rename_files(): #(1) get file names from a folder file_list = os.listdir(r"C:\Projetos\Pessoal\python\prank\prank") print(file_list) saved_path = os.getcwd() print("Current Working Directory is " + saved_path) os.chdir(r"C:\Projetos\Pessoal\python\prank\prank") #(2) for e...
import time import nearest_neighbour as nn import brute_force as bf import back.backend as ba def test_nn(locations): print("test nn") start = time.time() path, distance = nn.nearest_neighbour_dependencies(locations) duration = time.time() - start print("nearest neighbour path: ", path) print("...
import Tkinter # built-in Python graphics library import random import math game_objects = [] class Shape: def __init__(self, x, y): '''Create a new circle at the given x,y point with a random speed, color, and size.''' self.x = x self.y = y self.x_speed = random.randint(1, 5) ...
# imageManip.py - an image manipulation program by Sherri Goings # import pygame class DisplayWindow: """A class that describes a display window that can be used for drawing and manipulating Image objects""" def __init__(self, width, height): """Constructor for a DisplayWindow object.""" ...
# practicing trie implementation # using the implementation provided by Steve Hanov -- just adding # personal comments # Trie data structure keeps a set of words, organized with one node # per letter. Each node has branch for each letter that may follow # in set of words. # e.g., if SET OF WORDS includes # short, sh...
def doormatPattern(rows, columns): width = columns for i in range (0, int (rows / 2)): pattern = "|*|" * ((2 * i) + 1) print (pattern.center (width, '-')) print ("Hacktoberfest2021!".center (width, '-')) i = int (rows / 2) while i > 0: pattern = "|*|" * ((2 * i) - 1) ...
from matplotlib import pyplot as plt import numpy as np class ProbabilityDistribution: def __init__(self,minX,maxX,stepSize): self.minX=minX self.maxX=maxX self.stepSize=stepSize self.domain=np.arange(minX,maxX,stepSize) self._name="Probability Distribution" def getDens...
import math as m def solution(n): count = 0 if n == 2 or n == 3: return 1 else: for i in range (2, n + 1): plus = True for j in range (2, int(m.sqrt(i)) + 1): if i % j == 0: plus = False break if plu...
##code data = input("Enter a value :") print("Output :",data[::-1]) #OUTPUT Enter a value :name Output : eman
import keyword friend = 1 a= 10 my_name = "황일영" myName = "유재석" _yourName = "이정재" member1 = '박명수' print(friend) print(a) print(my_name) print(_yourName) print(member1) # 에러 # $friend = 2 # a! = 1 # 1abc = 3 # def = 3 print(keyword.kwlist) print(len(keyword.kwlist))
# Deze tool berekent de wisselkoers # Door Nikita Verhoeven # Waarde van de valuta in EUR US_DOLLAR = 1.1811 GB_POUNDS = 0.9079 JP_YEN = 125.317 # Vraag om input zodat de juiste valuta wordt genomen valuta = int(input("Kies een valuta. Valuta: 1 = US Dollar, " "2 = GB Pounds, 3 = Yen: ")) wiss...
def denormalize_coordinates(coordinates, size): """ Convert normalized coordinates to integer coordinates that correspond to plane size. Take (xn, yn) where (0 <= xn, yn <= 1) and (width, height). Return False if normalized coordinates are not valid. Return (x, y) where (0 <= x <= width) and (0...
print("What is your age?") age_1 = int(input()) print("What is your age?") age_2 = int(input()) print(age_1 + age_2) age_4 = int(input("What is your name")) age_5 = int(input("What is your name")) print(age_4 + age_5)
print("Mencari bilangan terbesar dari 3 buah bilangan\n") A = int(input("Masukkan Bilangan Pertama: ")) B = int(input("Masukan Bilangan Kedua: ")) C = int(input("Masukan Bilangan Ketiga: ")) if A>B>C: print("\nBilangan Pertama adalah Bilangan Terbesar = %s"%A) elif B>C: print("\nBilangan Kedua adalah Bilanga ...
import re def split_str_digit(s): """ split s into numeric (integer) and non-numeric parts return split as a tuple of ints and strings """ res = [] for m in re.finditer('(\d*)(\D*)', s): for g in m.groups(): if g != '': try: res.append(in...
import numpy as np def ellipsoid_selem(radii, dtype=np.uint8): ''' axis-aligned ellipsoid structuring element dimensionality determined by length of radii iterable ''' # NOTE: when a scalar radius is given, we default to 1D # TODO: this might not be terribly useful, change default or error...
""" Cable Car: Part 1a Class used to make moves (place tiles) Author: Jenny Zhen (jxz6853@rit.edu) Author: Neil Zimmerman (nxz3937@rit.edu) """ from copy import deepcopy class MakeMove(object): """ Class used to make a move / place a tile """ #define slots __slots__ = ('validPos','allMoves',...
import sys import logging class _AnsiColorizer: """ A colorizer is an object that loosely wraps around a stream, allowing callers to write text to the stream in a particular color. Colorizer classes must implement C{supported()} and C{write(text, color)}. """ _colors = dict(black='30m', re...
list_data = [1, 2, 3, 4, 5] for num in list_data: print(num* 2) print("-----" + str(num)) embedded_lists = [[1, 2, 3], [4, 5, 6]] for data in embedded_lists: for num in data: print(num) dict_data= {1:{"name": "gav", "age": "20"}, 2: {"name": "boo", "age": "299"} } # for key in dict_data: # pr...
user_input = True while user_input: age = input("how old are you?") if age.isnumeric() : if age <117: user_input = False
# Fibonacci series # the sum of two elements gives the third number a,b = 0,1 lim =input('Please enter end of fibonacci series:') print "Fibonacci series follows:" print a while b < lim: print b a, b = b, a+b
import prompt ROUNDS_COUNT = 3 def run(game): """Function runs a game.""" print('Welcome to The Brain Games!') player_name = prompt.string('May I have your name? ') print('Hello, {}!'.format(player_name)) print(game.DESCRIPTION) for _ in range(ROUNDS_COUNT): question, correct_answer...
def is_transitive(node1, node2, graph): transitivity_found = False for connectedNode in graph[node1]: if connectedNode == node2: transitivity_found = True break else: transitivity_found = is_transitive(connectedNode, node2, graph) return transitivity_found...
a=10#создаю переменную и присваиваю ей значение 10 b=5#создаю переменную и присваиваю ей значение 5 c=a+b#создаю переменную и присваиваю ей сумму переменных print(c)#вывожу переменную c=a-b#создаю переменную и присваиваю ей разность переменных print(c)#вывожу переменную c=a*b#создаю переменную и присваиваю ей про...
# Day - 4 - 16/07/2021 # Type - Basic Programming # Program - Print the multiplication table for given number # Explanation - Logic is very simple, if number is 2 then 2*i upto N def multiplication_table(number,table_range = 10): for i in range(1,table_range+1): print(number, '*',i,'=',number*i) multiplic...
from Objects import * class BossRoom(Location): def entered(self, hero): print("You don't have a weapon. This boss is really mean and he took all your hearts :(") hero.health = 0 def getMapChar(self): return '\u2620' class Kitchen(Location): def entered(self, hero): print(...
import re from nltk.corpus import brown class SpellChecker: def __init__(self): self.my_dict = brown.words() def check_sentence(self, sentence): rgx = re.compile("([\w][\w']*\w)") result = [] for item in rgx.findall(sentence): if item not in self.my_dict: ...
def pythaTriple(n): return [(x,y,z) for z in range(1,n) for y in range(z,1,-1) for x in range(y,1,-1) if x*x + y*y == z*z] print(pythaTriple(100))
import Player, Turn, GameCommunication as gc class Yahtzee(): def __init__(self, gameCommunication:gc): self.self = self self.gc = gameCommunication self.players = self.getPlayers() self.rounds = self.getRounds() self.startGame() def getPlayers(self) -> list: players = [] player_names ...
import sqlite3 # the control class mediates between model and view class Control: def getModelDescription(self, productmodel): model = Model() view = View() description_data = model.getDescription(productmodel) return view.description(description_data, productmodel) def getProd...
#!/usr/bin/python3 ''' In a text file, there is a single character H. Your text editor can execute only two operations in this file: Copy All and Paste. Given a number n, write a method that calculates the fewest number of operations needed to result in exactly n H characters in the file. ''' def minOperations(n): ...
import random def keyFinder(): try: accountKey = input("What account are you looking for?") with open('allpsswrds.txt', 'r') as file: for line in file: if accountKey in line: print("Here is your key for: " + accountKey) print(line...
from bubble_sort import bubble_sort """ 二进制查找 """ def binary_search(sequence, number, lower, upper): if number in sequence: if lower == upper: return lower else: middle = (lower+upper) // 2 if number > sequence[middle]: return binary_search(sequen...
#!/usr/bin/python #LAB PROJECT 1: HOW RANDOM IS RANDOM? #PART A: CREATE RANDOM NUMBER SEQUENCES: #A-i: print '\n\n\n\n\n\nBEGIN PROJECT 1\n\n\n\n\n\n' print 'BEGIN PROJECT 1 -- PART A-i\n\n\n\n' import Johnston_Functions as MY import numpy as np import matplotlib.pyplot as plt import scipy as sp from scipy.stats ...
import random import sys suits = ('Hearts', 'Diamonds', 'Spades', 'Clubs') ranks = ('Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight', 'Nine', 'Ten', 'Jack', 'Queen', 'King', 'Ace') values = {'Two': 2, 'Three': 3, 'Four': 4, 'Five': 5, 'Six': 6, 'Seven': 7, 'Eight': 8, 'Nine': 9, 'Ten': 10, 'Jack': 10,...
# Ross Nelson CSC380 Assignment 1: Eight Puzzle # January 26th, 2020 # path.py from node import Node import sys # Iterates through the path and prints each node's action, cost, state, # and the current total cost of the solution. def printPath(current, start, time, space, message=""): length = 0 cost = curre...
# Referred video https://www.youtube.com/watch?v=-8n91btt5d8 import pygame import sys import random # Pythons random library pygame.init() # To initialize pygame # Defining the width and height of the screen WIDTH = 800 # Global variables HEIGHT = 600 # Defining the color for player and enemy RED = (255, 0, 0) B...
import pygame from pygame.sprite import Sprite class Bullet (Sprite): """管理飞机发射子弹的类""" def __init__(self,ai_game): """在飞船的位置创建子弹""" super().__init__() self.screen=ai_game.screen self.setting=ai_game.setting self.color=self.setting.bullet_color #在0,0处创建一个表示子弹的矩形,在...
input_map = open("input.txt").read().rstrip() example_map = """..##....... #...#...#.. .#....#..#. ..#.#...#.# .#...##..#. ..#.##..... .#.#.#....# .#........# #.##...#... #...##....# .#..#...#.#""" example_map = example_map.split("\n") input_map = input_map.split("\n") def count_trees(some_map: list) -> int: pos...
with open("input.txt", "r") as input_file: INPUT = input_file.read().strip() EXAMPLE = """nop +0 acc +1 jmp +4 acc +3 jmp -3 acc -99 acc +1 jmp -4 acc +6""" def parse_raw(data_raw: str) -> list: return [[row.split()[0], int(row.split()[1])] for row in data_raw.splitlines()] example_data = parse_raw(EXAMPLE...
inp1="kabali" b=sorted(inp1) inp2=int(input()) count=0 lis=[] for i in range(0,inp2): inp3=input() a=sorted(inp3) lis.append(a) print(lis) for i in lis: if(b==i): count=count+1 print(count)
inp1=int(raw_input()) inp2=int(raw_input()) inp=int(raw_input()) if inp in range(inp1,inp2): print "yes" else: print "no"
num=int(input()) sum=0 temp=num while(temp>0): digit=temp%10 sum+=digit**3 temp//=10 if (num==sum): print("is an Armstrong number") else: print("is not an Armstrong number")
from random import * from time import time def random_array(): return [randint(-50, 50) for _ in range(0, 10**3)] def bubble_sort(arr): for i in range(len(arr)): # k = 0 for j in range(len(arr) - i - 1): if arr[j] > arr[j + 1]: arr[j], arr[j + 1] = arr[j + 1], arr...
import sqlite3 def delete_record(table_name, attribute, data): with sqlite3.connect("main_database.db") as db: cursor = db.cursor() cursor.execute("Pragma foreign_keys = ON") sql = "delete from {0} where {1}=?".format(table_name, attribute) cursor.execute(sql, data) db.commi...
def subsets(l): if len(l)==0: return [[]] final_subset=[] popped_ele=l.pop() print(popped_ele) for i in subsets(l): ns=i.copy() for j in range(0,len(ns)): ns.insert(j,popped_ele) print(ns) final_subset.append(ns) return fina...
a=input().lower() b=input().lower() if a==b: print(0) elif a>b: print(1) else: print(-1)
def rot(arr,n): for i in range(0,n): arr.append(arr.pop(0)) return arr arr=[1,2,3,4,5,7,9] print(rot(arr,6))
# -*- coding: utf-8 -*- """ Created on Sat Nov 21 15:15:29 2020 @author: Dell """ class Stack: def __init__(self,size): self.size = size self.data = [0 for i in range(size)] self.top = 0 def IsEmpty(self): if self.top == -1: return True else: ...
''' Lab 3 ''' def LinearSearch(lst, v): for i in range(len(lst)): if lst[i] == v: return i else: return -1 # print(LinearSearch([2,3,4,5,6], 5)) # Data must be sorted def BinarySearch(data, n, v): l = 0 r = n-1 while l <= r: m = (l+r)//2 if data[m...
class Node: def __init__(self, value): self.value = value self.next = None class LinkedList: def __init__(self): self.head = None self.tail = None def InsertAtFirst(self, value): newnode = Node(value) newnode.next = self.he...
import pygame from pygame.sprite import Sprite class SpaceShip(Sprite): """A class to manage a space ship in the Alien Invasion game""" def __init__(self, game): """Initialize the ship and set its starting position.""" super().__init__() self.screen = game.screen self.settings =...
import numpy as np import matplotlib.pyplot as plt def cost(X,Y,thetas): """ Calcular el costo de un conjunto de hipótesis basado en la cantidad de thetas ingresados. """ hipos = np.matmul(X, thetas) return np.sum(np.power(hipos - Y, 2)) / (2 * X.shape[0]) def derivative(X,Y,thetas): "...
def generic_menu(diccionario): """ Builds a generic menu from the configuration dictionary. Arguments: diccionario -- dictionary where the keys are the options for the menu and the value is the function to execute after getting chosen nargumentos Returns: Results fr...
#! python3 ''' This program will launch a browser, go to the set solver game and automatically solve it for you. Satisfying to write, deeply unsatisfying to run. url: https://www.setgame.com/set/puzzle ''' import bs4, sys, requests, os, time from selenium import webdriver from selenium.webdriver.common.keys...
# Xavier Linn # A Monte Carlo Problem # Metropolis algorithm to compute the properties of a 2D Ising models. # Import statements import numpy as np # Library for providing array and functions to calculate values import matplotlib.pyplot as plt # Library for plotting # TwoDArray is a class that provides a 2D lattice f...
a = 10 print ("Printing a number : ", a) print("Type of variable a : ", type(a)) print ("Type of any number : ", type(-100)) print ("Type of decimal number : ", type(3.5))
numberList = [1, 2, 3] strList = ['one', 'two', 'three'] # No iterables are passed result = zip() # Converting itertor to list resultList = list(result) print(resultList) # Two iterables are passed and looping through them result = zip(numberList, strList) for i, j in result: print("%d is %s " %(i, j)) # Convertin...
import unittest from card import Card from hand import Hand from deck import Deck """ Unit tests for card class. To run all tests, use the following command: 'python3 -m unittest' """ class TestCard(unittest.TestCase): def test_init(self): card_1 = Card(2, "C") self.assertEqual(2, card_1.rank...
# Separar um número inteiro independente de seu tamanho # Nome do projeto: Separar Casas de um número # Linguagem: Python # Utilizações: Variáveis, Repetições e Vetores # Autor: Rafael Lua - rafaellua13 # Usuário deve escolher o numero inteiro positivo de qualquer tamanho num = int(input("Digite o número: ")) ...
#convert temperature from Celsius to Fahrenheit celsius = float(input("Enter temperature in celsius: ")) fahrenheit = (celsius * 9/5) + 32 print('%.2f Celsius is: %0.2f Fahrenheit' %(celsius, fahrenheit)) # Calculate the square root num = float(input('Enter a number: ')) num_sqrt = num ** 0.5 print('The square root...
def without_iota_subscriptum(char): if char == 'ᾳ': return 'α' if char == 'ᾴ': return 'ά' if char == 'ᾲ': return 'ὰ' if char == 'ᾷ': return 'ᾶ' if char == 'ᾁ': return 'ἁ' if char == 'ᾅ': return 'ἅ' if char == 'ᾃ': return 'ἃ' if char == 'ᾇ': return 'ἇ' if char == 'ᾀ': return 'ἀ' i...
import time epoch = time.time() # Get Days Since Epoch secs_in_a_day = 24 * 60 *60 ## Calculate secs in a day my_date = epoch // secs_in_a_day ## Divide epoch by secs in a day to get number of days since epoch num_days = int(my_date) # Change the days to an integer # Get Time t_secs = epoch ...
# Greatest common divisor of two numbers # Euclidean algorithm # GCD(48, 18) # step1: 48/18 = 2 reminder 12 # step2: 18/12 = 1 reminder 6 # step3: 12/6 = 2 reminder 0 def gcd(num1, num2): assert int(num1) == num1 and int(num2) == num2, 'The numbers mst be integer only!' if num2 == 0: return num1 # To handle negat...
# Sum of digit of positive number def sum_of_digit(number): assert number>=0 and int(number) == number, 'This number has to be positive integer only' if number == 0: return 0 else: return (number % 10) + sum_of_digit(number//10) res = sum_of_digit(11111) print(res)
p=float(input("Enter the principle amount:")) t=input("Enter the time(years):") r=float(input("Enter the rate:")) si=(p*t*r)/100 print("The simple interest is: ",si)
a=[] n= input("Enter the number of elements in list:") for x in range(0,n): element=input("Enter element" + str(x+1) + ":") a.append(element) b=[sum(a[0:x+1]) for x in range(0,len(a))] print "The original list is: ",a print "The new list is: ",b
n=input("Enter the number of elements to be in the list: ") l=[] for i in range(0,n): a=input("Element: ") l.append(a) even=0 odd=0 neg=0 for j in l: if(j>0): if(j%2==0): even+=j else: odd+=j else: neg+=j print "Sum of all positive even numbers:",even prin...
a=input("Enter First No: ") b=input("Enter Second No: ") c=input("Enter Third No: ") if a<b<c: print "Largest No is: ",c elif : print "Largest No is: ",a else: print "Largest No is: ",b
a=input("Enter Start: ") b=input("Enter End: ") for i in range(a,b): if i%2!=0: print i
pun = '''!()-[]{};:'"\,<>./?@#$%^&*_~''' str1 =raw_input("Enter Sentence: ") res= " " for char in str1: if char not in pun: res=res + char print(res)
count = 0; while(count < 9): print(count); count+=1 # var = 1 # while var == 1 : # This constructs an infinite loop # num = int(input("Enter a number :")) # print ("You entered: ", num) # while else loop count = 0 while count < 5: print (count, " is less than 5") count = count + 1 else: print (...
# nested if num = int(input("Enter No : ")) if(num < 100): if(num ==50): print("num is 50"); elif(num >50): print("num is greater than 50") else: print("num is less than 50") else: print(" num is not less than 100") # example of a one-line if clause − var = 100 if ( var == 100 ) : print ("Value of expre...