text
stringlengths
5
121k
class Solution: def threeSum(self, nums): result = [] print(float('inf')) for i in range(0, len(nums)): for j in range(i+1, len(nums)): for k in range(j+1, len(nums)): if nums[i] + nums[j] + nums[k] == 0: childResult = [...
from collections import deque class findLongestSubString: def longest_string_online(self, s): curr = deque() longest = 0 for c in s: if c in curr: while curr.popleft() != c: pass curr.append(c) longest = max(longest, len(curr)) r...
names = ['tony','deirdre','senan','carol'] print(names[0:2]) print(names[1:3]) print(names[:3]) print(names[2:]) print(names[-3:])
admin_users = ['tony','frank'] username = input("Please enter you username?") if username not in admin_users: print("You do not have access.") else: print("Access granted.")
import json filename = 'username.json' try: with open(filename) as f1: username = json.load(f1) except FileNotFoundError: username = input("What's your saint nick's name") with open(filename, 'w') as f2: json.dump(username, f2) else: print("Welcome back %s!" % username)
str = 'hello world and welcome to the show' print(str.split(' ', 4)) for word in range(len(str.split())): print(str.split()[word])
rental_properties = {} rental_open = True while rental_open: username = input("\nWhat is your name?") rental_property = input("What is the address of the property you would like to rent?") rental_properties[username] = rental_property repeat = input("\nDo you know anyone how might like to...
registered_names = ['tony','frank','mary','peter'] username = input("Please enter username you would like to use.\n\n").lower() if username in registered_names: print("Sorry, username is already taken.") else: print("This username is available")
terms = {'integer' : 'Is a number that contains a decimal place.' , 'string' : 'a sequence of characters.'} del terms['integer'] print(terms)
def welcome(username): """Showing a username""" print("Hi " + username.title() + ".\n") name = 'omer' welcome(name) welcome('jessie') welcome(username = 'david')
numbers = list(range(1,6)) print(numbers) print('\n') even_numbers = list(range(0,102, 2)) print(even_numbers) print('\n') print("List of square values of 1 to 10:") squares = [] for value in range(1,11): square = value ** 2 squares.append(square) print(squares) print('\n') digits = [1,2,3,4...
class Tablet(): """This will be the class that uses the attribute.""" def __init__(self, thickness, color, battery): """Initialize a parameter as a class""" self.thickness = thickness self.color = color self.battery = battery self.screen = Screen() class Screen(): """This will be the attribute for ...
def assign_seat(seat, *requests): """Assign a seat and requests to a passenger""" print("\nThe passenger in seat %d has made the follwing requests:" % (seat)) for request in requests: print("- " + request) assign_seat(5, 'window seat', 'pre-order breakfast', 'extra leg space')
from tkinter import * import smtplib from tkinter import messagebox root = Tk() root.geometry('500x500') root.title('Email Sender @_python.py_') root.resizable(False, False) root.config(bg="#fff") Email = StringVar() Password = StringVar() To = StringVar() Subject = StringVar() def emaillogin(): f = Frame(r...
def has_duplicates(dates): word_checked = {} same_date = [] for i in dates: if i not in word_checked: word_checked[i] = 1 else: if word_checked[i] == 1: same_date.append(i) word_checked[i] = word_checked[i] + 1 return word_checked dates = [(2020, 5, 17),(2019, 5, 17),(2020,...
from typing import List, Optional import math import attr import pickle Time = float @attr.s(frozen=True) class Location(object): """ The distance between any pair of locations must be known, this is the only requirement. A simple way to fulfill this requirement is by generating 2D coordinates ...
found = True userinput = input ("Enter the file name: ") string = input ("Enter the string: ") myfile = open (userinput) for line in myfile: if string in line: print ("The line which contain the string", string, "is: ", line) found = False myfile.close() if found: print ("The string", ...
def bunny_ears(n): if n <= 0: return 0 elif n % 2 == 0: return bunny_ears(n-1) + 2 else: return bunny_ears(n-1) + 3 x = int(input("Enter a number of bunnies: ")) print("The number of ears are:", bunny_ears(x))
import random with open("input.txt") as f: words = f.read() words = words.split() word_after = dict() for i, word in enumerate(words[:-1]): if word in word_after: word_after[word].append(words[i+1]) else: word_after[word] = [words[i+1]] sentence = "he" value = sentence while not sente...
def determinePrime(number): if number < 2: return False if number == 2: return True for i in range(2,number): if number % i == 0: return False return True def checkPrimeDuplicate(d): count = 0 for i in range(0,len(d)): for specific in d[i]: if determinePrime(specific)==True: count = count + 1 ...
import time import re ''' module to convert the given time in UTC to local device time _convert() method takes a single time in string and returns the local time convert() takes a list of time in string format and returns in local time NOTE: any string not in the format "digits:digits" will be returned as is USAGE:...
import graph def main(): base_input = input().split(' ') numero_cidades = int(base_input[0]) gp = graph.Graph() for i in range(1, numero_cidades+1): gp.add_vertex(str(i)) numero_pares = int(base_input[1]) for i in range(numero_pares): base_input = input().split(' ') ...
from collections import defaultdict import math with open('d23_input.txt') as f: puzzle_input = [line.strip().split() for line in f.readlines()] def run_program(instructions, part2_mode=False): registers = defaultdict(int) if part2_mode: registers['a'] = 1 pointer = 0 mul_count = 0 ...
test_input = """ 0 <-> 2 1 <-> 1 2 <-> 0, 3, 4 3 <-> 2, 4 4 <-> 2, 3, 6 5 <-> 6 6 <-> 4, 5""".strip().splitlines() with open('d12_input.txt') as f: puzzle_input = f.readlines() def build_groups(inp): return dict(parse_line(line) for line in inp) def parse_line(line): """return the index and direct lin...
n = int(input()) for i in range(1,n+1): string = reversed(input().rstrip().split()) print('Case #' + str(i) + ': ' + ' '.join(string))
while True: in_value = input() if in_value != '0 0 0': L = sorted(tuple(map(int, in_value.split()))) if L[-1]**2 == (L[0]**2 + L[1]**2): print('right') else: print('wrong') else: break
def my_sum(l): print(l) try: if not l: return 0 else: return l[0] + my_sum(l[1:]) except RecursionError as re: print(re) return 0 def my_sum2(l): try: first, *rest = l print(l) return first if not rest else first + my_sum...
from typing import List def longest_common_prefix(strs: List[str]) -> str: if not strs: return "" shortest = min(strs, key=len) for i, ch in enumerate(shortest): for other in strs: if other[i] != ch: return shortest[:i] return shortest if __name__ == "__ma...
contests = [[5, 1], [2, 1], [1, 1], [8, 1], [10, 0], [5, 0]] k = 3 def luck_balance(k, contests): max_luck = 0 loose_important = 0 contests.sort(reverse=True) for contest in contests: if contest[1] == 0: max_luck += contest[0] else: if loose_important < k: ...
from random import randint from Playground.my_utils.staff.timer3 import timer3 @timer3 def binary_search(list_: list, item): """list_ must be sorted""" first = 0 last = len(list_) - 1 while first <= last: mind_point = (first + last) // 2 if list_[mind_point] == item: retu...
import networkx as nx import matplotlib.pyplot as plt def depth_first_search(graph: dict, start: str, visited: set = None) -> set: if visited is None: visited = set() visited.add(start) print(start) for next_ in graph[start] - visited: depth_first_search(graph, next_, visited) retu...
def extended_gcd(a: int, b: int) -> tuple: assert a >= 0 and b >= 0 and a + b > 0 if b == 0: d, x, y = a, 1, 0 else: (d, p, q) = extended_gcd(b, a % b) x = q y = p - q * (a // b) return d, x, y def chinese_remainder_theorem(n1, r1, n2, r2): (_, x, y) = extended_gc...
def print_formatted(number): w = len(f'{number:b}') for n in range(1, number + 1): print(f'{n:={w}} {n:={w}o} {n:={w}X} {n:={w}b}') if __name__ == '__main__': print_formatted(99)
class Squares: def __init__(self, start, stop): if self.check(start): self.value = start - 1 self.stop = stop else: self.value = 0 self.stop = 0 def __iter__(self): return self def __next__(self): if self.value == self.stop: ...
def stable_matching(n: int, men_preferences: list, women_preferences) -> list: unmarried_men = list(range(n)) man_spouse = [None] * n woman_spouse = [None] * n next_man_choice = [0] * n while unmarried_men: he = unmarried_men[0] his_preferences = men_preferences[he] she = h...
import string from random import choices def generate_random_string(size): return "".join(choices(string.ascii_lowercase, k=size)) def generate_random_string_all(size): return ''.join(choices(string.ascii_letters + string.digits, k=size)) if __name__ == '__main__': print(generate_random_string_all(12)...
print("I'm : ", __name__) def min_max(test, *args): res = args[0] for arg in args: if test(arg, res): res = arg return res def less_than(x, y): return x < y def greater_than(x, y): return x > y if __name__ == '__main__': print(min_max(less_than, 4, 2, 1, 4, 67, 8, 9, 3, 1))...
class SuperMeta: def __call__(self, classname, supers, classdic): print("in SuperMeta.call: ", classname, supers, classdic, sep='\n') Class = self.__new__(classname, supers, classdic) self.__init__(Class,classname, supers, classdic) return Class class SubMeta(SuperMeta): def __...
from itertools import permutations def count_triplets(arr: list, r: int) -> int: try: if len(arr) <= 2: return 0 triplets = [tuple(sorted(per)) for per in permutations(arr, 3)] count = 0 for triplet in triplets: if triplet[1] == triplet[0] * r and triplet[2...
import random from datetime import datetime, date import calendar import csv class NationLottery: def populate_draw_ticket(self): x = 0 y = 6 entry_ticket = [] while x < 6: user_number = input("Please enter " + str(y) + " numbers int...
def swap_tuple(value_one,value_two): value_one,value_two=value_two,value_one return value_one,value_two X=input("enter value of X :") Y=input("enter value of Y :") X, Y=swap_tuple(X,Y) print('value of X after swapping:', X) print('value of Y after swapping:', Y)
import matplotlib.pyplot as plt plt.figure x_series = [0,1,2,3,4,5] y_series_1 = [x**2 for x in x_series] y_series_2 = [x**3 for x in x_series] plt.plot(x_series, y_series_1, label="x^2") plt.plot(x_series, y_series_2, label="x^3") plt.xlabel("Small X Interval") plt.ylabel("Calculated Data") plt.title("Our Fan...
a = 5 b = 10 print(a+b) print(type(a+b)) print('') a = 5.0 b = 10.0 print(a+b) print(type(a+b)) print('') texto = "Lorem ipsum dolor sit amet." print(texto) print(type(texto))
my_dict = {'a':500, 'b':5874, 'c': 560,'d':400, 'e':5874, 'f': 20} print('Maximal keys:') print([k for k,v in my_dict.items() if v == max(my_dict.values())])
from itertools import compress from random import randint nums = [randint(-9, 10) for i in range(15)] positive = [num for num in nums if num > 0] negative = list(filter(lambda num: num < 0, nums)) print(f'positive: {positive}\nnegative: {negative}', end='\n\n') def is_int(val): try: nu...
""" Experimenting with Python's Counter data type! Counter is a container that keeps track of how many times equivalent values are added. Just like a dictionary (it's a dict subclass), except values can be positive/negative integers. It's an unordered collection where elements are stored as keys. """ from collecti...
from itertools import groupby from collections import defaultdict from operator import itemgetter rows = [ {'address': '5412 N CLARK', 'date': '07/01/2012'}, {'address': '5148 N CLARK', 'date': '07/04/2012'}, {'address': '5800 E 58TH', 'date': '07/02/2012'}, {'address': '2122 N CLARK', 'date'...
import copy """Shallow copy of an object """ class Point: def __init__(self, x, y): self.x = x self.y = y def __repr__(self): return f'Point({self.x!r}, {self.y!r})' a = Point(23, 42) b = copy.copy(a) print(a) print(b) print(a is b) class Rectangle: def __init__(self, topleft, ...
""" Decorators: allow you to extend the behaviour of a callable(fun, class, method) """ def null_decorator(func): return func def greet(): return 'hello' greet = null_decorator(greet) print(greet()) @null_decorator def greeting(): return 'hello!' print(greeting())
""" Lambda are single statement anonymous function """ add = lambda x, y: x + y print(add(5, 3)) print((lambda x, y: x + y)(10, 20)) """Sorting iterables with alt key """ tuples = [(1, 'd'), (2, 'b'), (4, 'a'), (3, 'c')] tuples.sort(key=lambda x: x[1]) print(tuples) """ this are the same""" lel = list(range(-5,...
with open('hello.txt', 'w') as f: f.write("hello, world!") f = open('hello.txt', 'w') try: f.write('hello world') finally: f.close()
class Adder: def __init__(self, n): self.n = n def __call__(self, x): return self.n + x plus_3 = Adder(3) print(plus_3(4)) print(callable(plus_3))
""" default dict is dict subclass that returns a callable if the key cannot be found """ from collections import defaultdict dd = defaultdict(list) dd['dogs'].append('Rufus') dd['dogs'].append('Kathrin') dd['dogs'].append('Mr Sniffles') print(dd['dogs']) print(dd)
from intcomputer import intcomputer, input_ctrl def main(): filename = 'day21_input.txt' with open(filename, 'r') as f: text = f.read() program = [int(numeric_string) for numeric_string in text.split(",")] imp_str = 'NOT A J\nNOT C T\nOR T J\nAND D J\nWALK\n' comp_input = [ord(c...
import re mystring = "Monty Python ! And the holy Grail ! \n" word_freq = {} for tok in mystring.split(): if tok in word_freq: word_freq[tok] += 1 else: word_freq[tok] = 1 print(word_freq)
from . import utility class offer(): _multi = False def __init__(self, **kwargs): pass def discount(self,**kwargs): pass def isMulti(self): return self._multi class xfory(offer): _x = _y = 0 def __init__(self, **kwargs): self._x = kwargs...
""" Given a cell with "it's a fib sequence" from slideshow, please write function "check_fib", which accepts a Sequence of integers, and returns if the given sequence is a Fibonacci sequence We guarantee, that the given sequence contain >= 0 integers inside. """ from typing import Sequence def check_fibonacci...
""" We have a file that works as key-value storage, each line is represented as key and value separated by = symbol, example: name=kek last_name=top song_name=shadilay power=9001 Values can be strings or integer numbers. If a value can be treated both as a number and a string, it is treated as number. Write a wrappe...
""" Some of the functions have a bit cumbersome behavior when we deal with positional and keyword arguments. Write a function that accept any iterable of unique values and then it behaves as range function: assert = custom_range(string.ascii_lowercase, 'g') == ['a', 'b', 'c', 'd', 'e', 'f'] assert = custom_range(stri...
def funk(mom): totSweets = 0 for no in mom: totSweets = totSweets + int(no) return totSweets def countThree(mom): count = 0 for no in mom: if(int(no)%3==0): count = count + 1 return count+1 n = int(input()) mom = input().split() if(funk(mom)%3==0): print("Yes " + str(countThree(mom))) else: print("No"...
import math def nCr(n,r): f = math.factorial return f(n) / f(r) / f(n-r) N, K = input().split() N= int(N) K = int(K) res = 0 for k in range(0, K+1, 2): res = res + int(nCr(N,k)) print( str(res) )
while(True): print("CELSIUS TO FAHRENHEIT CONVERTER") celsius = float(input("Please enter your degree by celcius:")) fahr=1.8*celsius+32 print("Your temperature " +str(celsius) + " Celsius is " +str(fahr) + " in Fahrenheit.")
import nmap scanner = nmap.PortScanner() print("Nmap Automation Tool") print("--------------------") ip_addr = input("IP address to scan: ") print("The IP you entered is: ", ip_addr) type(ip_addr) resp = input("""\nSelect scan to execute: 1) SYN ACK Scan 2) UDP Scan ...
""" LeetCode 252 Easy Meeting Rooms Given an array of meeting time intervals consisting of start and end times [[s1,e1],[s2,e2],...] (si < ei), determine if a person could attend all meetings. For example, Given [[0, 30],[5, 10],[15, 20]], return false. """ def meeting_rooms(intervals): """ Sort the meeting...
def day6(): inp = '4 10 4 1 8 4 9 14 5 1 14 15 0 15 3 5' memory = [int(i) for i in inp.strip().split()] past_states = [] num_banks = len(memory) cycles = 0 while (hash(tuple(memory)) not in past_states): past_states.append(hash(tuple(memory))) rea...
i=1 a=0 b=1 while b<=10**999: a,b=b,a+b i+=1 print ("The "+str(i)+"th term is the first term to have 1000 digits.\n") print ("The number is:\n"+str(b))
lista=[1,2,3,4,5,6,7,8,8] l=len(lista) n=False for x in range(l): for y in range(l): if x!=y and lista[y]==lista[x]: n=True if n==True: print ('Yes') else: print('No')
import time x = input("What number do you want to start the count from?\n") while not x.isnumeric(): x = input("That is not a number...\nWhat number do you want to start the count from?\n") xInt = int(x) y = input("What number do you want to end the count on?\n") while not y.isnumeric(): y = input("What numbe...
import time print("Hello there!") print("What's your name?") name = input() print("Hello there, " + name) time.sleep(2) print("You have arrived at a horror mansion!\nIt's a large and spooky house with strange noises coming from inside") time.sleep(2) print("You hop out of the car and walk closer...") time.sleep(2) pri...
def sum(*nums: int) -> int: _sum = 0 for num in nums: _sum += num return _sum res = sum(1, 2, 3, 5) print(res)
number = int(input('Enter a number: ')) if number % 2 == 1: print('Odd') else: print('Even')
while True: number = int(input('Enter a number (-1 to stop): ')) if number == -1: break
def max_num(a, b): if a > b: return a return b def abs(x): if x >= 0: return x return -x inp = input() inp = inp.split() a, b, c = int(inp[0]), int(inp[1]), int(inp[2]) m_num = max_num(a, max_num(b, c)) if m_num == a: s_m = max_num(b, c) elif m_num == b: s_m = max_num(c, a)...
friend_salary = float(input('Enter your salary:')) my_salary = 1200 if friend_salary > my_salary: print('Friend\'s salary is higher') print('Code finish')
def hello(name): print('Hello', name) n = 'Kaka' hello(n)
from bs4 import BeautifulSoup import requests url = 'https://en.wikipedia.org/wiki/List_of_deadly_earthquakes_since_1900' r = requests.get(url) html_content = r.text html_soup = BeautifulSoup(html_content, 'html.parser') earthquakes_table = html_soup.find_all('table', class_='wikitable') earthquakes = ...
""" Regular expression basics, regex groups and pipe character usage in regex """ import re message = 'Call me at 415-555-1011 tomorrow. 415-555-9999 is my office.' phoneNum_regex = re.compile( r'\d\d\d-\d\d\d-\d\d\d\d') mob_num = phoneNum_regex.search(message) print(mob_num.group) phoneNum_regex = re.co...
import unittest def reverse(n: list): return list(reversed(n)) class TestListMethod(unittest.TestCase): def test_get_reverse1(self): nums = [10, 20, 40, 80] self.assertListEqual(reverse(nums), [80, 40, 20, 10]) def test_get_reverse2(self): nums = [10, 20, 40, 40, 80] ...
import unittest from src.dominio import Cliente, Lance, Leilao class TestLances(unittest.TestCase): def setUpClass(): pass def setUp(self): self.phyl = Cliente("Phyl") self.lance_do_phyl = Lance(self.phyl, 150.0) self.leilao = Leilao("1 Saco de Arroz de 5kg"...
num = 123456786 x = [int(a) for a in str(num)] n = x.pop() z = (sum(x)) if z%10== n: print('VALID') else: print ('INVALID') num = 123456789 x = [int(a) for a in str(num)] n = x.pop() z = (sum(x)) if z%10== n: print('VALID') else: print ('INVALID') num = 123 x = [int(a) for a in str(num)...
class Grid: def __init__(self, arr): self.arr = arr def find_minimum_steps(self): res = 0 for i in range(0, len(self.arr)-1): res = res + self.min_of_two(self.arr[i], self.arr[i+1]) print("Min Steps: {}".format(res)) def min_of_two(self, first, second): ...
def select_max(A, left, right): max_pos = left i=left while i<= right: if A[i] > A[max_pos]: max_pos = i i = i + 1 return max_pos def selection_sort(A): for i in range (len(A) - 1, 0, -1): max_pos = select_max(A,0,i) if max_pos !=i: ...
import sys import functools def allow_space(c): ''' :param c: str :return: Bool True 允许加空格,False 不允许加空格 ''' return not c.isspace() and not (c in ',。;「」:《》『』、[]()*_') def is_latin(c): ''' 判断是否为英文字符,或者是数字 :param c: str :return: Bool True 允许加空格,False 不允许加空格 ''' return ord(c...
import tkinter as tk from tkinter import messagebox def hello(): l1 = tk.Label(win, bg="yellow",text=msg, width=20) l1.place(x = 50, y = 250) win = tk.Tk() win.geometry("500x500+50+50") l2 = tk.Label(win, bg="yellow",text="username", width=20) l2.place(x = 50, y = 50) l3 = tk.Label(win, bg="yellow",text="passw...
import tkinter as tk from tkinter import messagebox def hello(): msg = e1.get() l1 = tk.Label(win, bg="yellow",text=msg, width=20) l1.place(x = 50, y = 250) win = tk.Tk() win.geometry("500x500+50+50") e1 = tk.Entry(win, bg="yellow",width=20) e1.place(x = 50, y = 50) b1 = tk.Button(win, text = "Click Me",...
print('hello python') print("hello python") print() print('''hello python''') print("""hello python""") print('T','E','S','T',sep='/') print('T','E','S','T',sep='') print('2020','07','14',sep='-') print('test','naver.com',sep='@') print('------------- end 옵션 ---------------') print('welcome ...
def almost(s,t): hash_s = {} hash_t = {} for i, j in zip(s,t): if i not in hash_s: hash_s[i] =1 else: hash_s[i] += 1 if j not in hash_t: hash_t[j] = 1 else: hash_t[j] += 1 ...
import math def isPrime(n): for i in range (2,int(math.sqrt(n))+1): if n%i==0: return False return True def primeString(string): res = [] for i in string: ascii = ord(i) if isPrime(ascii): res.append(i) else: s = True j = ascii ...
''' Input: "eeeeffff" Output: 1 Why? We can delete one occurence of e or one occurence of 'f'. Then one letter will occur four times and the other three times. Input: "aabbffddeaee" Output: 6 Why: For example, we can delete all occurences of 'e' and 'f' and one occurence of 'd' to obtain the ...
row =int(input('Insert num: ')) for i in range(row): for _ in range(i + 1): print('*', end = '') print() for i in range(row): for j in range(row): if j < row -i - 1: print(' ', end = '') else: print('*', end = '') print() for i in range(row): for j in range(row): if j < row -i - 1: print('...
win = 0 lose = 0 while True: import random comp = random.randint(1,5) choose = int(input("Guess any number 1-5: ")) if comp == 1: print("bot = 1") elif comp == 2: print("bot = 2") elif comp == 3: print("bot = 3") elif comp == 4: print("bot ...
''' Python连接MySQl ''' import pymysql class Python_MySQL(): ''' host:主机名 userName:数据库拥有者 password:数据库登录密码 tableName:数据库名 ''' def __init__(self, host, userName, paassword, tableName): self.host = host self.userName = userName self.password = paassword sel...
import numpy as np import matplotlib.pyplot as plt def expert_chooses(crowd): expert = max(crowd) if np.random.uniform(0,1) < expert: return 1 else: return 0 def crowd_chooses(crowd): ballots = [] for c in crowd: if np.random.uniform(0,1) < c: ballots.append(1) ...
import pandas as pd import numpy as np from day_6.list_tuple import main_list from datetime import date, datetime from datetime import date today = date.today() def calculate_age(born): today = date.today() return today.year - born.year - ((today.month, today.day) < (born.month, born.day)) id = [] age =...
text = input("Hello, please talk\n") print("Your talk is {} chars long".format(len(text))) print("words={}, spaces={}".format( len(text.split(" ")), text.count(" ") ))
a = int(input("Type a:\n")) b = int(input("Type b:\n")) print("input: a={}, b={}".format(a,b)) c = a a = b b = c print("input: a={}, b={}".format(a,b))
""" Created on Mon Sep 21 14:02:49 2020 @author: Adrian Gallo """ import matplotlib.pyplot as plt import matplotlib.animation as animation from matplotlib import style import pandas as pd style.use('fivethirtyeight') fig = plt.figure() ax1 = fig.add_subplot(1,1,1) x = [] pos = [] neg = [] neu = [] def animate(i...
def swap(arr, left, right): temp = arr[left] arr[left] = arr[right] arr[right] = temp return arr def partitionLomuto(arr, left = 0, right = None): if right == None: right = len(arr) - 1 pivot = arr[right] index = left for i in range(left, right): if arr[i]...
x = 123 y = 456 def swap(x, y): temp = x x = y y = temp return (x, y) result = swap(x, y) print(result)
def insertion_sort(list): for curr in range(1, len(list)): temp = list[curr] prev = curr - 1 while(prev >= 0): if (list[prev] > temp): list[prev + 1] = list[prev] list[prev] = temp prev = prev - 1 return list list = [10, 1, 9...