text
stringlengths
37
1.41M
def findtidy(a): string = list(str(a)) reverse = [] for i in range(len(string)-1, -1, -1): reverse.append(string[i]) #print(reverse) for i in range(len(reverse)-1): if reverse[i]<reverse[i+1]: if(i==len(reverse)-2 and reverse[i+1]=='1'): for...
#!/usr/bin/env python3 from itertools import count from math import sqrt def next_range(stream): line = stream.readline() if not line: return None return [int(x) for x in line.split()] def is_palindrome(n): n = str(n) return all(n[i] == n[len(n)-1-i] for i in range(len(n) // 2)) def my...
import sys def generate_triplet(score, is_surprising): result = [score/3, score/3, score/3] if score%3 == 0: if is_surprising: result[0] = result[0] -1 result[2] = result[2] +1 elif score%3 == 1: result[2] = result[2] + 1 else: if is_surprising: result[2] = result[2] + 2 else: res...
def solve(translation_dictionary, sentence): solution = '' for c in sentence: if c in translation_dictionary: solution += translation_dictionary[c] else: print c, "is missing from translation" print solution, sentence return solution code = "ejp mysljyl...
#!/bin/python def get_digit(number, index, digits): left = pow(10, digits - index -1 ) number = number // left number = number % 10 return number def get_previous_number_to_check(number, num_len): if number < 10: return number to_change = None for i in range(num_len -...
import sys import math def print_ans(case_num,solution): print("Case #"+str(case_num)+":"), print_solution(solution) def print_solution(solution): """TO DO""" print solution def input_processor(filename): f=open(filename) data=f.read().split("\n") case_nums=int(data[0]) """Ins...
def ispalindrome(x): #accept str lengthx=len(x) opposite=lengthx-1 index=0 while (opposite>=index): if x[index]!=x[opposite]: return False index+=1 opposite-=1 return True def testrange(minim,maxim): from math import sqrt #need to be ints lelist=[...
import math import sys def is_palindrome(number): return str(number)[::-1] == str(number) def fair_and_square(x): # fair and square number x means palindrome(sqrt(x)) && palindrome(x) fair = is_palindrome(x) square = math.sqrt(x) % 1 == 0.0 and is_palindrome(int(math.sqrt(x))) return fair and square def fa...
import sys import math def flip( cake_list, start, stop, step ): #print( "before flip : " + str(cake_list) + "start = %d, stop = %d, step = %d" % ( start, stop, step ) ) for i in range( start, stop, step ): if cake_list[i] == '-': cake_list[i] = '+' else: cake_list[i] = '-' #print( "after flip ...
''' Created on April 30 2016 @author: elmoatasem ''' int2Str = lambda x:str(x) # map(int2Str,[1,2]) : [1,2] > ['1', '2'] intList2StringList = lambda x: map(str,x) #map(intList2StringList, [[1,3,4],[4,5,4]]) : [[1, 3, 4], [4, 5, 4]] > [['1', '3', '4'], ['4', '5', '4']] strList2IntList = lambda x: map(int,x)#map...
file = open("input.txt","r"); case = 0; for _ in range(int(file.readline().strip())) : case+=1; num = file.readline().strip() #print(sorted(num)); if num == ''.join(sorted(num)) : print("Case #",case,": ",num,sep = ""); continue; while int(num)>0 : num = str(int(num)-1) ...
def is_tidy(number_string): max_digit = 0 for ch in number_string: if(int(ch) < max_digit): return False if(int(ch) >= max_digit): max_digit = int(ch) return True def naive_solver(num): cur_num = num while(not is_tidy(cur_num)): cur_num -= 1 return cur_num def smart_solver(str_num): #saved_n...
#!/usr/bin/env python import sys class Experiment(object): def __init__(self): self.list = [] self.combined = dict() self.opposed = set() def add_combined(self, a, b, c): """a+b->c""" self.combined[(a, b)] = self.combined[(b, a)] = c def add_opposed(...
def solveSmall(r,y,b): n = r+y+b if(r>n//2 or y>n//2 or b>n//2): return "IMPOSSIBLE" if(r==0 or y==0 or b==0): if n%2 == 1: return "IMPOSSIBLE" elif r==0: return "BY"*b elif y==0: return "RB"*r elif b==0: return "...
def main(): t = int(input()) for i in range(1, t + 1): number = int(input()) answer = "" if isTidy(number): answer = number else: answer = makeTidy(number) print("Case #{}: {}".format(i, answer)) def isTidy(input): number = str(input) for i in range(len(number) - 1): if int(number[i]) > int(num...
#!/usr/bin/env python # -*- coding: utf-8 -*- FILE_NAME = 'B-large' IN_FILE = FILE_NAME + '.in' OUT_FILE = FILE_NAME + '.out' f = open(IN_FILE, 'r') src = f.read().split('\n') f.close() case_num = int(src.pop(0)) case_count = 0 result = '' #returns "got better than p" and "was suprising" def judge(score, p, can_be_...
#!/usr/bin/env python from __future__ import print_function from exceptions import Exception from collections import deque def get_input(): from sys import stdin input = stdin.readlines() return input[0], deque(input[1:]) def prepare_case(data): data = deque(data.split()) recipes = {} recipes_...
f = open("C-small-attempt3.in","r") fo = open("op.txt","w") class check_for_val: def __init__(self,val): self.last_res = -1 self.a = -1 self. b = -1 self.val = val self.total = '' def push(self,char): self.total += char if char == self.val and self.last_res == -1 and self.a == -1 and self.b == -1 : ...
class Problem(object): def __init__(self): self.numGoals = None self.numAchievedGoals = 0 self.robots = {"O": Robot(), "B": Robot()} Robot.setProblem(self) def loadProblem(self, line): split = line.split(" ") numGoals = int(split[0]) a...
#!/usr/bin/env python # vim: set fileencoding=utf-8 : """Introduction Magicka™ is an action-adventure game developed by Arrowhead Game Studios. In Magicka you play a wizard, invoking and combining elements to create Magicks. This problem has a similar idea, but it does not assume that you have played Magicka. Note: ...
n_problems = input() for i in xrange(n_problems): n_engines = input() engines = set() for j in xrange(n_engines): engines.add(raw_input()) n_queries = input() pool = engines.copy() switches = 0 for j in xrange(n_queries): engine = raw_input() pool.discard(engine) ...
from Queue import PriorityQueue def is_goal(state): seconds, cookies, rate, C, F, X = state return cookies == X def successors(state): ## two successors: ## 1. buy one farm and return new [new_seconds, cookies=0, rate+F, ...] ## 2. buy no farms but go for X cookies and return [new_seconds, cooki...
#Fair and Square import sys import pdb def is_palindrome(x): x = str(x) n = len(x) for i in xrange(n / 2): if x[i] != x[n - i - 1]: return False return True def make_palindrome1(x): x = list(str(x)) y = x[:] y.reverse() x += y[1:] return int("".join(x)) def mak...
import sys import math def main(): total = int(sys.stdin.readline()) for i in range(total): line = sys.stdin.readline() length, step = map(lambda x: int(x), line.rstrip().split(' ')) result = find_space(length, step) print ('Case #{}: {} {}'.format(i + 1, result[0], result[1])) ...
import os class QuestionC(object): def __init__(self): self.income = 0 self.case = 1 def start(self, filename): with open(filename, "a") as o: for i in range(self.R): self.board() o.write("Case #%d: %d\n" % (self.case, self.income)) ...
#!/usr/bin/python import sys import math def factorial( n ): if n == 0: return 1 else: return n*factorial(n-1) def nchoosek( n, k ): #return factorial(n)/(factorial(k)*factorial(n-k)) answer = 1 for i in range(1,k+1): answer *= (n - (k - i)) answer /= i return...
import sys def max_not_surprising(t): max_score = t / 3 if t > 0 and t % 3 > 0: max_score += 1 return min(max_score, 10) def max_surprising(t): max_score = t / 3 if t > 0: if t % 3 == 2: max_score += 2 else: max_score += 1 ...
#!/usr/bin/env python def xsum(list): result = 0 for i in list: result = result^i return result if __name__ == '__main__': f = open('input') a = int( f.readline() ) for i in range(a): f.readline() list = map(int,f.readline().split()) if xsum(list) != 0: ...
#!/usr/bin/env python # -*- coding: utf-8 -*- import sys # Single def read_word(f): return f.readline().strip() def read_int(f, b = 10): return int(read_word(f), b) def read_float(f): return float(read_word(f)) # Multiple def read_words(f): return read_word(f).split(' ') def read_ints(f, b = 1...
test_size = int(input()) for test_case in range(test_size): number = list(str(input())) for i in range(1, len(number)): if number[i - 1] > number[i]: for j in range(i, len(number)): number[j] = '9' for j in reversed(range(i)): ...
#!/usr/bin/env python3.1 baseElements = ('Q', 'W', 'E', 'R', 'A', 'S', 'D', 'F') def isCombination(first, second, combinations): """ first -- first element to see if is a combination second -- second element to see if is a combination """ if first in baseElements: if second ...
#!/usr/bin/env python # -*- coding: utf-8 -*- class Button: def __init__(self, step_num, color, pos): self.color = color self.pos = int(pos) self.step_num = step_num def __str__(self): return "%s: %s: %s" % (self.step_num, self.color, self.pos) class Hallway: def __init__(self, str_line): ...
nbTests = int(input()) def trouverMax(nombre): for i in range(len(nombre)-1, 0, -1): if i == 1: if nombre[i] < nombre[i-1]: nombre[0] = str(int(nombre[0])-1) for j in range(len(nombre)-1): nombre[j+1] = "9" else: if nombre[i] < nombre[i-1]: nombre[i] = "9" nombre[i-1] = str(int(nombre[...
#!/usr/bin/python import math import sys #This is my first python program #it's ugly, I know def pal(num): original=num revered=0 while original >0 : revered=revered*10 + original % 10 original=original/10 return revered == num def check_far_sqaure(a,b): count=0 a_lower=int(math.sqrt(a))-1 b_lower=int(m...
from __future__ import division def function(current_speed,C,F,X): op1=(C/current_speed)+(X/(current_speed+F)) op2=X/current_speed #print op1,op2 return op2 > op1 def current_speed(F,i): return 2+F*i def main(): a=open("B-large (1).in","r") b=open("answerrrr.out","w") ...
# -*- coding: utf-8 -*- """ Created on Sat Jan 2 10:18:47 2021 @author: nrtc """ import math #1 ''' def f1(x,y): return math.sin(x+y) - math.exp(x-y) def f2(x,y): return math.cos(x+y) - (x**2)*(y**2) def df1x(x,y): return math.cos(x+y) - math.exp(x-y) def df1y(x,y): return math.cos(x+y) + math.ex...
#n=int(input("enter a number:")) f=open("result1.txt","a") def tab(n): f.write("table \n") for i in range(1, 11): f.write(str(n)) f.write("x") f.write(str(i)) f.write("=") f.write(str(n*i)) f.write("\n") f.close()
#!/usr/bin/env python3 #James Watson #Project 0 #2/19/2019 #Imports needed functions and scripts import numbers from getpass import getpass import sys sys.path.append('io') from InputOutput import * sys.path.append('error') from error import * #Creating a logger import logging LOG_FORMAT = '%(name)s - %(levelname)s...
#分支语句 a = 10 b = 5 if a > b : print ("a>b") print("hello") print("world") if a == 10 : print("a ==10") elif a == b : print("a==b") else: print("a<b")
__author__ = 'lyle' def median(alist): alist = sorted(alist) count_of_list = len(alist) midIndex= 0 if count_of_list ==1: return alist[0] if count_of_list %2==0: midIndex = (int)(count_of_list/2) return (alist[midIndex]+alist[midIndex-1])/(2.0) else: midIndex = (...
def BinarySearch(arr,x): start=0 end=len(arr)-1 mid=0 while start<=end: mid=(start+end)//2 if arr[mid]==x: return mid elif arr[mid]>x: end=mid-1 else: start=mid+1 return -1 print("Enter the list :") arr=list(map(int,input().split(...
''' You are given two linked-lists representing two non-negative integers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list. Example: Input: (2 -> 4 -> 3) + (5 -> 6 -> 4) Output: 7 -> 0 -> 8 Explanation: 342 + 465 = 807. ''' # De...
""" Ejercicio 1.6. Escribir funciones que resuelvan los siguientes problemas: a) Dados dos numeros, imprimir la suma, resta, division y multiplicacion de ambos. b) Dado un numero entero n, imprimir su tabla de multiplicar. """ #b def imprime_tabla_multiplicar(numero): print '*****************************' pr...
""" Defining activation functions (af_) =========================== The activation function of a node defines the output of that node given an input or set of inputs. The activation function is usually an abstraction representing the rate of action potential firing in the cell. In its simplest form, this function is bi...
# ! python3 # score.py """ 类方法、静态方法、实例方法 综合练习 需求: 设计一个 Game 类 属性: 定义一个 类属性 top_score 记录游戏的 历史最高分 定义一个 实例属性 player_name 记录 当前游戏的玩家姓名 方法: 静态方法 show_help 显示游戏帮助信息 类方法 show_top_score 显示历史最高分 实例方法 start_game 开始当前玩家的游戏 主程序步骤 1) 查看帮助信息 2) 查看历史最高分 3) 创建游戏对象,开始游戏 """ class Game: top_score = 0 d...
from turtle import Turtle with open('data_score.txt') as file: HIGH_SCORE = file.read() file.close() ALIGNMENT = 'center' FONT = ('Courier', 20, 'normal') class Score(Turtle): def __init__(self): super().__init__() self.score = 0 self.high_score = int(HIGH_SCORE) self.color(...
import artes import palavras from random import choice vida = 6 mostrar = [] erro = '' def escolhe_nivel_palavra(): print(''' Escolha um nível: [ 1 ] - Fácil [ 2 ] - Normal [ 3 ] - Difícil''') while True: try: opcao = int(input('Opç...
from turtle import Turtle STARTING_POSITION = [(0, 0), (-10, 0), (-20, 0)] MOVE_DISTANCE = 10 class Snake: def __init__(self): self.snake = [] self.create_snake() self.snake_head = self.snake[0] # Added function so that it is possible to add a continuous play mode of the game. #...
#!/usr/bin/env python3 import sys assert sys.version_info >= (3,7), "This script requires at least Python 3.7" print('Greetings!') color = input("What is my favorite color? ") if (color.lower() == 'red'): print('Correct!') else: print('Sorry, try again.') #line 9 should change "color" to all lowercase lett...
from tree import Tree from node import Node def test_is_bst(): head = Node(10, Node(6, Node(4, Node(3), Node(5)), Node(7)), Node(15, Node(13, Node(12), Node(14)), Node(16))) t = Tree(head) #print(t.inorder(head)) print(t.is_bst(head)) test_is_bst()
from math import sqrt def noCommonPrimeFactor(i, N): NPrimeFactors = primeFactors(N) #This doesn't need to be recalculated every time... iPrimeFactors = primeFactors(i) return len(list(set(NPrimeFactors).intersection(iPrimeFactors))) == 0 def primeFactors(n): primeFactors = [] # Print the number of two's that di...
print "To find : " to_find = input() print "How many elements are in the list?" n = input() print "List : " List = [] for i in range (0,n): x = input() List.append(int(x)) begin = 0 end = len(List)-1 mid = int((begin+end)/2) found = 1 while List[mid] != to_find: if List[mid] < to_find: begin = ...
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Advent of Code 2020 Day 23, Part 1 """ def play_game(cups): max_cup, min_cup = max(cups), min(cups) picked_cups = cups[1:4] # print(picked_cups) cups = [cups[0]] + cups[4:] destination = cups[0] - 1 while True: if destination in picke...
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Advent of Code 2020 Day 6, Part 2 """ import string def main(): with open('in.txt') as f: lines = f.read().split('\n\n') letters = string.ascii_lowercase total = 0 questions = set(list(letters)) for group in lines: for line in ...
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Advent of Code 2020 Day 13, Part 2 """ def main(): with open('in.txt') as f: lines = f.readlines() arrival = int(lines[0].strip()) bus_ids = [] for i, n in enumerate(lines[1].strip().split(',')): if n == 'x': continue ...
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Advent of Code 2020 Day 24, Part 1 """ def print_floor(floor): floor = [' '.join(map(str, f)) for f in floor] floor = '\n'.join(floor) print(floor) def parse(line): movement = [] i = 0 while i < len(line): if line[i] in 'ns': ...
x = int(input("Enter the value of x")) n = int(input("Enter the range till which you want the values to be print")) sum = 0 for i in range(1, n+1): val = x ** (-i) sum = sum + val print("The value for the given sigma operation is", sum)
main = False if(__name__ == '__main__'): main = True def ascending(array): for i in range(1, len(array)): hasMoved, notPlaced = False, True key = array[i] for j in range(i-1, -1, -1): #print('i ' + str(i)) if(key < array[j]): array[j+1] = array[j] ...
""" Each ListNode holds a reference to its previous node as well as its next node in the List. """ class ListNode: def __init__(self, value, prev=None, next=None): self.prev = prev self.value = value self.next = next def delete(self): if self.prev: self.prev.next =...
#!/usr/bin/env python # -*- coding: utf-8 -*- from unittest import TestCase, expectedFailure, main from metafunction import scanr, scanl, scanr1, scanl1, cons from operator import add, pow class TestScanl(TestCase): def scan(self, *args): "Given some arguments, return a list from the scanl iterator." ...
#!/usr/bin/env python from hwtools import * print "Section 4: For Loops" print "-----------------------------" nums = input_nums() # 1. What is the sum of all the numbers in nums? a=sum(nums) print "1.",a # 2. Print every even number in nums print "2. even numbers" for i in range(0,len(nums)): if nums[i]%2 == 0...
#!/usr/bin/env python from random import randint s = 1 input_number = int(raw_input()) number_list = [ ] #adds random integers to list so that list length equals input number and includes input number for _ in range(input_number): number_list.append(randint(0,20)) print number_list while s: s = 0 for i ...
#coding=utf8 class Person(object): country = 'cn' def __getattr__(self, name): return object.__getattribute__(self, name) def show(self): print 'hello' return self.country p = Person() attr = getattr(p, 'show') if callable(attr): print attr() else: print attr attr = get...
def main(): ## my_string= "One two three four" ## #print(my_string) ## ## word_list = my_string.split() ## ## print(word_list) ## date_string = "03/27/2018" ## ## date_list = date_string.split('/') ## print(date_list) ## print("Month:", date_list[0]) ## print("Day:", date_...
import sqlite3 import csv class csvrd(object): def csvFile(self): self.readFile('bank_of_india.csv') def readFile(self, filename): conn = sqlite3.connect('Bank.db') cur = conn.cursor() cur.execute("""CREATE TABLE IF NOT EXISTS Bank(BANK varchar,IFSC varchar,MICR varchar,BRANC...
#!/usr/env/bin python3 import collections TeamMember = collections.namedtuple("TeamMember", "ID FamilyName FirstName Gender") PPT = [] PPT.append(TeamMember(1, "Taylor", "Joe", "Male")) PPT.append(TeamMember(2, "Hesford", "Catherine", "Female")) PPT.append(TeamMember(3, "Warburton", ...
importe = int(input("ingrese el valor de la compra: ")) mes = input("ingrese el mes: ") totalDes = importe*0.85 if (mes == "octubre") : print("El valor del importe con descuento es de: $", totalDes) else : print("El valor del importe con descuento es de: $" , importe)
n1 = int(input("ingrese el primer número: ")) n2 = int(input("ingrese el segundo número: ")) n3 = int(input("ingrese el tercer número: ")) multiplicacion = n1*n2*n3 suma = n1+n2+n3 if n1<0 : print("El resultado de la multiplicación es: " , multiplicacion) else : print("El de la suma es: " , suma)
""" Creates inverted index file with a dictionary of stemmed words with their exact location in all the documents Creates a file with a dictionary named processeddict with title, author and other parts separated under each document Creates a file with dictionary named uncategorized_wordlist with list of words under eac...
user_info = {'first_name': '', 'last_name': ''} first_name = input('Enter your name: ') user_info['first_name'] = first_name last_name = input('Enter your last name: ') user_info['last_name'] = last_name print(user_info.values())
import os import sys def print_directory_contents(path): """ This function takes the name of a directory and prints out the paths files within that directory as well as any files contained in contained directories. This function is similar to os.walk. I've built it just for learning purposes. """...
#!/usr/bin/python # -*- coding: utf-8 -*- ''' A dictionary-like object with SQLite backend ============================================ Python dictionaries are very efficient objects for fast data access. But when data is too large to fit in memory, you want to keep data on disk but available for fast random access. ...
# class Dog: # def __init__(self, name, age): # self.name = name # self.age = age # # def bark(self): # print(f"{self.name} is barking") # # def age(self): # print(f"{self.name} age is {self.age}") # # # dog1 = Dog('German Shepherd', 4) # print(f'{dog1.age}') # dog1.bark() #...
"""Mad Libs""" print "Mad Libs has started..." name = raw_input("Enter the name of your character...") adj1 = raw_input("Enter one adjetive: ") adj2 = raw_input("Enter another one: ") adj3 = raw_input("Enter just one more: ") verb1 = raw_input("Now we need verbs, give me the first one: ") verb2 = raw_input("A second...
''' Created on Jan 11, 2013 @author: Shunping Huang These functions were copied from Shunping Huang's Lapels Just used for argparse to check that a file exists and/or is read/writable ''' import os import argparse as ap def readableFile(fileName): if os.path.isfile(fileName) and os.access(fileName, os.R_OK): ...
"""Packet definition and properties.""" class Packet(object): """Packet and it's properties are given here.""" def __init__(self, node_type, from_node_id, from_node, message_size, message, destination="sink"): # Defining a packet """ Packet type: To differentiate betw...
# https://app.codility.com/programmers/lessons/2-arrays/odd_occurrences_in_array/ # Detected time complexity: O(N) or O(N*log(N)) def solution(A): num = 0 for i in A: num ^= i return num
from Pro131 import Gravity import pandas as pd import matplotlib.pyplot as plt df = pd.read_csv("project_131.csv") radius = df["Radius"].tolist() mass = df["Mass"].tolist() gravity = df["Gravity"].tolist() mass.sort() radius.sort() gravity.sort() plt.plot(radius,mass) plt.xlabel("RADIUS") plt.ylabel(...
import tkinter as tk from tkinter import * import sqlite3 root = tk.Tk() connection = sqlite3.connect('management.db') TABLE_NAME = "management_table" BILL_ID = "Bill_id" FRIES = "Fries" NOODLES = "Noodles" DRINKS = "Drinks" PIZZA = "Pizza" connection.execute(" CREATE TABLE IF NOT...
import sqlite3 ''' Script to create the database "college_database" and its associated tables: "students", "student_rep" and "class_enrolments" then insert records into those tables''' print("="*100) print("Start of script") print("="*100) # Connect to the database connection = sqlite3.connect("college_data...
import sqlite3 # Connect to the database connection = sqlite3.connect("college_database.db") # Create a cursor cursor = connection.cursor() # Drop the table cursor.execute("DELETE FROM students WHERE student_number = 67832") # Commit connection.commit()
#!/usr/bin/env python # -*- coding: utf-8 -*- import numpy as np def img_rgb_to_gs(img: np.ndarray) -> np.ndarray: """ Converte uma imagem RGB para GrayScale :param img: Imagem normalizada aberta pelo OpenCV e com três canais :return: Imagem normalizada com apenas um canal """ w, h, c = img.s...
# Store Simple Message message = "You're a shitty friend" print (message) tom = "Thomas" print ("Hello, " + tom + "! You're gr8" ) first_name = "anna" last_name = "pawl" full_name = first_name.title() + " " + last_name.title() print("Hello, " + full_name + "!") car = "MazDa" model = "miata" print ("I own a " + car.t...
# LISTS '''Lists are awesome! - Lets you store info in one place - A collection of items in a particular order - You can put anything in a list - Square brackets [ ] indicate a list - List items seperated by commas''' bicycles = ['cannondale', 'trek', 'redline'] print (bicycles) fruits = ['cherry', 'ba...
# Sort the names of some friends. # Print each name by accessing each element one at a time my_friends = ['Rebi','Sarah','Nicky','Grace'] print(my_friends[0]) print(my_friends[1]) print(my_friends[2]) print(my_friends[3]) yellow_stuff = [] yellow_stuff.append('banana') yellow_stuff.append('daisy') yellow_stuff.append(...
# Only the Words # gives a list of all the words of a string without punctuations at the end of the word # @param s string provided # @return a list of the words in the string def words_of_string(s): punctuations = [':', ',', '.', ';', '?', '!', '-', "'"] # split the words from the string words = s.split()...
# Season from Month and Day month = input('enter a month: ') day = int(input('enter a day: ')) season = '' if month == 'jan' or month == 'feb' or month == 'dec' and day >= 21 or month == 'mar' and day < 20: season = 'winter' elif month == 'apr' or month == 'may' or month == 'mar' and day >= 20 or month ==...
# Celsius to Fahrenheit and Kelvin degrees_celsius = float(input('enter the degrees celsius: ')) degrees_fahrenheit = degrees_celsius*9/5 + 32 degrees_kelvin = degrees_celsius + 273.15 print(degrees_fahrenheit, 'degrees fahrenheit') print(degrees_kelvin, 'degrees kelvin')
# Operator Precedence # this function will give the precedence of the operators # @param operator the operator to be checked # @return the precedence of the operator, if no operator found return -1 def precedence(operator): if operator == '+' or operator == '-': return 1 elif operator == '*' or operato...
# Word by Word Palindromes from ex117 import words_of_string # determine is a string is a word by word palindrome # @param t is the string to execute # @return True is the string is a word by word palindrome, False otherwise def is_word_palindrome(t): # create a list of words without punctuation word_list = ...
# BirthDate to Astrological Sign day = int(input('enter your day of birthday: ')) month = input('enter your month of birthday: ') sign = '' if month == 'dec' and day >= 22 or month == 'jan' and day <= 19: sign = 'capricorn' elif month == 'jan' and day >= 20 or month == 'feb' and day <= 18: sign = 'aq...
# Distance Between Two Points on Earth import math t1 = float(input('enter latitude of the first point: ')) g1 = float(input('enter longitude of the first point: ')) t2 = float(input('enter latitude of the second point: ')) g2 = float(input('enter longitude of the second point: ')) distance = 6371.01 * math...
# Area of a room width = float(input('type the width of the room in meters\n')) length = float(input('type the length of the room in meters\n')) area = width * length print('the area of the room is %.2f squared meters' % area)
# Faces onMoney # George Washington $1 # Thomas Jefferson $2 # Abraham Lincoln $5 # Alexander Hamilton $10 # Andrew Jackson $20 # Ulysses S. Grant $50 # Benjamin Franklin $100 banknote = int(input('enter a banknote size: ')) face = '' if banknote == 1: face = 'George Washington' elif banknote == 2...
# Vowel or Consonant letter = input('enter a letter of the alphabet: ') if letter == 'a' or letter == 'e' or letter == 'i' or letter == 'o' or letter == 'u': print(letter, 'is a vowel') elif letter == 'y': print(letter, 'can sometimes be a vowel and sometimes be a consonant') else: print(letter, ...
# List of Proper Divisors # provides a list of the proper divisors of an integer # @param n the number you want to find the divisors # @return a list of the proper divisor def divisor(n): div = [] for d in range(1, n): if n % d == 0: div.append(d) return div # test with input from use...
# Area of a Regular Polygon import math n = int(input('enter the number of sides of the regular polygon: ')) s = float(input('enter the length of the side of the regular polygon: ')) a = (n*s**2)/(4*math.tan(math.pi/n)) print('the area of the regular polygon is %.2f' % a)
# Is a List already in Sorted Order? # determine if a list is sorted either ascending or descending # @param t is the list to check # @return True if the list is sorted, False otherwise def is_sorted(t): if t == sorted(t) or t == sorted(t, reverse=True): return True return False # test is_sorted() wi...
# Decimal to Binary decimal = int(input('enter a decimal (base 10) number: ')) binary = '' while decimal > 0: binary = str(decimal % 2) + binary decimal = decimal // 2 print('the equivalent binary number is', binary)
# Capitalize It # Capitalize the appropriate characters in a string # @param string the string that needs capitalization # @return a new string with the capitalization improved def capitalize(string): new_string = '' for index in range(len(string)): # capitalize the first letter if index == 0: ...