text
stringlengths
5
121k
def perfect_num(num): sum = 0 for i in range(1,num): if num%i==0: sum+=i if sum==num: return f"The {num} is perfect number." return f"The {num} is not a perfect number." n = int(input("Enter a number :")) print(perfect_num(n))
class Base(): def __init__(self, name): self.name = name def getName(self): return self.name class Child(Base): def __init__(self, name, age): Base.__init__(self, name) self.age = age def getAge(self): return self.age class GrandChild(Child): def __init__(self, name, age, address): Child.__...
import unittest import line_class class Test_Dist_slope(unittest.TestCase): def test_distance(self): coordinate1 = (3,2) coordinate2 = (8,10) obj = line_class.Line(coordinate1,coordinate2) result = obj.distance() self.assertEqual(result, 9.433981132056603) def test_...
from RandomChoice import choose_randomly from os import listdir def list_files(files: list): print("What file would you like to choose from?") for i, file in enumerate(files): print(str(i + 1) + ". " + file) def main(): files = listdir("./Choices") list_files(files) choice = int(input())...
''' Write a program that asks the user for a long string containing multiple words. Echo back to the user the same string, except with the words in backwards order. For example, say we type the string: My name is Michele Then we would expect to see the string: Michele is name My ''' def reverse_str(string): ''' ...
print("Please enter a positive integer: ") input_num = int(input()) for counter in range(1, input_num + 1): print(counter)
def main(): print("Please enter the temperature in Fahrenheit: ") temp_fahr = float(input()) temp_celsius = fahrenheit_to_celsius(temp_fahr) print(temp_fahr, "Fahrenheit is", temp_celsius, "Celcius") def fahrenheit_to_celsius(F): temp_celc = (F - 32) * (5/9) temp_celc = round(temp_celc, 3) ...
print("Please enter a positive integer: ") number_of_numbers = int(input()) for i in range(2, (number_of_numbers*2) + 1, 2): print(i)
print("Please enter the number of days you traveled") days_traveled = int(input()) full_weeks = days_traveled // 7 remaining_days = days_traveled % 7 print(days_traveled, "days are", full_weeks, "weeks and",\ remaining_days,"days")
print("Please input several words, so a line of text, seperated with spaces: ") line = input() spaces_count = 0 for curr_char in line: if(curr_char == " "): spaces_count += 1 number_of_words = spaces_count + 1 print("You typed", number_of_words, "words")
print("Please enter a positive integer: ") n = int(input()) for i in range(1,n + 1): line = i*'*' print(line)
""" Khoa Tran CSE 163 AB This program performs analysis on a given Pokemon data file, giving various information like average attack levels for a particular type or number of species and much more. This program immplements the panda library in order to compute the statistics. """ def species_count(data): """ ...
x=1 while x<=9: y=1 while y<=x: print("{}*{}={}\t".format(x,y,x*y),end='') y +=1 print() x +=1 print() names = ['anne','beth','george','damon'] ages = [12,45,32,102] for i in range(len(names)): print(names[i],'is',ages[i],'years old') print(list(zip(names,ages))) from math im...
import pandas_datareader as data import pandas as pd import mplfinance as mpf import trading_functions as tf ''' This scripts purpose is to plot a candlestick chart out of a pandas dataframe. Next To-Do: - Add functions for - Inside days - Outside days - Plot Inside/Outside days in chart ''' ...
""" Given two words word1 and word2, find the minimum number of operations required to convert word1 to word2. You have the following 3 operations permitted on a word: Insert a character Delete a character Replace a character Example 1: Input: word1 = "horse", word2 = "ros" Output: 3 Explanation: horse -> rorse (rep...
""" Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as one sorted array. Note: The number of elements initialized in nums1 and nums2 are m and n respectively. You may assume that nums1 has enough space (size that is greater or equal to m + n) to hold additional elements from nums2. Example: I...
""" Description 32: Given a string containing just the characters '(' and ')', find the length of the longest valid (well-formed) parentheses substring. Example 1: Input: "(()" Output: 2 Explanation: The longest valid parentheses substring is "()" Example 2: Input: "((()()))" Output: 4 Explanation: The longest valid...
""" Description: Given an array of strings, group anagrams together. Example: Input: ["eat", "tea", "tan", "ate", "nat", "bat"], Output: [ ["ate","eat","tea"], ["nat","tan"], ["bat"] ] Note: All inputs will be in lowercase. The order of your output does not matter. Runtime: 152 ms, faster than 39.32% of Pytho...
""" Given two integers n and k, return all possible combinations of k numbers out of 1 ... n. Example: Input: n = 4, k = 2 Output: [ [2,4], [3,4], [2,3], [1,2], [1,3], [1,4], ] 执行用时: 160 ms, 在Combinations的Python3提交中击败了85.61% 的用户 内存消耗: 9.1 MB, 在Combinations的Python3提交中击败了56.38% 的用户 Not bad, just use recur...
""" Description: Given a 32-bit signed integer, reverse digits of an integer. Note: Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [−2^31, 2^31 − 1]. For the purpose of this problem, assume that your function returns 0 when the reversed integer overfl...
""" Description 24 Given a linked list, swap every two adjacent nodes and return its head. Example: Given 1->2->3->4, you should return the list as 2->1->4->3. Note: Your algorithm should use only constant extra space. You may not modify the values in the list's nodes, only nodes itself may be changed. Runtime: 48 ...
''' A Data frame is a two-dimensional data structure, i.e., data is aligned in a tabular fashion in rows and columns. Features of DataFrame: Potentially columns are of different types Size – Mutable Labeled axes (rows and columns) Can Perform Arithmetic operations on rows and columns ''' import pandas a...
''' A dictionary is like an address-book where we can find the address or contact details of a person by knowing only his/her name i.e. we associate keys (name) with values Dictionary is represented by dict class. Pair of keys and values are specified in dictionary using the notation d = {key1 : value1, key2 : value2 }...
''' A large number of methods collectively compute descriptive statistics and other related operations on DataFrame. Most of these are aggregations like sum(), mean(), but some of them, like sumsum(), produce an object of the same size. Generally speaking, these methods take an axis argument, just like ndarray.{sum, st...
''' Webscraping to GET the html response, then PARSE and fetch the content, FIND the tables, CONSTRUCT a DF We'll use here the pandas.read_html(), which returns a list of data frames. According to the PANDAS doc: "This function searches for <table> elements and only for <tr> and <th> rows and <td> elements within each ...
''' Functions are reusable pieces of programs. They allow us to give a name to a block of statements, allowing us to run that block using the specified name anywhere in your program and any number of times. This is known as calling the function. ''' def printMultipleTimes(message:str, time:int): print(message * tim...
''' A lambda function is a small anonymous function. A lambda function can take any number of arguments, but can only have one expression. Syntax lambda arguments : expression ''' sentence = "I bought a bike, from a bike store, she bought a bike from amazon, they bought a bike from bike stores" myLambdaFunction = lam...
''' The Series and DataFrame class of Pandas has an instance method called to_csv() which allows to write the DF to a file either in .xlsx, .txt or .csv format ''' import pandas as pd desired_width=320 pd.set_option('display.width', desired_width) pd.set_option('display.max_columns',100) df = pd.read_csv("~/Desktop/...
''' Find and output all rows contain a specific value in a specific column using df.loc() ''' import pandas as pd desired_width=320 pd.set_option('display.width', desired_width) pd.set_option('display.max_columns',100) df = pd.read_csv("~/Desktop/Learning/Sandbox/PythonSandbox/Data/pokemon_data.csv") print(df.loc[...
''' Webscraping to GET the html response, then PARSE and fetch the content, FIND the tables, CONSTRUCT a DF ''' import pandas as pd import requests from bs4 import BeautifulSoup from tabulate import tabulate from pandas import DataFrame res = requests.get("https://www.worldometers.info/coronavirus/") soup = Bea...
''' There is way of organizing a software program which is to combine data and functionality and wrap it inside something called an object. This is called the object oriented programming paradigm. In this program we'll explore Class, behaviour and attributes of a class ''' class Mail(): numberOfObjectsCreat...
''' Webscraping to GET the html response, then PARSE and fetch the content, FIND the tables, CONSTRUCT a DF We'll use here the pandas.read_html(), which returns a list of data frames. According to the PANDAS doc: "This function searches for <table> elements and only for <tr> and <th> rows and <td> elements within each ...
age: int = 20 name: str = "Shelley" print('{0} was graduated from Wayne State University in Michigan USA when she was {1}'.format(name,age)) print(f'{name} was graduated from Wayne State University in Michigan USA when she was {age}') print('{someOne} was graduated from Wayne State University in Michigan USA wh...
import matplotlib.pyplot as plt x_val = list(range(1, 5001)) y_val = [x**3 for x in x_val] plt.scatter(x_val, y_val, c=y_val, cmap=plt.cm.Reds, edgecolor='none', s=20) plt.title("Cube Numbers", fontsize=24) plt.xlabel("Value", fontsize=14) plt.ylabel("Cube of Value", fontsize=14) plt.tick_params(axis='bo...
""" stanCode Breakout Project Adapted from Eric Roberts's Breakout by Sonja Johnson-Yu, Kylie Jue, Nick Bowman, and Jerry Liao. Here is the basic version of breakout game. """ from campy.gui.events.timer import pause from breakoutgraphics import BreakoutGraphics FRAME_RATE = 1000 / 120 NUM_LIVES = 3 de...
import re import sys from collections import defaultdict def run_reindeer(speed, time, resting_time, run_time): total = time + resting_time laps = run_time // total rest = run_time - (laps * total) return laps * time * speed + (speed * (rest if rest < time else time)) def race(reindeer, run_time)...
user_list = [] id = 0 class user: def __init__(self, uid, name, age, film, food, address): self.uid = uid self.name = name self.age = age self.film = film self.food = food self.address = address def save_list(): global user_list data_list = open(r'1.0\user_...
a=int(input("Your number a:")) b=int(input("Your number b:")) a,b=b,a print("Your answer:",a,b)
""" Array Index & Element Equality Given a sorted array arr of distinct integers, write a function indexEqualsValueSearch that returns the lowest index i for which arr[i] == i. Return -1 if there is no such index. Analyze the time and space complexities of your solution and explain its correctness. input: arr = [-8...
""" Award Budget Cuts The awards committee of your alma mater (i.e. your college/university) asked for your assistance with a budget allocation problem they’re facing. Originally, the committee planned to give N research grants this year. However, due to spending cutbacks, the budget was reduced to newBudget dollars ...
""" Array Quadruplet (meaning 4Sum) Given an unsorted array of integers arr and a number s, write a function findArrayQuadruplet that finds four numbers (quadruplet) in arr that sum up to s. Your function should return an array of these numbers in an ascending order. If such a quadruplet doesn’t exist, return an empt...
import sys def encrypt(string, perm): ''' Takes a string and a list with the keys for the permutation Returns the permutation Inputs: string: a string perm: a list Returns: A string with the permuted message ''' n = len(perm) end = len(string) -1 ...
a=int(input("Enter the length of one side of the rectangle: ")) b=int(input("Enter the length of the other side of the rectangle: ")) c = a + a + b + b print("The perimeter of your rectangle is: ", c)
if __name__ == '__main__': n = int(input()) i = 1 numbers = [] while i <= n: numbers.append(str(i)) i+=1 start = 0 count = len(numbers) total = "" total =str(total) for number in numbers: total+=numbers[start] if start <= count: start+=1...
add = lambda x,y : x+y print(add(4, 6)) add = lambda x,y:x>y print(add(4, 6)) a = [(1, 2), (4, 5), (555, 34)] a.sort(key=lambda x:x[1]) print(a)
lengLista = int(input()) listaNumeros = [] for i in range(1, lengLista + 1): numero = int(input()) listaNumeros.append(numero) valores = listaNumeros def main (valores): contadorPositivo = 0 contadorNegativo = 0 for i in valores: if (numero != 0): ...
MENU = { "espresso": { "ingredients": { "water": 50, "coffee": 18, }, "cost": 1.5, }, "latte": { "ingredients": { "water": 200, "milk": 150, "coffee": 24, }, "cost": 2.5, }, "c...
import time import datetime class fake_datetime(datetime.datetime): """Like datetime.datetime, but always defer to time.time() These implementations of now and utcnow are lifted straight from the standard library documentation, which states that they are "equivalent" to these expressions, but may prov...
class Queue: """ Sequential Queue implement """ def __init__(self): """ initialize an empty Queue, __queue means it's a private member """ self.__queue = [] def first(self): """ get the first element of Queue :return: if Queue is empty return...
numero = int(input("Numero: ")) if numero > -3 and numero < 0 : print("Pertenece") elif numero >= 3 and numero < 6 : print("Pertenece")
alphabet = list(map(chr, range(ord('a'), ord('z')+1))) def main(): for c in alphabet: template = "Template/alphabettemplate.html" with open(template) as f: alphabettemplate = f.read() body = "Bodies/{}-body.html".format(c) w...
import string import collections def string_permutation(str1, str2): """Checks whether str1 and str2 are permutations of each other. Note that the function is case insensitive. """ if not ((str.isalpha(str1) or str1 == "") and (str.isalpha(str2) or str2 == "")): raise ValueError("The...
import sys prev_word = None counts = 0 for word_count in sys.stdin: word, count = word_count.split("\\") count = int(count) if prev_word == word: counts += count else: if prev_word: print("%s: %s"%(prev_word, counts)) counts...
class User: def __init__(self, username): self.username = username self.firstName = "" self.lastName = "" self.bio = "" self.friendsList = [] self.posts = [] self.userID = "" def addfirstName(self, firstName): self...
from urllib import request, error def get_ip_address(): import subprocess ip = subprocess.check_output(['hostname', '-s', '-I']).decode('utf-8')[:-1].split(' ')[0] return ip
''' constrains: 1. Consist of numbers, "+", "-", and ".". 2. Contain at most one of "+" and "-". 3. Have exactly one "." symbol, and must have a number after ".". 4. must contain at least 1 decimal value. ''' for _ in range(int(input())): dot = False number = False string = input() if string[0] in '01...
A = set(input().split()) result = True for _ in range(int(input())): B = set(input().split()) if B-A != set() or A-B == set(): result = False break print(result)
import re def varify(s): if not re.match(r'^[456]\d{3}(-?\d{4}){3}$',s): return 'Invalid' s = s.replace('-','') if re.search(r'(\d)\1{3}',s): return 'Invalid' return 'Valid' for _ in range(int(input())): print(varify(input()))
import calendar day_name = ['MONDAY', 'TUESDAY', 'WEDNESDAY', 'THURSDAY', 'FRIDAY', 'SATURDAY', 'SUNDAY'] date = input().split() year = int(date[2]) month = int(date[0]) day = int(date[1]) print(day_name[calendar.weekday(year,month,day)])
cube = lambda x: x**3 def fibonacci(n): if n==0: return [] fib = [1]*n fib[0] = 0 for i in range(3,n): fib[i] = fib[i-1] + fib[i-2] return fib ''' def fibonacci(n): fib = [0,1] for i in range(2,n): fib.append(fib[i-1]+fib[i-2]) return fib[0:n] ''' if __name__ == ...
import textwrap def wrap(string, n): result = '' k = len(string)//n for i in range(k): result += string[n*i:n*(i+1)]+'\n' if len(string)%n != 0: result += string[n*k:]+'\n' return result if __name__ == '__main__': string, max_width = input(), int(input()) result = wrap(stri...
""" Both loops, while and for, have one interesting (and rarely used) feature. As you may have suspected, loops may have the else branch too, like ifs. The loop's else branch is always executed once, regardless of whether the loop has entered its body or not. """ i = 1 while i < 5: print(i) i += 1 else: ...
""" A car's fuel consumption may be expressed in many different ways. For example, in Europe, it is shown as the amount of fuel consumed per 100 kilometers. In the USA, it is shown as the number of miles traveled by a car using one gallon of fuel. Your task is to write a pair of functions converting l/100km into mpg...
""" Take a look at the code in the editor: it reads a float value, puts it into a variable named x, and prints the value of a variable named y. Your task is to complete the code in order to evaluate the following expression: 3x3 - 2x2 + 3x - 1 The result should be assigned to y. """ x = 0 x = float(x) y = 3 * x ** ...
""" A natural number is prime if it is greater than 1 and has no divisors other than 1 and itself. Complicated? Not at all. For example, 8 isn't a prime number, as you can divide it by 2 and 4 (we can't use divisors equal to 1 and 8, as the definition prohibits this). On the other hand, 7 is a prime number, as we ca...
""" Powerful slices Fortunately, the solution is at your fingertips - its name is the slice. A slice is an element of Python syntax that allows you to make a brand new copy of a list, or parts of a list. It actually copies the list's contents, not the list's name """ list1 = [1] list2 = list1[:] list1[0] = 2 print...
""" The inner life of lists Now we want to show you one important, and very surprising, feature of lists, which strongly distinguishes them from ordinary variables. We want you to memorize it - it may affect your future programs, and cause severe problems if forgotten or overlooked. Take a look at the snippet in th...
""" Now you can easily swap the list's elements to reverse their order: """ myList = [10, 1, 8, 3, 5] print(myList) for i in range(len(myList) // 2): myList[i], myList[len(myList)-1-i] = myList[len(myList)-1-i], myList[i] print(myList)
""" It's legal, and possible, to have a variable named the same as a function's parameter. The snippet illustrates the phenomenon: def message(number): print("Enter a number:", number) number = 1234 message(1) print(number) A situation like this activates a mechanism called shadowing: parameter x shadows ...
""" Spathiphyllum, more commonly known as a peace lily or white sail plant, is one of the most popular indoor houseplants that filters out harmful toxins from the air. Some of the toxins that it neutralizes include benzene, formaldehyde, and ammonia. Imagine that your computer program loves these plants. Whenever it ...
import sys import biotools file1 = sys.argv[1] file2 = sys.argv[2] def mkdictionary(filename): names = {} with open(filename) as fp: for name in fp.readlines(): name = name.rstrip() names[name] = True return names d1 = mkdictionary(file1) d2 = mkdictionary(file2) u1 = [] u2 = [] both = [] for wo...
from tkinter import * import os __author__ = "Sergey_Matusevich" def walk(dir_name="D:\\", min_size=100): for address, dirs, files in os.walk(dir_name): for file in files: addr = address + '/' + file if os.path.getsize(addr) >= min_size: yield addr def ins...
import _thread import time lock=_thread.allocate_lock() def print_time( threadName, delay): count = 0 if lock.acquire(): while count < 5: time.sleep(delay) count += 1 print ("%s: %s sec" % ( threadName, time.localtime()[5] )) lock....
""" Test utilities """ from pyquery import PyQuery as pq def html_pyquery(content): """ Shortand to use Pyquery parsing on given content. This is more useful to dig in advanced HTML content. PyQuery is basically a wrapper around ``lxml.etree`` it helps with a more intuitive API (alike Jquery) to ...
""" Created on Mon Jan 29 19:31:22 2018 @author: IBM-Watson """ from graphics import * import math def main(): win = GraphWin('Rectangle Information', 400 , 400) win.setCoords(-10, -10, 10, 10) point1 = win.getMouse() point2 = win.getMouse() aRectangle = Rectangle(point1,...
"""Package that will handle `ISO 8601:2004 Representation of dates and times <http://www.iso.org/iso/catalogue_detail?csnumber=40874>`_ parsing and formatting. """ __copyright__ = """Copyright 2011 Lance Finn Helsten (helsten@acm.org)""" from .__meta__ import (__version__, __author__, __license__) from .time import ...
""" The interface class providing the way to configure an EV3 lego robot. The robot is represented by an instance of EV3Robot class. This is meant to be derived from and passed to EV3RobotDriver instance. """ class EV3RobotConfigurator(object): drive = None touch_sensor = None ir_sensor = None ...
"""Common functions used in COINSTAC scripts. """ import numpy as np def list_recursive(d, key): """Yields the value corresponding to key in a dict d.""" for k, v in d.items(): if isinstance(v, dict): for found in list_recursive(v, key): yield found if k == key: ...
cubes = [] for value in range(1, 11): print(value**3, " ", end="") print("\nfinished")
one_million = [] for value in range(1, 1000001): one_million.append(value) print(f"Mininum value is {min(one_million)}") print(f"Maximum value is {max(one_million)}") print(f"The sum of adding one million numbers together is {sum(one_million)}!") print("\nfinished")
from random import choice lottery_numbers = ('0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd') ticket = "" for x in range(1, 7): ticket += choice(lottery_numbers) print(f"The winning number is: {ticket.upper()}...")
from restaurant import Restaurant class IceCreamStand(Restaurant): def __init__(self, name, cuisine, flavors=None): super().__init__(name, cuisine) self.flavors = flavors def add_flavor(self, flavor): """This method adds an ice cream flavor to the the flavors list.""" se...
import unittest from city_functions import get_formatted_city_country class CityCountryNameTestCase(unittest.TestCase): """Tests get_formatted_city_country().""" def test_city_country(self): """Do names like santiago chile work?""" formatted_city_country = get_formatted_city_country...
"""A set of clases that can be used to represent users, specialized users and privileges.""" class User: """The User class is a simple attempt to model a computer user.""" def __init__(self, user_id, first_name, last_name, address_1=None, address_2=None, city=None, ...
import matplotlib.pyplot as plt from typing import List upper_bound: int = 5001 input_values: range = range(1, upper_bound) cubes: List[int] = [x**3 for x in range(1, upper_bound)] plt.style.use("bmh") fig, ax = plt.subplots() ax.scatter(input_values, cubes, c=input_values, cmap=plt.cm.get_cmap( ...
cubes = [value**3 for value in range(1, 11)] for value in cubes: print(value, " ", end="") print("\nfinished")
cats_file = 'cats.txt' dogs_file = 'dogs.txt' try: with open(cats_file) as cats: contents = cats.read() except FileNotFoundError: pass else: print(contents) try: with open(dogs_file) as dogs: contents = dogs.read() except FileNotFoundError: pass else: print(contents)
from user import User u1 = User("leetuckert", "terry", "tucker") u1.address_2 = "1690 Macedonia Church Rd." u1.city = "Sparta" u1.state = "NC" u1.zip = "28675" u1.describe_user() print("") u1.increment_login_attempts() u1.describe_user() print("") u1.increment_login_attempts() u1.increment_login_attem...
cubes = [value**3 for value in range(1, 11)] print("The entire list:") for value in cubes: print(value, " ", end="") print('\n') print(f"The first three items are: {cubes[:3]}") print(f"Three items beginning at index 3 are: {cubes[3:6]}") print(f"The last three items are: {cubes[-3:]}") print()
favorite_nums = { 'terry': [18, 21, 41, 60], 'carLee': [12, 16, 21, 25], 'linda': [16, 12, 44], 'rebekah': [21], 'nathan': [42, 25, 30, 35], } for name, numbers in favorite_nums.items(): if numbers: print(f"{name.title()}'s favorite numbers are:") print("\t", end="") ...
def make_car(manufacturer, model, **car): """ Make a car using a couple positional parameters and and arbitrary number of arguments as car. """ car['manufacturer'] = manufacturer car['model'] = model return car def print_car(car): """ Print out key/value pairs in the user profile diction...
favorite_places = { 'terry': ['wild cat rock', 'mount mitchell', 'grandfather mountain'], 'carlee': ['blue ridge parkway', 'tweetsie', 'boone', 'carter falls', 'cave', 'burger king'], 'linda': ['thrift store', 'home', 'little switzerland', 'sparta'], 'rebekah': [], } for na...
def make_shirt(text, size): print(f"Making a {size.title()} T-Shirt with the text '{text}'...") make_shirt('Love You', 'large') make_shirt(text="Love YOU", size='Medium') make_shirt(size='extra large', text='Love YOU')
class Car: """A simple attempt to model a car.""" def __init__(self, make, model, year): self.make = make self.model = model self.year = year self.odomoeter = 0 print("Car constructor...") def get_descriptive_name(self): """Return a long descriptive nam...
import pandas as pd import numpy as np from bokeh.models import ColumnDataSource, HoverTool, Range1d, Div from bokeh.plotting import figure, curdoc from bokeh.layouts import column, row, widgetbox from bokeh.models.widgets import Select, Slider import os """ This code uses Bokeh and Pandas to display the top sellers...
import node as n ''' Time complexity: O(n) Algorithm iterates through link list once only. It adds memory location as a key to a dictionary. As it iterates it checks if the current node memory matches any in the dictionary in O(1) time. If it does a cycle must be present. ''' def cycle(head_node): if head_nod...
def reverseIntArray(int_list): if int_list is None: raise Exception("Can't enter None") length = len(int_list) if length == 0: return None half = length // 2 for i in range(half): temp = int_list[i] int_list[i] = int_list[length - 1 - i] ...
def unique_pairs(int_list, target_sum): ''' Time complexity: O(n^2). 1) This is because I have a nested for loop. I search through int_list, and for each element in int_list I search through int_list again. N for the outer and n^2 with the inner. 2) The second part of...
""" http://quiz.geeksforgeeks.org/puzzle-100-people-in-a-circle-with-gun-puzzle/: 100 people standing in a circle in an order 1 to 100. No. 1 has a gun. He kills the next person (i.e. No. 2) and gives the gun to the next (i.e. No. 3). All people do the same until only 1 survives. Which number survives at the last? The...
def is_merge(s, part1, part2): return merge(s, part1, part2) or merge(s, part2, part1) def merge(s, part1, part2): if (s == '' and part1 == '' and part2 == ''): return True elif (s != '' and part1 != '' and s[0] == part1[0]): return is_merge(s[1:], part1[1:], part2) elif (s != '...