text
stringlengths
37
1.41M
#!/usr/bin/python months = { "January": 1, "February": 2, "March": 3, "April": 4, "May": 5, "June": 6, "July": 7, "August": 8, "September": 9, "October": 10, "November": 11, "December": 12 } try: ri = raw_input("Enter month\n") if months.has_key(ri): print 'Number month is', months[ri] else: ...
def count_trees(file, *slopes): with open(file) as f: file = f.read().splitlines() total = 1 for slope in slopes: count = 0 x, y = 0, 0 while y < (len(file) - 1): x += slope[0] y += slope[1] if x > (len(file[y])-1): x -= len...
import turtle def draw_square(some_turtle): for j in range(1,5): some_turtle.forward(100) some_turtle.right(90) def draw_art(): window = turtle.Screen() window.bgcolor('pink') # create personalize turtle brad = turtle.Turtle() brad.shape("turtle") brad.color('green') brad...
province = input('What province do you live in? ') if province in ('chennai', 'madurai'\ 'nagercoil'): tax = .5 elif province.lower() == 'azhagai': tax = .4 else: tax = .9 print(tax)
class User: #class def __init__(self, username, email_address):# now our method has 2 parameters! self.name = username # and we use the values passed in to set the name attribute self.email = email_address # and the email attribute self.account_balance = 0 ...
#!/usr/bin/env python # -*- coding: utf-8 -*- # This script finds stray pixels in an indexed PNG file. # A stray pixel is defined as one or a few pixels of a particular color # lost among a large amount of pixels of another color # Any area with less pixels than this value will trigger a warning MAX_AREA_SIZE = 5 im...
# Student ID: 1201200463 # Student Name: Lim Wee Zheng kilo = float(input("Please enter the value of kilogram: ")) gram = kilo * 1000 print("For {:.2f} kilogram is equivalent to {:.2f} gram".format(kilo,gram))
import requests import collections MovieResult = collections.namedtuple( 'MovieResult', 'imdb_code, title, duration, director, year, rating, imdb_score, keywords, genres' ) search = input("What movie do you want to search for?") # key word in movie title url = 'http://movie_service.talkpython.fm/api/search/{...
#!/usr/bin/python3 import string badchar = input("Enter Letter: ") def encode(badchar): for x in string.printable: for y in range(16): if chr(ord(x) ^ y) == str(badchar): print(x + ' ' + str(y)) encode(badchar)
import math import unittest from algos.recursion import * class TestLinkedList(unittest.TestCase): def test_factorial(self): n = 10 assert math.factorial(n) == compute_factorial(n) def test_reverse_string(self): s = 'abc' assert 'cba' == reverse_string(s) def test_a_pow...
#!usr/bin/python3.8.0 # --> called: shebang, checkout why it's useful """ Project: To be decided Module : dashed.py Autor : Shruti Created: 13th September 2020 These are called docstrings, they can be used to store multiline string values. Commonly used to document your code on a high-le...
import datetime name = raw_input("What is your name: ") age = int(input("How old are you: ")) thisYear = int(datetime.date.today().strftime("%Y")) year = str((thisYear-age)+100) print(name+" will turn 100 years old in the year "+year)
#1 radius=float(input("enter number")) def area(rad): area= 3.14*rad*rad return area ar= area(radius) print(ar) #2 def perfect(n): sum = 0 for i in range(1,n): if(n%i==0): sum= sum + i if(sum==n): return True else: return False for i in range(1,1001): ...
""" Fibonacci Write a program to print terms in the Fibonacci sequence up to a maximum value. In the 13th century, the Italian mathematician Leonardo Fibonacci, as a way to explain the geometric growth of a population of rabbits, devised a mathematical sequence that now bears his name. The first two terms in this sequ...
""" If you're up for it, we can make Khansole Academy an even better learning tool. Be creative! We recommend you start with the "three in a row" extension first, then come up with your own :-). Three in a row In the previous milestone you wrote code to randomly generate one addition problem at a time and tell the us...
""" Tiny mad libs Write a program which prompts the user for an adjective, then a noun, then a verb, and then prints a fun sentence with those words! Mad Libs is a word game where players are prompted for one word at a time, and the words are eventually filled into the blanks of a word template to make an entertaining...
import tkinter import user_input_check '''This module creates an input menu to prompt user for information using tkinter''' class Input_Window(): def __init__(self): self.input_window = tkinter.Tk() self.input_window.resizable( width = 0, height = 0) title_menu = tk...
""" By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13. What is the 10 001st prime number? """ from lib.primes import fast_nth_prime print(fast_nth_prime(10001))
""" If the numbers 1 to 5 are written out in words: one, two, three, four, five, then there are 3 + 3 + 5 + 4 + 4 = 19 letters used in total. If all the numbers from 1 to 1000 (one thousand) inclusive were written out in words, how many letters would be used? NOTE: Do not count spaces or hyphens. For example, 342 (th...
# If we want our solution to be scalable, we need to omit the rotations that # are useless. For instance: # A = [1, 2, 3, 4] # K = 4 # the function should return [1, 2, 3, 4] # But we also have # A = [1, 2, 3, 4] # K = 8 # the function should return [1, 2, 3, 4] # The pattern is that if K is a multiple of the length of...
# !pip install pycryptodome """ Programmed by Muhammet Çelik (mcelik - 20418) and Kemal Sarper Yücel(syucel - 21031) """ import random from Crypto.Hash import SHA3_256 def egcd(a, b): x,y, u,v = 0,1, 1,0 while a != 0: q, r = b//a, b%a m, n = x-u*q, y-v*q b,a, x,y, u,v = a,r, u,v, m,n ...
from cryptography.fernet import Fernet import ast import os.path import os import getpass def main(): print("============ Main Menu ============ \n") a = input(" 1. Create an account\n 2. Login \n 3. Reset keys \n 4. Exit \n") if a == "1": create_account() if a == "2": login() if a ...
""" Implements Ackermann function algorithm """ # inbuilt libs import logging import sys logger = logging.getLogger(__name__) # variable to store the number of recursive calls made recursion_count = 0 def ackermann_function(m, n): """ Calculate the value of Ackermann function A(m, n). According to defi...
def PrintFromTopToBottom(root): # write code here if not root: return [] #注意这里不能返回None,而应该i是[] queue = [root] res = [] while queue: n = len(queue) for _ in range(n): if not queue: break node = queue.pop(0) res.append(node.val) if node.l...
""" Requirement: https://leetcode.com/problems/rotate-array/ Given an array, rotate the array to the right by k steps, where k is non-negative. Example 1: Input: [1,2,3,4,5,6,7] and k = 3 Output: [5,6,7,1,2,3,4] Explanation: rotate 1 steps to the right: [7,1,2,3,4,5,6] rotate 2 steps ...
#!/usr/bin/python """ https://www.tutorialspoint.com/python/python_tuples.htm """ # Accessing Values in Tuples print('\naccess:') tup1 = ('physics', 'chemistry', 1997, 2000) tup2 = (1, 2, 3, 4, 5, 6, 7) print("tup1[0]: ", tup1[0]) print("tup2[1:5]: ", tup2[1:5]) # Updating Tuples print('\nupdate:') tup1 = (12, 34.5...
""" Idea: keep going to divide items to left and right until atom, then merge and sort them up back to a whole items Special: divide first then conque Complexity: O(nlog(n)) Ref Course: https://www.linkedin.com/learning/programming-foundations-algorithms/the-merge-sort?autoplay=true """ def mergesort(ite...
''' 15. 3 Sum Given an array nums of n integers, are there elements a, b, c in nums such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero. Note: The solution set must not contain duplicate triplets. Example: Given array nums = [-1, 0, 1, 2, -1, -4], A solution set is: [ [-1,...
""" Assumption: What does table means? My assumption is a list of number. Basing on that, I am coding. """ def internal(table): nummax = 0 numset = set() for element in table: if element not in numset: numset.add(element) nummax = element if element > nummax else numm...
def heuristic(capacity, items): """ This function performs heuristic, greedy solution to the knapsack problem based on the value-to-size ratio. """ items.sort(key=lambda el: el.desire, reverse=False) solution = [] _size = 0 while _size < capacity and items: taken = items.pop(...
# LeetCode: Problem 66 # Jonathan Kosasih #Given a non-empty array of digits representing a non-negative integer, plus one to the integer. # #The digits are stored such that the most significant digit is at the head of the list, #and each element in the array contain a single digit. # #You may assume the integer does ...
# LeetCode: Problem 56 # Jonathan Kosasih #Given a collection of intervals, merge all overlapping intervals. # #Example 1: #Input: [[1,3],[2,6],[8,10],[15,18]] #Output: [[1,6],[8,10],[15,18]] #Explanation: Since intervals [1,3] and [2,6] overlaps, merge them into [1,6]. # #Example 2: #Input: [[1,4],[4,5]] #Output: [[1...
# LeetCode: Problem 242 # Jonathan Kosasih #Given two strings s and t , write a function to determine if t is an anagram of s. # #Example 1: #Input: s = "anagram", t = "nagaram" #Output: true # #Example 2: #Input: s = "rat", t = "car" #Output: false #------------------------------------------------------------------ c...
# LeetCode: Problem 131 # Jonathan Kosasih #Given a string s, partition s such that every substring of the partition is a palindrome. # #Return all possible palindrome partitioning of s. # #Example: #Input: "aab" #Output: #[ # ["aa","b"], # ["a","a","b"] #] #----------------------------------------------------------...
# LeetCode: Problem 22 # Jonathan Kosasih #Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses. # #For example, given n = 3, a solution set is: # #[ # "((()))", # "(()())", # "(())()", # "()(())", # "()()()" #] #---------------------------------------------------...
# LeetCode: Problem 268 # Jonathan Kosasih #Given an array containing n distinct numbers taken from 0, 1, 2, ..., n, find the one that is missing from the array. # #Example 1: #Input: [3,0,1] #Output: 2 # #Example 2: #Input: [9,6,4,2,3,5,7,0,1] #Output: 8 # #Note: #Your algorithm should run in linear runtime complexit...
# LeetCode: Problem 19 # Jonathan Kosasih #Given a linked list, remove the n-th node from the end of list and return its head. # #Example: # #Given linked list: 1->2->3->4->5, and n = 2. # #After removing the second node from the end, the linked list becomes 1->2->3->5. #Note: # #Given n will always be valid. #-------...
# LeetCode: Problem 62 # Jonathan Kosasih #A robot is located at the top-left corner of a m x n grid (marked 'Start' in the diagram below). # #The robot can only move either down or right at any point in time. The robot is trying to reach the bottom-right corner of the grid (marked 'Finish' in the diagram below). # #H...
# LeetCode: Problem 189 # Jonathan Kosasih #Given an array, rotate the array to the right by k steps, where k is non-negative. # #Example 1: #Input: [1,2,3,4,5,6,7] and k = 3 #Output: [5,6,7,1,2,3,4] #Explanation: #rotate 1 steps to the right: [7,1,2,3,4,5,6] #rotate 2 steps to the right: [6,7,1,2,3,4,5] #rotate 3 ste...
# LeetCode: Problem 217 # Jonathan Kosasih #Given an array of integers, find if the array contains any duplicates. # #Your function should return true if any value appears at least twice in the array, #and it should return false if every element is distinct. # #Example 1: #Input: [1,2,3,1] #Output: true # #Example 2: ...
# LeetCode: Problem 412 # Jonathan Kosasih #Write a program that outputs the string representation of numbers from 1 to n. # #But for multiples of three it should output “Fizz” instead of the number and #for the multiples of five output “Buzz”. For numbers which are multiples of both three and five output “FizzBuzz”. ...
# LeetCode: Problem 38 # Jonathan Kosasih #The count-and-say sequence is the sequence of integers with the first five terms as following: # #1. 1 #2. 11 #3. 21 #4. 1211 #5. 111221 #1 is read off as "one 1" or 11. #11 is read off as "two 1s" or 21. #21 is read off as "one 2, then one 1" or 1211. # #...
# LeetCode: Problem 206 # Jonathan Kosasih #Reverse a singly linked list. # #Example: #Input: 1->2->3->4->5->NULL #Output: 5->4->3->2->1->NULL #------------------------------------------------------------------ # Definition for singly-linked list. class ListNode(object): def __init__(self, x): self.val = x...
# LeetCode: Problem 234 # Jonathan Kosasih #Given a singly linked list, determine if it is a palindrome. #Example 1: #Input: 1->2 #Output: false # #Example 2: #Input: 1->2->2->1 #Output: true #------------------------------------------------------------------ # Definition for singly-linked list. class ListNode: d...
# LeetCode: Problem 210 # Jonathan Kosasih #There are a total of n courses you have to take, labeled from 0 to n-1. # #Some courses may have prerequisites, for example to take course 0 you have to first take course 1, #which is expressed as a pair: [0,1] # #Given the total number of courses and a list of prerequisite ...
# Your code here!! def sing(): for i in range(10): if i<4 or i>4 and i<8: print("let it be,") elif i==4: print("whisper words of wisdom, let it be, let it be,") elif i==9: print("there will be an answer, let it be") sing()
from getch import getch, pause print "Push any key. (ESC : exit)" while True: key = ord(getch()) if key == 13: # Enter print "Enter" pass elif key == 27: # ESC key = ord(getch()) if key == 91: # Arrow keys key = ord(getch()) if key == 66: print "Down Arrow" elif ke...
# converting numbers (number to different base number) # encoding characters (char to number) # decoding characters (number to char) class ConvertingArrays(object): """dynamically set up a method to call conversions for arrays""" def __init__(self): super().__init__() @staticmethod def array...
#! /usr/bin/python # Filename: 4_palindrome_in_base.py # Description: Solution to <Series 1 - Problem 4> # Author: Ali Mousavi <ali.mousavi@gmail.com> # Instructor: Mr. Ali Rezaee # Date: 2018/10/23 import sys def convert_bases(number, initial_base=10, converted_base=10): """Converts a number fro...
a = input()[::-1] b = input()[::-1] op = "<" if int(a) == int(b): op = "=" elif int(a) > int(b): b, a = a, b print(a[::-1], op, b[::-1])
#!/Python36/python import pymongo import pandas as pd from os import system from pymongo import MongoClient import time import datetime def to_integer(stu_doa): return 10000*stu_doa.year + 100*stu_doa.month + stu_doa.day class student: def add_student(self): stu_roll=int(input("enter roll no of stud...
import matplotlib.pyplot as plt import pandas as pd import date_utils as dtutils def history_plot(history, loss_units=None): epochs = len(next(iter(history.history.values()))) ylabel = "loss" if loss_units is None else f"loss ({loss_units})" xlabel = "epoch" multiline_plot( history.h...
class Funcionario(object): def __init__(self, nome, cargo, salario): self.nome = nome self.cargo = cargo self.salario = salario def calcula_reajuste(self): if self.cargo.lower() == 'operador': return self.salario * (1.2) elif self.cargo.lower() == 'progr...
the_count = [1, 2, 3, 4, 5] fruites = ['apples', 'oranges', 'pears', 'apricots'] change = [1, 'pennies', 2, 'dimes', 3, 'quarters'] for number in the_count: print ("this is count : %d" % number) for fruit in fruites: print ("A fruit of type : %s" % fruit) for i in change: print ("I got %r" % i) eleme...
# -*- coding: utf-8 -*- """ Created on Wed May 15 18:49:33 2019 @author: wukak """ def timestamp_dict(): timestamp = dict() for year in range(2000,2020): for month in range(1,13): key = str(year + float(month)/100) if len(key) < 7: key += '0' ...
user_name = input("Please enter your name: ") out_file = open('name.txt', 'w') print(user_name, file=out_file) out_file.close() in_file = open('name.txt', 'r') print("Your name is ", in_file.read()) in_file.close() sum_of_numbers = 0 in_file = open('numbers.txt', 'r') for i in in_file.readlines(): sum_of_numbers ...
# generates hashiwokakero boards from https://gamegix.com/hashi-o-kakero/game # the board needs to be copies into input_board.txt dim = 13 f = open('input_board.txt', 'r') board = f.readlines() board_list = [] for i in range(dim): row = [] for j in range(dim): row.append(0) board_list.append(row) ...
import sqlite3 from datetime import datetime users = sqlite3.connect("users_data") """users.execute("INSERT INTO user1 values('hellloooo','user3','"+str(datetime.now())+"')") users.execute("INSERT INTO user1 values('bye','user3','"+str(datetime.now())+"')") users.execute("INSERT INTO user1 values('bye','user3','"+str...
size = input() li = input().strip(" ").split(" ") max_block = 0 temp = 0 flag = li[0] for j in li[1:]: if (j=='0' and flag=='0'): max_block += 1 print (max_block , j) elif (j=='1' and flag=='0'): if temp < max_block: temp = max_block max_block = 1 print (max_b...
def fun1(string): length = len(string) max_lex = length counter = 0 if(not length): return max_lex def fun2(key_index,compare_index , count, start_point): nonlocal max_lex, counter counter += 1 if(compare_index >= length or key_index > l...
def reverse(stack): start = 0 end = len(stack) - 1 def recur(stack , start , end): if start > end: return else: temp = stack[start] stack[start] = stack[end] stack[end] = temp recur(stack, start+1 , end-1) rec...
#use for fraction from fractions import Fraction #use for decimal calculations float gives you approximate result from decimal import Decimal def fraction(a,b): try: return Fraction(int(a),int(b)) except Exception as e: return e def decimal(num): try: if isinstance(num,float): ...
import matplotlib.pyplot as plt def get_para(): x = tuple(map(float, input("X-Axis: ").split(" "))) y = tuple(map(float, input("Y-Axis: ").split(" "))) if len(y) == len(x): return [x, y, ""] else: return [[], [], "Invalid Args: Length Must Be Same."] def add_legend(): x, y, err =...
def sum_of_fibonacci(maximum, sum_even): """ Function returns the sum of all even or odd terms in the fibonacci sequence up to maximum. REQ: maximum >= 0 and whole :param maximum: {int} is maximum to sum to :param sum_even: {bool} determines whether to sum even or odd terms :return: {i...
def largest_continuous_product(series, adjacent): """ Function returns the largest product of adjacent numbers within the given series. REQ: type(series) == str and int(series) REQ: type(adjacent) == int :param series: {string} series of whole integers within a string :param adjacent: {int} nu...
import os import sys sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) from sum_of_multiples import sum_of_multiples if __name__ == "__main__": # get inputs form user maximum = input("Please enter a maximum number: ") divisor_one = input("Please enter your first multi...
def largest_prime_factor(input_num): """ Function returns the largest prime factor of an input. REQ: input_num >= 0 and whole :param input_num: {int} is original input number :return: {int} the largest prime factor of the input or {NoneType} if input_num < 2 """ # if input is less than 2,...
#Определите ключ шифра сдвига, которым зашифровано одно из, возможно самых знаменитых, #изречений Гая Юлия Цезаря: MVEZ MZUZ MZTZ Ответ представьте в виде целого числа. #127 def ceasar(story, shift): return ''.join([ # concentrate list to string (lambda c, is_upper: c.upper() if is_upper else c) # if or...
#Дана строка. Показать третий, шестой, девятый и так далее символы. #6 def get_string_1_3_6(string,step): start = step; while start < len(string): print (string[start], start) start+=step get_string_1_3_6('denisprinesivadipazhaluysta1',3)
class User: def __init__(self, name): self.name = name users = [User("Jose"), User("Rolf"), User("Anna")] selected_username = "Jose" selected_users = list(filter(lambda user: user.name == selected_username, users)) print(selected_users[0].name)
#try :예외발생 #except:예외발생시 실행 #else:예외발생하지 않을떄 #finally :항상 # 원화를 입력, 환율 입력 -> 달러값 won = input("원화금액을 입력해>>>") dollar = input("환율을 입력해>>>") try: # 예외가 발생 할 수 있는 코드 print(int(won) / int(dollar)) except ValueError as s: # 문자 넣을시 출력 print("문자열 예외가 발생했다.", s) except ZeroDivisionError as s: #나누기 0 넣으면 출력 print("...
# 파일 열기 => 작업 => 닫기 # (w)write:덮어쓰기,(a)append:이어쓰기,(r)read #1.파일 쓰기 file = open("E:/python/Chapter10/filetest/data0823.txt", "w", encoding="utf8") file.write("1.인생은고통이다") file.close #2. 파일추가 file = open("E:/python/Chapter10/filetest/data0823.txt", "a", encoding="utf8") file.write("\n2.상위 5% 뺴면 시궁창이다.") file.close()...
# raise 구문을 사용해서 에러를 강제로 발생시켜 봅시다. try: num = int(input("음수를 입력해 주세요>>>")) if num >= 0: raise ValueError("양수는 입력 불가") except ValueError as e: print("에러 발생!", e)
# 실습문제 6.1.3 # 로또 번호 추출기 import random def get_random_number(): number = random.randint(1, 45) return number lotto_num = [] # 로또 번호를 저장할 리스트 count = 0 # 현재 뽑은 숫자 개수 while True: if count > 5: break random_number = get_random_number() if random_number not in lotto_num: lotto_num.a...
#정의 def printHello(): print("Hello") # 호출 printHello() # 매개 변수 가 있는 함수 def sum(a, b): print(a + b) sum(7, 7) # 반환값 있는 함수 import random def getRandomNumber(): number = random.randint(1,10) return number print(getRandomNumber()) #매개 변수와 반환 값이 있는 함수 def add(a,b): result = a + b return result ...
# while # : 보통 반복 횟수가 정해지지 않았을 때 사용한다. i = 0 # 초기식 while i < 10: # 조건식 print(i, "번째 다짐, 나는 할 수 있다!") i += 2 # 증감식 # 무한루프 # : 조건식에 True를 넣어서 항상 반복되게 만든 것. while True: x = input("종료하려면 exit를 입력하세요 >>>") if x == "exit": break
#PROBLEMA 1 a=input("Cual es tu nombre: ") print("Hola", a)
#!/usr/bin/env python3.5 def reverse_string(string: str): return "".join([string[-index] for index, element in enumerate(string, 1)]) print(reverse_string("Hello World"))
class Array: def __init__(self,n): self.__n = n self.__arreglo = [] for i in range(0,n,1): self.__arreglo.append(0) def length(self): return self.__n def get_item(self,index): return self.__arreglo[index] def set_item(self,index,value): self...
import pandas as pd import numpy as np pd.set_option('display.max_columns', 30) from utils import standardize_data def data_preprocessing2(df, standardize= False): # specifying which columns contain dummy variables dummies_names = ['gender', 'Partner', 'Dependents', 'PhoneService', 'PaperlessBilling', 'Churn...
import pandas as pd import matplotlib.pyplot as plt pd.set_option('display.max_columns',10) from dataPreprocessing import data_preprocessing from utils import load_data def explicative_structure_table(column_name, df): churn_yes = "Churn_Yes" percentage_population = "Percentage population" average_churn_ra...
list_ofsquares=[] for x in range(1,10): square=x**2 list_ofsquares.append(square) print(list_ofsquares)
#calculator program # + - * / print("Press 1 : For add") print("Press 2 : For substract") print("Press 3 : For multiply") print("Press 4 : For Divide") userInput=int(input("Please enter something :")) firstNumber=int(input("Please enter First Number:")) secondNumber=int(input("Please enter Second Number:")) if userInp...
a = int(input("Please Enter any Number: ")) lastValue=a s=str(a) d=0 i=0 b=0 c=0 e=0 Count = 0 while(a > 0): a = a // 10 Count = Count + 1 while(i<Count): b=s[i] c=int(b) d=c**Count e+=d i=i+1 if(lastValue==e): print("Your number is amstrong number") else: print("Sorry! your number i...
#!/usr/bin/python3 from math import * import random def Fibonacci(un_2, un_1): return un_2+un_1 print('\nFibonacci') print(Fibonacci(0,1)) print(Fibonacci(1,Fibonacci(0,1))) def Fibonacci_liste(n): L=[] for i in range(n): if ((i==0) | (i==1)): L.append(i) else: L.append(Fibonacci(L[len(L)-1],L[len(L)-...
# -*- coding: utf-8 -*- """ Created on Wed Sep 5 09:45:33 2018 @author: Pshypher """ try: print("Entering the try suite") dividend = float(input("Provide a dividend to divide:")) divisor = float(input("Provide a divisor to divide by:")) result = dividend/divisor print("{:2.2f} divided by {:2.2f} ...
# prompt user for a number "num" greater than 2 # repeatedly prompt the user for the number "num" if it is not greater than 2 # while the number "num" is greater than 2 # take the square root of "num" # increment a count variable "times" used to record how many times the # operation has been completed # each ti...
# Simple Interest is p*r*t/100 where p is principal # r is rate and t the time. p = 10000 r = 12.5 t = 5 simple_interest = (p * r * t) / 100 print("The simple interest of ${} for a duration of {} years \ and interest rate equal to {:.1%} is {}".format(p,t,(r/100),simple_interest))
# Laboratory Exercise #1 (Part A) AAA = 8 BBB = 20 CCC = 1 DDD = 11 EEE = 13 FFF = 5 # Give the value displayed by each of the calls to "print" below. A = BBB // AAA print( "\nValue of A: ", A ) # Value of A: 2 B = BBB % AAA print( "\nValue of B: ", B ) ...
A,B,C,D = 0,0,0,0 while A <= 10: A += 2 if A%3 == 0: B += 1 else: C += 1 D += 1 print( "A =", A ) # Line 1 A = 12 print( "B =", B ) # Line 2 B = 2 print( "C =", C ) # Line 3 C = 4 print( "D =", D ) # Line 4 D = 6
# Program written to transfer the elements of a list to another # list whilst rearranging the order in which the elements appear # Unless stated otherwise, variables are assumed to be of type int def transform(list1, list2, r1, r2): """Removes items from list1 in the slice r1:r2, appends them onto list2 i...
# Program designed to read a file and insert carriage-return characters (\n) # and write the contents of the file to a new text file that is composed of # four/five lines of five words import string # input_file = open("testFile.txt", 'r') output_file = open("modTestFile.txt", 'w') WORDS_PER_LINE = 5 word_count = 0 ...
# Progam creates the lowercase English alphabet sequence from two substring # sequence variables 'x' and 'y' and displays the result x = 'acegikmoqsuwy' y = '+bdfhjlnprtvxz' z = '' for index in range(len(x)): z = z + x[index] + y[index+1] for char in z: print(char, end=' ')
# -*- coding: utf-8 -*- """ Created on Thu Aug 23 21:09:42 2018 @author: Pshypher """ class Compound(object): def __init__(self,name:str,formula:str): """Constructor for a chemical Compound.""" self.__name = name self.__formula = formula def __add__(self, param_Compound):...
# -*- coding: utf-8 -*- """ Created on Wed Aug 29 15:14:59 2018 @author: Pshypher """ import copy, math, random def distance(point_a, point_b): """Calculates the distance between two points on a rectangular coordinate.""" x_diff = point_a[0] - point_b[0] y_diff = point_a[1] - point_b[1] return math.s...
# continue to process values until the user enters the value 0 # ignore all negative integers # count the number of odd integers entered # count the number of even integers entered # calculate the sum of odd integers in the series # calculate the sum of even integers in the series # display the sum of odds # display th...
def fibonacci_sequence(length): """Function prints the first N(not less than 1) fibonacci numbers.""" nth_term = 1 parent_nth_term = 1 grandparent_nth_term = 0 while length > 1: nth_term = parent_nth_term + grandparent_nth_term print(parent_nth_term, end=', ') grand...
# Telephone directory has P pages, N lines per page and # C columns per line. The entire telephone directory has a total # of E entries. # Assume that page, line, column numbers and X all start from 1 C_str = input("Enter the number of column on a line: ") X_str = input("What entry contains the name and number of indi...
# -*- coding: utf-8 -*- import time def add_list1(int_list): '''add a list of ints, iteration''' result_sum = 0 for num in int_list: result_sum = result_sum + num return result_sum def add_list2(int_list): '''add a list of ints, use builtin sum''' return sum(int_list) def timer_func(...
# Program displays the index of both o's in the input "Who's on first?" input_str = "Who's on first?" first_o = input_str.find('o') second_o = input_str.find('o', first_o+1) print("1st o: {}\n2nd o: {}".format(first_o, second_o))