text
stringlengths
37
1.41M
def triplet(m, n): m2 = m ** 2 n2 = n ** 2 return (m2 - n2, 2 * m * n, m2 + n2) for n in xrange(1, 10): for m in xrange(n+1, 10): a = triplet(m, n) print a, sum(a)
def factorial(n): if n == '0' or n == '1': return 1 elif n == '2': return 2 elif n == '3': return 6 elif n == '4': return 24 elif n == '5': return 120 elif n == '6': return 720 elif n == '7': return 5040 elif n == '8': return 40320 elif n == '9': return 362880 else: raise...
from itertools import count, permutations from math import ceil def is_cube(n): v = ceil(pow(n, (1/3.))) return (v ** 3) == n def convert_to_int(n): y = 0 for x in xrange(len(n)): y = (y * 10) + (ord(n[x]) - 48) return y def check_cube(number, limit): count = 0 repeated = set() ...
def print_johnson(g, result): if not result: return distance, path = result for u in g.vertices: for v in g.vertices: if path[u][v]: print('Droga z {} do {} (odległość: \ {}): '.format(u, v, distance[u][v]), end=''...
def find_max_min(items): if min(items)== max(items): return [len(items)] return [min(items), max(items)] #print minmax([4,4,4,4])
''' Channel coding module for transmitter and receiver ''' import numpy import hamming_db # Matrices for Hamming codes ''' Transmitter side --------------------------------------------------- ''' def get_frame(databits, cc_len): ''' Perform channel coding to <databits> with Hamming code of n=<cc_len> A...
# 해당 파일은 앙상블학습의 gradient boost 알고리즘을 적용한 학습모델을 구축하여 성능 확인을 수행 # Package Load import pandas as pd import numpy as np from sklearn.model_selection import train_test_split from sklearn.ensemble import GradientBoostingRegressor ########################################### MakingLT ##########################################...
import phonenumbers from phonenumbers import carrier # Built in function for country name from phonenumbers import geocoder def service_provider_details(number): # Provide service provider details try: service_number = phonenumbers.parse(number,"RO") print("Service Provider : ",end="...
''' Prompt: Write a program that asks the user how many Fibonnaci numbers to generate and then generates them. Take this opportunity to think about how you can use functions. Make sure to ask the user to enter the number of numbers in the sequence to generate. ''' from sys import exit print("This program is generates f...
try: x = int(input('Digite um numero: ')) except: print('Deu erro, insira apenas numeros') x = 0 finally: print('O valor digitado é: ', x)
def quick_sort(array, low, high): if low < high: instance = get_instance(array, low, high) quick_sort(array, low, instance - 1) quick_sort(array, instance + 1, high) def get_instance(array, low, high): while low < high: temp = array[low] while low < high and temp <= arr...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sat May 2 16:33:26 2020 @author: zhangyun """ import numpy as np import pandas as pd import matplotlib.pyplot as plt path = 'ex1data1.txt' data = pd.read_csv(path, header=None, names=['Population', 'Profit']) data.plot(kind='scatter', x='Population', y=...
list1 = [1, 2, 3, 4, 1, 2, 10] list1 = set(list1) print(list1) set1 = {1, 2, 3, 4, 4, 5, 5, 6} print(set1) print(list1.union(set1)) print(list1 & set1) print(list1 | set1) print(list1 - set1) print(set1 - list1) set1.add(7) print(set1) set1.update([10, 11, 12]) set1.remove(3) set1.pop() print(set1)
file = "adventdata4.txt" fh = open(file, 'r') data = fh.readlines() # import re # import string # def freqTable(string): # myTable = {} # for char in string: # if char in myTable: # myTable[char] += 1 # else: # myTable[char] = 1 # return myTable # def makeCode(roomName): # myTable = freqTable(roomName...
def binToArray(num): num = bin(num)[2:].zfill(6) return (num) for i in range(0, 41): print(binToArray(i))
''' Given array, put all None entries to the end, preserving the order of other entries example: a = [3, 2, 6, None, None, 5, None] -> [3, 2, 6, 5, None, None, None] ''' import tester a = [None, 3, 2, 6, None, None, 5, None] def defrag_1(a): # in-place, but O(nlogn) a.sort(key=lambda x: 0 if x != None else ...
# Using Python to solve the questions. # Question 3 from string import ascii_lowercase from string import ascii_uppercase def encryptMessage(msg): alphabet_lower = ascii_lowercase alphabet_lower_reverse = alphabet_lower[::-1] alphabet_upper = ascii_uppercase alphabet_upper_reverse = alphabet_upper[::...
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 5/30/2020 10:24 PM # @Author : Tian Z # @Site : # @File : 10-11_12.py # @Software: PyCharm # @Version: import json filename = "favorite_number.json" try: with open(filename) as f_obj: favorite_num = json.load(f_obj) except FileNotFoundError: wit...
place = ["Guizhou", "Yunnan", "Beijing"] print(place) sorted(place) print(place) sorted(place, reverse=True) place.reverse() print(place) place.reverse() print(place) place.sort() print(place) place.sort(reverse=True) print(place) print(len(place))
def list_compare(a, b): newA = list(a) newB = list(b) lastA = [] lastB = [] c = [] while newA != []: for n in newA: popA = newA.pop() if popA not in lastA: lastA.append(popA) while newB != []: for n in newB: popB = newB.pop(...
food_list = ("tofu", "chicken", "beef", "lamb", "pork") for food in food_list: print(food.title())
import random import game class GuessNumberGame(game.Game): # subclass of Game ''' Guess My Number Game -- A Game in which the player provides a number and the computer guess it. ''' def __init__(self, attempts): super(GuessNumberGame, self).__init__(attempts) self.greeting = "You,...
trigger = True while trigger: print("Enter 'q' to quit.") name = input("Please enter your name: ") if name != "q": print("Hello, {}".format(name.title())) with open("guest_book.txt", "a") as guest_book: guest_book.write(name + "\n") else: print("Input terminated!") ...
file_name = "learning_python.txt" with open(file_name) as file_object: contents = file_object.read() print(contents.strip()) print("####################") with open(file_name) as file_object: for line in file_object: print(line.strip()) print("####################") with open(file_name) a...
# a) d = {"Tom": 500, "Stuart": 1000, "Bob": 55, "Dave": 21274} print(len(d)) print(d.keys()) print(d.values()) # b) del d["Bob"] d["Phil"] = 55 print(d) # c) def detect(a): if a in d: print("Yes") else: print("Not {}".format(a)) detect("Dave") detect("Peter") detect(500) # d for key, value...
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2020/2/20 12:25 # @Author : Tian ZHANG # @Site : # @File : checkbutton.py # @Software: PyCharm # @Version: from tkinter import * time1 = 0 time2 = 0 def checkbox1(): global c1, time1 if time1 % 2 == 0: time1 += 1 l['text'] = 'checkbox1...
import pandas as pd import numpy as np import csv df = pd.read_csv("Marks.csv") with open("Marks.csv") as f: reader = csv.reader(f) data = list(reader) data.pop (0) days = [] marks = [] for i in range(len(data)): days.append(float(data[i][2])) marks.append(float(data[i][1])) cor...
#!/usr/bin/python """ Utility Script to calculate the wavenumber for a given period in picoseconds """ def main(): T = float(input('\nPeriod in picoseconds: ')) f = 1 / T k = f/1E-12*(8.0655E+03/2.41796E+14) print '\nFor a period of '+str(T)+' ps the wavenumber is:' print 'k = '+str(k)+' cm^-1\...
sentence = "House deemed an inappropriate manner for an event in the Oval Office." letter = str (input()) print (sentence.count(letter))
a = int (input()) b = int (input()) c = int (input()) d = int (input()) if a == c or b == d: print('YES') else: if abs (a - c) == abs (b - d): print('YES') else: print ('NO')
n=int(input('Enter number:')) for y in range(n): print("*")
import math #Repaper z = input("Enter the word: " ) #z = ("Repaper") z = z.lower() y = len(z)/2 k = int (math.ceil(y)) l = int (math.floor(y)) a = z[:k] b = z[l:] h = b[::-1] if a==h: print ("Palyndrom") else: print ("Not Palyndrom")
class Node: def __init__(self, value): self.value = value self.left = None self.right = None def insert(self, value): if value: if value < self.value: if self.left is None: self.left = Node(value) else: ...
print("Pomidor 2.5 Ziemniaki 4.5 Ogorki 5.5 Cebula 2.33") produkty = { "Pomidor" : 2.5, "Ziemniaki" : 4.5, "Ogorki" : 5.5, "Cebula" : 2.33, } magazyn = { "Pomidor" : 40, "Ziemniaki" : 50, "Ogorki" : 90, "Cebula" : 22, } print("Nasz zieleniak oferuje: ") for p in produkty: prin...
# Another solution to strong_password_detection.py task import re def strong_password_detection(password): if not 20>=len(password)>=8: return None password_regex_lowercase = re.search(r"[a-z]+", password) password_regex_uppercase = re.search(r"[A-Z]+", password) password_regex_number = re.s...
''' Write a program that, given the URL of a web page, will attempt to download every linked page on the page. The program should flag any pages that have a 404 “Not Found” status code and print them out as broken links. ''' import requests, bs4, os def verify_links(url, cwd): """ Processes all links for giv...
#! python3 # random_quiz_generator_Example_Task.py - Creates quizzes with questions and answers in random order, along with the answer key. import os, random from random_quiz_csv_data_reader import data_reader from random_quiz_csv_data_writer import data_writer # writing-reading csv data is done for practicing purpos...
''' Write a program that goes to a photo-sharing site like Flickr or Imgur, searches for a category of photos, and then downloads all the resulting images. You could write a program that works with any photo site that has a search feature. ''' import os, requests, bs4, urllib.request, re def download_images(url, keyw...
#! python3 # download_xkcd_Example_Task.py - downloads comic images from the most recent to the first one import requests, bs4, os, urllib.request def download_img(url, cwd): """ Downloads image from the current url page and all previous page images up to the last one.\n :param url: :param cwd: absol...
''' Create a program blankRowInserter.py that takes two integers and a filename string as command line arguments. Let’s call the first integer N and the second integer M. Starting at row N, the program should insert M blank rows into the spreadsheet. Example of the program: py blank_row_inserter.py 3 2 myProduce.xlsx '...
# STACK:: # stаck mеаns аrrаnging оbjеcts оn оvеr аnоthеr. # Stack allows operations at one end of it. => namely at the Top # PUSH:Addition and POP:Deletion happens only at the Top # Lаst in First Оut(LIFО) fеаturе # # ============================================================================= class Stack: def ...
# А tuplе is а sеquеncе оf immutаblе Pythоn оbjеcts. # Tuplеs аrе sеquеncеs, just likе lists. # tuplеs usе pаrеnthеsеs # # # ============================================================================ tup1 = ('physics', 'chеmistry', 1997, 2000) tup2 = (1, 2, 3, 4, 5 ) # empty tuple tup_empty = () # ...
#dectionalry = {Key1:"Value1",Key2 : "Value2,Key3 : "Value3"} Dection = {1:"I", 2 : "am", 34: "Pruthvi"} print(Dection) #Dic key can be num, strg ....anything print("key 34 value is -->", Dection[34]) # Dectionary[Key] to access the value in Key EmptyDectionary = {} #EmptyDictionary #-------- Add new key & value to...
#-------------------Slicing list list1 = [0,1,2,3,4,5,6,7,8,9] print(list1[0:10:3]) print(list1[::2]) print(list1[8:1:-2]) print(list1[::-1]) #to revrese a string
import numpy as np def average(a,n): sum = np.cumsum(a,dtype=float) sum[n:]=sum[n:] - sum[:-n] return sum[n-1:]/n a = [3, 5, 7, 2, 8, 10, 11, 65, 72, 81, 99, 100, 150] print(average(a, 3)) def matrix(ipvector, n, increasing=False): if not increasing: op_matx = np.array([x ** (n - 1 - i) for x...
def find_it(seq): #print(seq) #1) look at all the integer count_found = { "answer": [None] } def recursion(key_to_check_for): try: hold = count_found[key_to_check_for] #3) keep count of how many found count_found[key_to_check_for] += 1 exce...
#!/usr/bin/env python # coding: utf-8 # In[1]: def missing_char(word,index) : x = word.split("") x.pop(index) x.join() # In[17]: name = 'kitten' ind = 1 x= '' # In[34]: def missing_char(word,index) : x = list (word) x.pop(index) x= ''.join(x) return x # In[35]: missi...
import unittest import HandClass class HandClassTestCase(unittest.TestCase): def test_handclass_correctrank_successful(self): cards = {"AS","10C","10H","3D","3S"} hand = HandClass.Hand(cards) self.assertEqual(set(hand.Rank),set(["A","10","10","3","3"])) def test_handclass_correctsuit_succesfful(self): cards...
# -*- coding: utf-8 -*- """ Created on Wed Jun 15 12:52:43 2016 @author: richaopf """ import random, copy def choose(thing): chosen = [] if type(thing) is dict: for key in sorted(thing.keys()): if type(key) is str and key.startswith('!'): options = thing.pop(key) ...
from random import choice, randint STRINGS = list('ABCDEFGHIJKLMNOPQRSTUVWXYZ') ORIENTATIONS = ['updown', 'leftright', 'diagonalup', 'diagonaldown'] class BoardGrid: """ A class that basically represents the board of the puzzle. """ def __init__(self, grid_size, words): """ Initialize ...
'''Faça um Programa para um caixa eletrônico. O programa deverá perguntar ao usuário a valor do saque e depois informar quantas notas de cada valor serão fornecidas. As notas disponíveis serão as de 1, 5, 10, 50 e 100 reais. O valor mínimo é de 10 reais e o máximo de 600 reais. O programa não deve se preocupar com a qu...
#Faça um Programa que peça um número correspondente a um determinado ano e em seguida informe se este ano é ou não bissexto. ano=int(input('INFORME O ANO: ')) if ano % 4 == 0: print('Ano Bissexto!') else: print('O ANO INFORMADO NÃO É BISSEXTO')
'''Um posto está vendendo combustíveis com a seguinte tabela de descontos: Álcool: até 20 litros, desconto de 3% por litro acima de 20 litros, desconto de 5% por litro Gasolina: até 20 litros, desconto de 4% por litro acima de 20 litros, desconto de 6% por litro Escreva um algoritmo que leia o número de litros ve...
'''Tendo como dado de entrada a altura (h) de uma pessoa, construa um algoritmo que calcule seu peso ideal, utilizando as seguintes fórmulas Para homens: (72.7*h) - 58 Para mulheres: (62.1*h) - 44.7''' sexo=int(input('Escolha: \n1-Feminino \n2-Masculino\n')) if sexo == 1: altura=float(input('Qual sua altur...
""" COMP.CS.100 Programming 1 code template Fill in all TODOs in this file """ from math import sqrt def menu(): """ This is a text-based menu. You should ONLY TOUCH TODOs inside the menu. TODOs in the menu call functions that you have implemented and take care of the return values of the function ca...
from random import sample first_name = input('Please enter your first name: ') last_name = input('Please enter your last name: ') email = input('Please enter your email address: ') def generate_password(first_name, last_name): return first_name[:2] + last_name[-2:] + "".join(sample('abcdefghijklmnopqrstu...
def bubblesort(lst): #from last index to second for passes in range(len(lst) - 1, 0, -1): #from [0,passes[ keep swapping to put the largest #number at index passes for i in range(passes): if lst[i] > lst[i+1]: swap(lst, i, i+1) return lst def ...
import json def main(value: str) -> str: """Get a summary of the results of the predictions. Parameters ---------- value: str List-formatted string of the predictions Returns ------- str JSON-formatted string representing the summary of predictions """ results = js...
import numpy as np import math the_string = 'baaabaacaaabaaaa' #length of string string_length = len(the_string) unique = sorted(list(set(the_string))) print("Unique characters are: ",unique) #length of unique characters lenchar = len(unique) freq = np.zeros((1,lenchar)) prob = np.zeros((1,lenchar)) entropy_dict = {...
import numpy as np import cv2 # Create a rectangle rectangle = np.zeros((300, 300), dtype = "uint8") cv2.rectangle(rectangle, (25, 25), (275, 275), 255, -1) cv2.imshow("Rectangle", rectangle) cv2.waitKey(0) # Create a circle circle = np.zeros((300, 300), dtype = "uint8") cv2.circle(circle, (150, 150), 150, 255, -1) c...
from tkinter import * # python image library(PIL) from PIL import ImageTk, Image root = Tk() root.title('Images Demo') # add a icon root.iconbitmap('D:\\code\\pyGUI\\TKINTER\\mw.ico') # display an Image my_img = ImageTk.PhotoImage(Image.open("r.png")) my_lable = Label(image=my_img) my_lable.pack() ...
############ # Part 1 # ############ class MelonType(object): """A species of melon at a melon farm.""" def __init__(self, code, first_harvest, color, is_seedless, is_bestseller, name): """Initialize a melon.""" self.code = code self.first_harvest = first_harvest ...
import pandas as pd import random import plotly.figure_factory as ff import statistics lists =pd.read_csv('medium_data.csv') population = lists['reading_time'].to_list() population_mean = statistics.mean(population) def random_set_of_mean(UL) : dataset = [] for i in range(0,UL) : random_index = ...
#!/usr/bin/env python2 # -*- coding: utf-8 -*- """ Created on Wed Jan 31 17:20:04 2018 @author: kristianeschenburg """ from Queue import Queue import numpy as np def bfs(graph,source = None,target = None): """ Breadth First Search from source vertex s to target vertex t. Returns the final path. If...
from math import * def checkredvalidity(board, row, col, row2, col2): if (board[row2][col2].piece == "" and abs(row2 - row) == 1 and abs(col2 - col) == 1 and row > row2): return True if (abs(row2 - row) == 2 and abs(col2 - col) == 2 and row > row2): if (board[(row2 + row) / 2][(col2 + col) / 2]....
# -*- coding: utf-8 -*- """ Created on Fri Oct 22 11:24:19 2021 @author: Alejandro Vargas """ #Realizado por: “Alejandro Vargas Pacha” #Ejercicio_1 - Parte_2 print("Programa que identifica el tipo de dato de un valor ingresado por el usuario, se realizarán cinco interacciones: ") for variable in r...
class Tile: def __init__(self, terrain_type, high_elevation, low_elevation=None): """ Initialises the terrain tile and attributes """ self.terrain_type = terrain_type self.high_elevation = high_elevation self.low_elevation = low_elevation self.rover = None def elevation(self): """ Returns an integ...
from tkinter import * import Total_Frame #Menusection class contains the menu on the cashier side. class MenuSection(object): def __init__(self, left, right): container = Frame(left, borderwidth=2, relief="solid") checkbox = self.Checkboxes(left) left.pack(side="left", expand=True, fill="bo...
class Link: def __init__(self, first, rest=()): self.first = first if isinstance(rest, Link): self.rest = rest elif rest: rest = list(rest) self.rest = Link(rest[0], rest[1:]) else: self.rest = () def __len__(self): return 1 + len(self.rest) def __getitem__(self, index): def getitem(self, i...
weight = float(input("enter your weight kilograms ")) height = float(input("enter your height centimeters ")) height = height/100 bmi = weight/(height*height) if(bmi>0): if(bmi<=18.5): print("You are severely Underweight.") elif(18.5<bmi<24.9): print("You are healthy.") elif(25<bmi<29.9): ...
def censor(text,word): word_list = text.split() print(word_list) print(word_list.count(word)) new_word = '' for iword in word_list: if iword == word: print(True) for char in range(0,len(iword)): new_word = new_word + "*" #word_list.replace...
# Задача 6. Вариант 12. # Создайте игру, в которой компьютер загадывает название одного из восьми соборов Московского кремля, а игрок должен его угадать. # Зыбкина Анастасия # 29.09.2016 import random sobor=("Успенский собор,Благовещенский собор,Архангельский собор,Колокольня Ивана Великого,Храм Положения ризы Б...
# HR data analysis using dataset from IBM, UCI, U.S. Census Reports and Bureau of Labor Statistics import pandas as pd import plotly.express as px import plotly.graph_objects as go from astropy.table import Table import warnings warnings.simplefilter("ignore") def read_dataframes(): """ In this function, ...
def bubbleSort(a, N): j = 0 while j < N - 1: i = 0 while i < N - 1: if a[i] > a[i+1]: a[i], a[i+1] = a[i+1], a[i] i += 1 j += 1 print(a) return a N = int(input('N= ')) import random A = [] for i in range(N): A.append(random.randint...
class Queue(object): def __init__(self): self.container = list() def add_item(self, item): self.container.insert(0, item) def get_item(self): return self.container.pop() def is_empty(self): return self.container == [] def size(self): return len(self.contai...
inventory = { 'gold' : 500, 'pouch' : ['flint', 'twine', 'gemstone'], 'backpack' : ['xylophone','dagger','bedroll', 'bread loaf'] } #adding a key 'burlap bag' and assigning a list to it inventory['burlap bag'] = ['apple','small ruby', 'tree-toed sloth'] #sorting the list found under the key 'po...
import os import sys sys.path.append('./data') import pandas as pd #read file class read_file: def __init__(self,file_path): self.file_path=file_path def read_data(self): if ".csv" in self.file_path: os.chdir("data") data_value=pd.read_csv(self.file_path) ...
#! /usr/bin/env python3 import sys import argparse import sqlite3 import hashlib from folder1 import birthdays from scripts import dbmanager """Requires the credentials (username and password). If valid, it returns the birthday of the searched famous person/people. """ def parse_argument(): parser = argparse...
import re import string class NameBuilder(object): def __init__(self): # constructor # field without specific class field definition self.replacements = {"ä": "ae", "ü": "ue", "ö": "oe", "Ä": "Ae", ...
# Dot-Strt and the Caret/Dollar import re beginRegex = re.compile(r'^Hello') #begin with expression ^ print(beginRegex.search('Hello There')) print(beginRegex.search('He said "Hello!"')) # this returns consonantRegex endRegex = re.compile(r'world$') print(endRegex.search('Hello world')) allDigitRegex = re.compile(r...
import os print(os.path.join('folder1', 'folder2', 'file.png')) print(os.getcwd()) a= ''' Files have a name and a path. The root folder is the lowest folder. In a file path, the folders and filename are separated by backslashes on Windows and forward slashes on Linux and Mac. Use the os.path.join() function to combine...
import random class Fortune: # check how to use these variables from init def __init__(self, name, color, age): self.name = name self.color = color self.age = age @classmethod def from_input(self): name = input('Name: ') color = input('Color: ') age = ...
# # eggs = 101 # this is a global variable def spam(): eggs = 99 #Local to function Spam bacon() print(str(eggs) + " eggs are from local spam") def bacon(): ham = 101 eggs = 0 #Local to function bacon print(str(eggs) + " eggs are from local bacon") return # return None value pr...
import math import os import random import re import sys # Complete the compareTriplets function below. def compareTriplets(a, b): score = [] alice = 0 bob = 0 if len(a) == len(b): for i in range(len(a)): if a[i] > b[i]: alice = alice + 1 elif a[i] < b[...
# https://www.geeksforgeeks.org/python-map-function/ def listToStr(list): #long way without any methods str1 = '' for i in range(len(list)): if list[i] != list[-2] and list[i] != list[-1]: str1 = str1 + str(list[i]) + ', ' elif list[i] == list[-2]: str1 = str1 + str...
"""Basic Binary Search Tree.""" # insert, traverse (three ways), search, remove class Node: def __init__(self, data, parent): self.data = data self.left_child = None self.right_child = None self.parent = parent class BST: def __init__(self): self.root = None def ...
"""Merge Sort. O(NlogN) linearithmic time""" def merge_sort(items): # Divide Phase (split into single items) if len(items) == 1: # base case return mid = len(items) // 2 left_half = items[:mid] right_half = items[mid:] print(f'items: {items}') print(f'left: {left_half}') pr...
""" 2^15 = 32768 and the sum of its digits is 3 + 2 + 7 + 6 + 8 = 26. What is the sum of the digits of the number 2^1000? """ def sum_digits(n: int) -> int: result = 0 for digit in str(n): result += int(digit) return result def euler_16(): return(sum_digits(2**1000)) if __name__ == "__main_...
#Exercicio 3a class Pessoa: def __init__(self, name): self.name = name def __str__(self): return self.name luiza = Pessoa("Luiza") print(luiza) mary = Pessoa("Mary") print(mary)
# -*- coding: utf-8 -*- """ Created on Wed Apr 10 01:25:56 2020 @author: KM Zubair """ import statistics if __name__ == '__main__': n = int(input()) # Using a dictionary student_marks = {} for _ in range(n): # Here the * grabs rest of the input after 'name' and put in a list of st...
# -*- coding: utf-8 -*- """ Created on Wed Apr 9 22:20:06 2020 @author: KM Zubair ( Got most part of this solution from the internet ) """ # print function must be inserted in the very beginnig of the code, excluding some exceptions from __future__ import print_function if __name__ == '__main__': # using a dict...
n=input() if len(n)==1 and n.islower(): print(n.upper()) else: t=0 for i in n: if i.isupper(): t+=1 if t==len(n): print(n.lower())
from Timer import timer # @timer def insertion_sort(nums): sorted_nums = nums[:1] for num in nums[1:]: insert_at = 0 while insert_at < len(sorted_nums) and num >= sorted_nums[insert_at]: insert_at += 1 sorted_nums.insert(insert_at, num) return sorted_nums
import argparse from helpers import * # 5. if amount > 1 each product gets own line and unique sold_id def sell(prod_name: str, sell_price: float, sell_date: str, amount: int): #checks if format of date is correct, if yes executes code if not error message checkSellDate = checkDate(sell_date) if...
# -*- coding: utf-8 -*- # @Author: PythonHardWay # @Date: 2018-05-10 14:46:43 # @Last Modified by: BinhPhan # @Last Modified time: 2018-05-10 14:46:59 def break_words(stuff): """This function will break up words for us.""" words = stuff.split(' ') return words def sort_words(words): """Sorts the w...
# -*- coding: utf-8 -*- # @Author: BinhPhan # @Date: 2018-05-10 13:22:07 # @Last Modified by: BinhPhan # @Last Modified time: 2018-05-10 13:46:30 def add(a, b): print "ADDING %d + %d" % (a, b) return a + b def subtract(a, b): print "SUBTRACTING %d - %d" % (a, b) return a - b def multiply(a, b): print "MUL...
""" Program: student_class.py Author: Ihsan Anwary Last date modified: 10/31/2020 This is an example of student class contains a diver and unit test """ class Student: """Student class""" def __init__(self, lname, fname, major, gpa=0.0): name_characters = set("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmn...
a = 5 b = 0 try: print(a/b) except Exception as e: print("Hey, you cannot divide a Number by Zero", e) print("Bye")
position = -1 def search(numberList,n): i = 0 for i in range(len(numberList)): if numberList[i] == n: globals()['position'] = i return True i = i + 1 return False numberList = [] nl = int(input("Enter the list size : ")) for i in range(0, nl): print("Enter number...
position = -1 def search(list,n): l = 0 u = len(list)-1 while l <= u: mid = (l+u) // 2 if list[mid] == n: globals()['position'] = mid return True else: if list[mid] < n: l = mid +1 else: u = mid...