text
stringlengths
37
1.41M
def find(*nums): a = len(nums) total = (a+1)*(a+2)/2 summ = sum(nums) result = int(total - summ) return result def solution(*nums): m = max(nums) if m < 1: print("All numbers are negative, so: ", 1) else: if find(*nums) == 0: miss = max(nums) + 1 ...
#!/bin/python3 from datetime import datetime as fff import math import os import random import re import sys # Complete the time_delta function below. def time_delta(t1, t2): format = "%a %d %b %Y %H:%M:%S %z" return int(abs((fff.strptime(t1, format) - fff.strptime(t2, form...
from collections import deque class TestClass(object): def test_one(self): test_sol = solution(6, [["append", "1"], ["append", "2"], ["append", "3"], ["appendleft", "4"], ["pop"], ["popleft"]]) test_ans = deque([1, 2]) assert test_sol == test_ans def test_two(self): test_sol = solution(3, [["appen...
from itertools import permutations string, k = input().split() k = int(k) ans = list(permutations(string, k)) ans.sort() for i in ans: print("".join(i))
s = input() up = [] low = [] num1 = [] num0 = [] for i in s: if i.isdigit(): if int(i) % 2: num1.append(i) else: num0.append(i) elif i.isupper(): up.append(i) else: low.append(i) up.sort() low.sort() num1.sort() num0.sort() print(*low, *up, *num1, *num0, sep = "")
# -*- coding: utf-8 -*- """ Created on Sat Feb 1 15:38:46 2014 @author: MeenoiKung """ def parabola(x): return x**2 + 1. import numpy as np import matplotlib.pyplot as pl from plot_defaults import * import Ay190_Lib_7 as Lib7 opt = 7 N_0 = 5 n = np.arange(opt) n = N_0 * 10**(n) ans = np.zeros(opt) exact = 22/...
# Moving Zeroes 上一题讲的是一维数组的坐标变换 i, j # 本题也是关于一维数组的坐标变换,本题两种解法的代码都要写很熟,是后面同类题目的基础 # 可能解法: # 解法1:枚举法,双指针,嵌套循环,O(n^2),但本题枚举法用python会超出时间限制 class Solution: def maxArea(self, height: List[int]) -> int: ans = 0 # 以下嵌套循环当需要遍历左右边界,且左右边界不可重复时使用,也就是可以实现i, j两个下标对数组的遍历,同时保证i与j不重复;需要背熟!; for i in range(len(h...
# -*- coding: UTF-8 -*- # python提供了两个非常重要的功能来处理python程序在运行中出现的异常和错误。你可以使用该功能来调试python程序。 # 1.异常处理; # 2.断言(Assertions)。 # 一、 try...except... try: fh = open('myException.txt', 'w') fh.write("this is test exception.") except: print "Error: 没有找到文件或读取文件失败" else: print "内容写入成功" fh.close() # 在执行代码前为了测试方...
#Queues: # Enqueue, Dequeue, Empty # Have 2 pointers/indices to track: Write index (Where to write next) and Read Index (Where to read next) #Queue (size: n-1) implemented using array of size (n) # Empty is enqueue and dequeue indices are the same. Buffer of one element so no confusion is Queue is full/empty # Imple...
# search element by element as the algoorithm runs through out the data set def bruteForce(test, searchItem): found = False for i in test: if i == searchItem: found = True break else: found = False return found
# my aim is to store the values of the fibonacci series in a matrix and return the value of the Nth term in the matrix caches = {} # defining Null matrix def fibdynbu(n): caches[1] = 1 caches[2] = 1 # defining the initial values for the Matrix if n > 2: for i in range(3, n+1): caches[...
# coding: utf-8 # Dogs-vs-cats classification with CNNs # # In this script, we'll train a convolutional neural network (CNN, # ConvNet) to classify images of dogs from images of cats using # PyTorch. This script is largely based on the blog post [Building # powerful image classification models using very little # data...
# coding: utf-8 # # Dogs-vs-cats classification with CNNs # # In this script, we'll train a convolutional neural network (CNN, # ConvNet) to classify images of dogs from images of cats using Keras # (version $\ge$ 2 is required). This script is largely based on the # blog post [Building powerful image classification...
# coding: utf-8 # # Dogs-vs-cats classification with CNNs # # In this script, we'll train a convolutional neural network (CNN, # ConvNet) to classify images of dogs from images of cats using # TensorFlow 2 / Keras. This script is largely based on the blog # post [Building powerful image classification models using ve...
import random s = set([1, 2, 3]) x = random.randint(1, 3) print(x) y = int(input()) s1 = set([x, y]) print(*list(s - s1))
import math def merge(arr1, arr2): merged_array = [ ] i = 0 j = 0 while i < len(arr1) and j < len(arr2): if arr1[i] > arr2[j]: merged_array.append(arr2[j]) j += 1 else: merged_array.append(arr1[i]) i += 1 while i < len(arr1): merged_array.append(arr1[i]) i += 1 while j < len(arr2): ...
class OverloadDemo: def sum(self,a,b,c=0): s = a+b+c return s od = OverloadDemo() sum=od.sum(7,8) print("sum is:",sum) sum= od.sum(7.8,9) print("sum is:",sum)
#Multi waves from tkinter import * import time import random def lerp(v0, v1, w): lerp = (1 - w)*v0 + w*v1 #print(lerp, v0, v1) return v0-lerp class Wave(): def __init__(self, wavespeed, waveheight, wavereach, waveat): self.wavespeed = wavespeed self.waveheight = waveheight sel...
import time import random printtime = 0.1 letters = ['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","W","X","Y","Z"...
def is_all_upper(text: str) -> bool: import re if text.lstrip().rstrip() == "" or re.sub("[0-9]", "", text) == '': return False return len(text) == len(re.findall("([0-9A-Z ])", text)) if __name__ == '__main__': print("Example:") print(is_all_upper('ALL UPPER')) # These "asserts" are...
def Binary_Search(my_Array,num_to_search,first,last): # first = 0 # last = len(my_Array) - 1 if (last < first): return False else: middle = (first + last)//2 if(my_Array[middle]< num_to_search): first = middle + 1 last = len(my_Array) - 1 return Binary_Search(...
s = "ABCDEFGHIJKLIMNOQRSTUVWXYZ" w = int(input("Введите шаг: ")) while len(s) >= w: l = s[0:w] print(l) s = s[w:] print(s)
def reverseWords(inputString): l = inputString.split(" ") for i in range(0, len(l)): l[i] = l[i][::-1] reversedWords = " ".join(l) return reversedWords if __name__ == "__main__": inputSrting = input("Введите Вашу строку: ") rW = reverseWords(inputSrting) print(rW)
class Node: def __init__(self, data): self.data = data self.Next = None class Stack: def __init__(self): self.count = 0 self.head = None def push(self, a): b = Node(a) if self.head is None: self.head = b else: b.Next = self.he...
def NumberToPattern(num, k): g_dict = { 0:"A",1:"C",2:"G",3:"T"} #"g_dict[1]={}".format(g_dict[1]) #print('NumberToPattern: number={}'.format(num)) pattern = "" for j in range (k-1,-1,-1): #print('NumberToPattern: j={}'.format(j)) w = int(num / pow(4,j)) num = num - w*pow(4, ...
""" PAYE Calcuator Programmer: SAMUEL PELL Date: 06-01-17 (dd-mm-yy) Basic income tax calculator """ import PAYE_calculator as paye_funcs QUIT_KEY = "Q" HEADER = """ Income Tax Calculator By Samuel Pell -------------------------------------------------------- Plea...
b = input('Enter binary number: ') for x in b: while (int(x) != 0 or int(x) != 1): print ('this is not a binary number') b = input ('Enter binary number: ') bin = [] for x in b: bin.append(x) if bin.count('0') > bin.count('1'): print ('Longest run was zeros with length:', bin.count('0...
a = int(input("Enter the number of pronic numbers you want to create: ")) i=1 while i <= a: m = i*(i+1) print (m, end=' ') i += 1
# Import Dependencies import numpy as np import pandas as pd # Read-in csv files oneStardf = pd.read_csv("oneStars.csv") twoStardf = pd.read_csv("twoStars.csv") threeStardf = pd.read_csv("threeStars.csv") # Data Frame information """oneStardf.info() twoStardf.info() threeStardf.info() """ # Create columns for eac...
''' Design and implement a TwoSum class. It should support the following operations: add and find. add - Add the number to an internal data structure. find - Find if there exists any pair of numbers which sum is equal to the value. Example 1: add(1); add(3); add(5); find(4) -> true find(7) -> false Exampl...
''' Given a list of words and two words word1 and word2, return the shortest distance between these two words in the list. Example: Assume that words = ["practice", "makes", "perfect", "coding", "makes"]. Input: word1 = “coding”, word2 = “practice” Output: 3 Input: word1 = "makes", word2 = "coding" Output: 1...
''' Given an integer array sorted in ascending order, write a function to search target in nums. If target exists, then return its index, otherwise return -1. However, the array size is unknown to you. You may only access the array using an ArrayReader interface, where ArrayReader.get(k) returns the element of the ar...
import PyPDF2 file = open('meetingminutes.pdf', 'rb') # change the filename pdfReader = PyPDF2.PdfFileReader(file) # only add the watermark to the first page firstPage = pdfReader.getPage(0) pdfWatermarkReader = PyPDF2.PdfFileReader(open('watermark.pdf', 'rb')) # change the watermark pdf name if needed firstPage.merg...
a = ["banana", "oranges", "apples"] for elements in a: print(elements) b = [20, 10, 5] total = 0 for e in b: total += e print(total) print(" ") c = list(range(1, 100)) for each in c: print(each) print(" ") total2 = 0 for i in range(1, 8): if i % 2 == 0: print(i) total2 += i print("...
# Project Euler Problem 001 sum = 0 for x in range(1000): if((x%3==0) or (x%5==0)): sum += x print(sum)
#!/usr/bin/env python ## multi_neuron_classifier.py """ The main point of this script is to demonstrate saving the information during the forward propagation of data through a neural network and using that information for backpropagating the loss and for updating the values for the learnable parameters. The script ...
#WomenInTech = [ "Amanda Randles", "Aprille Joy Ericsson", "Cindy Alvarez", "Dorothy Vaughan", "Jess Lee" ] #print (WomenInTech) #print (len(WomenInTech)) #print ("Bob" in WomenInTech) anEx = "Lee!" print(len(anEx)) print("Le" in anEx) print(anEx[2]) print(anEx[2]+ anEx[1]) for letter in anEx: print(letter) prin...
from collections import deque import itertools from datetime import datetime def combat(decks): """Regular combat""" while True: if not decks[0]: return 1 if not decks[1]: return 0 # print(decks) combat_cards = [deck.popleft() for deck in decks1] ...
""" """ from collections import defaultdict adaptor_compat_map = defaultdict(set) if __name__ == "__main__": with open("input.txt") as input: lines = input.readlines() lines = [line.strip() for line in lines] adaptors = [int(line) for line in lines] adaptors.sort() adaptors.insert(0, 0)...
import random balls = {"red": (1, "Watch a movie"), "green": (90, "Productive life"), "blue": (9, "Watch YouTube")} print(f"The dictionary of balls: {balls}") print("") def extract_colors(balls): colors = [] for color in balls: colors.append(color) return colors colors = extract_colors(balls) pri...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sat Apr 11 17:47:21 2020 @author: andrebastos """ import tensorflow as tf import numpy as np from datetime import datetime class Tensorflow_Regression: train_inputs = [] train_labels = [] val_input = [] val_labels = [] std = 0 ...
def write_complain(office): with open(office, 'w') as office_name: complaint = input('What is your complaint? ') office_name.write(str(complaint)) print('Your complaint is accepted.\n') with open( office) as office_name: n = office_name.read() print(n) greeting = input('...
# immutable datatype my_tup=('amey','amet','ganga','proctor','vinayak','sachin') my_tup1=('sachin','sagar') # String concatination print("# Tuples concatination") print(my_tup) print(my_tup+my_tup1) # String repitation print("# Tuples repitation") print(my_tup1*3) # Tuples Slicing print("# Tuples Slicing") print(...
import random lowercase = ["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"] uppercase = [] for letter in lowercase: uppercase.append(letter.upper()) numbers = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"] special_cha...
class Friend: def __init__(self, name, num): self.name = name self.num = num def get_name(self): return self.name def get_phone(self): return self.num def set_phone(self, num): self.num = num def show_info(self): print("name: " + self.name, end = '...
def main(): st = input("input integer: ") if st.isdigit(): print(int(st) ** 2) else: print("It's not integer") main()
def main(): num = 3 if 1 < num and num < 5: print(True) else: print(False) main()
st = [1, 2, 3, 4, 5, 6] st[0], st[-1] = st[-1], st[0] print(st[0], st[-1])
from selenium import webdriver from selenium.webdriver.chrome.options import Options import time url = input("Enter the URL of the Question: ") options = Options() options.add_argument("--window-size=1920x1080") chromedriver_path = './chromedriver' driver = webdriver.Chrome(executable_path=chromedriver_path, options=...
from math import sqrt def mysqrt(a): while True: print(x) y = (x + a/x) / 2 if y == x: break x = y print("a", " ", "mysqrt(a)", " ", "math.sqrt(a)", " ", "diff") print("-", " ", "---------", " ", "------------", " ", "----" ) def test_square_root(): ...
AFC_east = ['New England Patriots', 'Buffalo Bills', 'Miami Dolphins', 'New York Jets'] numbers = [42, 123] empty = [] #print(AFC_east, numbers, empty) AFC_east[3] = 'New York Giants' print(AFC_east) AFC_east[-1] print("Buffalo Bills" in AFC_east) L = [ ['Apple', 'Google', 'Microsoft'], ['Java', 'Python', [...
def print_lyrics(): # after def is the name of the function print("hey jude. Dont make it bad.") ## everything after the function should be indented print("take a sad song and make it better") """print_lyrics() #callig the function we just defined print(type(print_lyrics)) #prints the type of the def""" ...
trans = {'0':'ling', '1':'yi', '2':'er', '3':'san', '4': 'si', '5':'wu', '6':'liu', '7':'qi', '8':'ba', '9':'jiu', '10': 'shi', '100': 'bai'} def speak_Chinese(number): ''' number: an integer, 0<=number<=999 Returns: a string that is the number in Chinese ''' while number < 1000: ...
x=int(input()) for i in range (1,6): c=i*x print(c, end=' ')
a=int(input()) f,b=0,1 while a: print(b,end=" ") f,b=b,f+b a=a-1
x=int(input()) if (x<=10): if(x is 1): print('One') elif(x is 2): print('Two') elif(x is 3): print('Three') elif(x is 4): print('Four') elif(x is 5): print('Five') elif(x is 6): print('Six') elif(x is 7): print('Seven') elif(x is 8): print('Eight') elif(x is 9 ): pr...
x=input() x=x+'a' c=x[::-1] if(x==c): print('yes') else: print('no')
x=input() for i in x: if(int(i)%2!=0): print(i,end=' ')
x=['a','e','i','o','u','A','E','I','O','U'] d=input() b=0 for i in d: if i in x: b=0 if b==0: print('yes') else: print('no')
import requests import sqlite3 import os # "RAPIDAPI_KEY" is stored on Heroku as an environmental variable for security reasons headers = { 'x-rapidapi-key': os.environ["RAPIDAPI_KEY"], 'x-rapidapi-host': "skyscanner-skyscanner-flight-search-v1.p.rapidapi.com" } def makeDatabase(): """Acc...
import tensorflow as tf import numpy as np import pandas as pd # Declare list of features. We only have one numeric feature. There are many # other types of columns that are more complicated and useful. feature_columns = [tf.feature_column.numeric_column("x", shape=[1])] # An estimator is the front end to inv...
#========================= # Trap List #========================= import random waterTrap = {'name':'Water Trap', 'damage':random.randint(1,4), 'description':'As you enter the room you hear a click. The room begins to fill with water, you scramble to find a way out.'} pitTrap = {'name':'Pit Fall Trap', 'damage':ra...
# Original source code found at : https://wiki.python.org/moin/UsingPickle # Save a dictionary into a pickle file. import pickle favorite_color = { "lion": "yellow", "kitty": "red" } pickle.dump( favorite_color, open( "save.p", "wb" ) ) # Load the dictionary back from the pickle file. favorite_color_loaded = pickle...
n = int(input("How many elements: ")) list = [] for i in range(0,n,1): elmnt = int(input()) list.append(elmnt) list.reverse() print(list)
matrix = [ [1,2,3], [4,5,6], [7,8,9] ] for i in range(0,3,1): for j in range(0,3,1): print(matrix[i][j] , end=" ") print("\n")
import numpy as np #declearing arrray a = np.array([1,3,5,9]) b = np.array([[1,3,4,5,7.5],[3,5,1,6,9]]) c = np.array([[1,2,3,4,5,6,7],[8,9,10,11,12,13,14]]) #get dimension # print(a.ndim) # print(b.ndim) #get shape # print(a.shape) # print(b.shape) #get type # print(a.dtype) # print(b.dtype) #get size # print(a.i...
marks = int(input()) if marks >= 33: print("Passed") elif marks>= 80: print("A") else: print("Failed")
from array_reverse import __version__ from array_reverse.array_reverse import reverse_array def test_reverse_odd(): lst = ["apples","bananas","cucumbers"] reverse_array(lst) assert lst == ["cucumbers","bananas","apples"] def test_reverse_even(): lst = ["apples","bananas","cucumbers","dates"] rever...
from codefellows.dsa.binary_tree import BinaryTree as BaseBinaryTree, Node class BinaryTree(BaseBinaryTree): def to_grid(self): def binary_tree_to_grid(root, grid, row=0, column=0): if not root: return # create a new row in the grid when needed. Will be twice as l...
class Node: def __init__(self, value, next_=None): self.value = value self.next = next_ class LinkedList: def __init__(self, values=None): self.head = None if values: # start, stop, step for slicing # O(n) FTW for value in reversed(values): self.insert(value) def __s...
def convert(x, y): x = int(x) y = int(y) return x+y print(convert("6","7"))
def dictTest2(): dict2 = dict() for i in range(1, 21): dict2[i] = i*i return dict2.values() print(dictTest2())
import re s = input("Do you agree?\n") if re.search("yes|y", s, re.IGNORECASE): #it will return true of false re.search("y(es)?") print("Agreed.") if re.search("no|n", s): print(("Not agreed.")) #if re.search("^y(es)?$", s, re.IGNORECASE) #^ It states search the beggining of the string #$ it states search th...
'''This is the module for interacting with tumblr.com. It includes the main class Tumblr''' import re import urllib from util import LoggerFactory from util import peterBrowser class Tumblr: '''Class for interacting with tumblr.com''' logger=LoggerFactory.getLogger('tumblr') #regular expressi...
# -*- coding: utf-8 -*- """ Created on Sat Apr 11 00:02:22 2020 @author: sourav """ """ Introducing CONVNETS: Convoluted Neural Networks """ from keras import layers from keras import models model = models.Sequential() model.add(layers.Conv2D(32, (3, 3), activation='relu', input_shape=(28, 28, 1))) ...
""" Interactive Drawing Interface for taking in line inputs. Allows users to draw on a surface and then save to a file. """ import Tkinter trace = 0 # XXX top left is (0, 0). Do we need to correct the frame? class CanvasEventsDemo(object): """ Interactive Drawing Interface for geting line input """ ...
# Import the os module, for the os.walk function import os import sys arg_count = len(sys.argv) if arg_count > 2: print(""" #usage rename txtName] """) exit # TODO: replace special char with space with open(sys.argv[1]+".txt", "r") as File: names = File.read().sp...
import sqlite3 def create_db(db_name=":memory:"): connection = sqlite3.connect(db_name) connection.execute("DROP TABLE IF EXISTS teams;") connection.execute( """CREATE TABLE teams( id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT NOT NULL );""" ) teams = [("Italy",),...
#!/usr/bin/env python # -*- coding: utf-8 -*- import sys import csv import time import re from papirus import Papirus from papirus import PapirusText screen = Papirus() text = PapirusText() #http://www.tweepy.org/ import tweepy #Get your Twitter API credentials and enter them here import keys consumer_key = keys.co...
#! /usr/bin/env python3.6 from user import User from profile import Profile import string import random def create_user(username, password): #create user ''' Method that creates a user ''' new_user = User(username, password) return new_user def create_profile(account, password): #create profile ''' M...
## Sentiments analysis using Python applied to French political speeches ## Lexicons (positive and negative words) used : Chen, Y., & Skiena, S. (2014). Building Sentiment Lexicons for All Major Languages. In ACL (2) (pp. 383-389). import matplotlib.pyplot as plt import numpy as np class Speech: # name of the speake...
def check_venues(users, venues): good_venues = [] bad_venues = {} for venue in venues: issues = check_venue(users, venue) if issues: bad_venues.update({ venue["name"]: issues }) else: good_venues.append(venue["name"]) retur...
import turtle def lt(t,s): t.lt(s) def polygon(t,l,n): for i in range(n): t.fd(l) lt(t,360/n) bob = turtle.Turtle() print(bob) polygon(bob,100,6) turtle.mainloop()
def filter: res=[] if isinstance(a,list): return a.append(b) else: return [a,b] def multiples_of_two(a,b,m): s = filter(divided_by_m,[x for x in range(a,b) if x % m ==0]) return s print(multiples_of_two(0,10,2))
import numpy as np class Solver: def __init__(self, puzzle: np.ndarray): assert puzzle.shape == (9, 9) self.puzzle = puzzle.copy() def solve(self): if self.is_solvable(): print('Solvable!') self.__solve_helper() return self.puzzle else: ...
import enum import numpy as np import random Winner = enum.Enum("Winner", "black white draw") Player = enum.Enum("Player", "black white") class GameEnv: def __init__(self): self.board = None self.turn = 0 self.done = False self.winner = None # type: Winner self.resigned = F...
a = [1,2,3,4,5,6,7,8] n = list(map(int,input().split())) if a == n: print("ascending") elif a[::-1] == n: print("descending") else: print("mixed")
a,b = input().split() def max(a,b): max = 0 a = a.replace('5','6') b = b.replace('5','6') return int(a) + int(b) def min(a,b): min = 0 a = a.replace('6','5') b = b.replace('6','5') return int(a) + int(b) print(min(a,b),max(a,b))
n = list(input()) for i in range(len(n)): if n[i].islower() == True: n[i] = n[i].upper() elif n[i].isupper() == True: n[i] = n[i].lower() for i in n: print(i,end='')
for i in range(int(input())): arr = [] for j in range(int(input())): a,b = input().split() arr.append([int(a),b]) arr.sort() print(arr[-1][1])
for i in range(int(input())): a = list(input().split()) fl = float(a[0]) del a[0] for j in range(len(a)): if a[j] == "@": fl *= 3 elif a[j] == "#": fl -= 7 elif a[j] == "%": fl += 5 else: pass print("%.2f" % fl)
for i in range(int(input())): s = input() print(s[0].capitalize()+s[1:])
def prime_number(num): if num != 1: # 만약에 입력이 1이아니면 for i in range(2,num): #2부터 num-1,ex)3까지 반복을 돈다 if num % i == 0: #만약에 입력을 i로 나눈 나머지가 0이면 False를 리턴한다. return False else: #만약에 입력이 1이면 return False #False를 리턴 한다. return True #만약에 3개의 if문 하나라도 해당이안되면 True를 리턴한다. ...
li = sorted(list(int(input()) for i in range(28))) for i in range(1,31): if i not in li: print(i)
n = int(input()) li = list(input()) def Lchange(): while "L" in li: ix = li.index("L") li.remove("L") li.insert(ix,"LL") li.remove("L") Lchange() li = "*".join(li) result = li.count("*")+2 if result > n: print(n) else: print(result)
second = int(input()) if second % 10 != 0:print("-1") else: A = second / 300 second %= 300 B = second / 60 second %= 60 C = second / 10 second %= 10 print(int(A),int(B),int(C))
# this program gets a numeric test score from the user and displays the corresponding letter grade # variables theo represent the grade thresholds A_score = 90 B_score = 80 C_score = 70 D_score = 60 # get the test scores from the user score = int(input('Enter your test score: ')) # determine the grade if score >= A_...
# get a number of seconds from the user total_seconds = float(input('Enter a number of seconds: ')) # get the total number of hours hours = total_seconds // 3600 # get the number of remaining minutes minutes = (total_seconds // 60) % 60 # get the remaining number of seconds seconds = total_seconds % 60 # display th...
# this program reads a files contents into a list def main(): infile = open('cities.txt', 'r') # read the contents of the file into a list cities = infile.readlines() # cloe the file infile.close() # print the contents of the list print(cities) # strip the \n from each element ...
# this program has two functions # first we define the first function def main(): print('I have a message for you') message() print('Goodbye') # next we define the message funstion def message(): print('I am Arthur') print('King of the Britons') # call the main function main()