text
stringlengths
37
1.41M
class DLNode: def __init__(self, val=None): self.val = val self.next = None self.prev = None class MovingAverage: def __init__(self, size: int): """ Initialize your data structure here. """ self.capacity = size self.head = DLNode() ...
class UF: def __init__(self, vars): self.parents = {var: var for var in vars} self.size = {var: 1 for var in vars} def find(self, var): root = self.parents[var] while root != self.parents[root]: root = self.parents[root] while self.parents[va...
# Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def str2tree(self, s: str) -> TreeNode: """ "4 (2(3)(1)) (6(5)(7))" """ ...
""" # Definition for a Node. class Node: def __init__(self, val=None, children=None): self.val = val self.children = children if children is not None else [] """ O(N) | O(1) class Solution: def findRoot(self, tree: List['Node']) -> 'Node': valSum = 0 for i in range(len(tree)): ...
# Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def rob(self, root: TreeNode) -> int: """ Rob(node) = max amount possible at that node ...
class Solution: def reverseVowels(self, s: str) -> str: sarr = list(s) i, j = 0, len(sarr)-1 vowels = {'a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U'} while i < j: if sarr[i] not in vowels: i += 1 elif sarr[j] not in vowels: j...
# Path with Maximum Probability 1514. # You are given an undirected weighted graph of n nodes (0-indexed), represented by an edge list where edges[i] = [a, b] is an undirected edge connecting the nodes a and b with a probability of success of traversing that edge succProb[i]. # Given two nodes start and end, find th...
# Can Make Arithmetic Progression From Sequence 1502 # ttungl@gmail.com # Given an array of numbers arr. A sequence of numbers is called an arithmetic progression if the difference between any two consecutive elements is the same. # Return true if the array can be rearranged to form an arithmetic progression, otherwi...
#Library import csv import math from sklearn import preprocessing from sklearn.feature_selection import SelectKBest from sklearn.feature_selection import f_regression from sklearn.feature_selection import mutual_info_regression #Variables X = [] y = [] features = ('X','Y','month','day','FFMC','DMC','DC','ISI','temp','...
# # Implementation of Knuth-Morris-Pratt (KMP) Algorithm # anontated. # # Algorithm creates a text table for use with searches. # # Running Time is O(n+m), where 'n' is length of the searched text (typically large) # and 'm' is the length of pattern (or pattern, typically small). # # Assumptions: length of pattern <= l...
#!/bin/python import sys def capitalize(string): s = string.split(" ") temp = [] for word in s: word = list(word) if len(word) != 0: word[0] = word[0].upper() word = "".join(word) temp.append(word) temp.append(" ") else: ...
import re for i in range(int(raw_input())): uid = raw_input() if bool(re.search(r"([A-Z].*){2}", uid)) and bool(re.search(r"([0-9].*){3}", uid)) and bool(re.search(r"^[a-zA-Z0-9]{10}$", uid)) and not bool(re.search(r"([a-zA-Z0-9]).*\1", uid)): print "Valid" else: print "Invalid"
n = input("Ingrese un número: ") n = int(n) if n < 100: print(False) else: print(True)
def counting_valleys(path): altitude = 0 count_valleys = 0 is_in_valley = False for step in path: # Update altitude if step == "U": altitude += 1 else: altitude -= 1 if altitude < 0 and not is_in_valley: # Check if going into valley ...
# reverse_integer # Input: Number # Output: Number # Side effects: None def reverse_integer(num): str_num = str(num).replace('-', '')[::-1] if num < 0: str_num = '-' + str_num rev_num = int(str_num) if rev_num > 2147483647: return 0 if rev_num < -2147483648: return 0 return rev_num
#program 02 from coursera. hrs = input("Enter hours: ") hours= int(hrs) rate = input("Enter rate: ") rate= float(rate) pay = hours *rate Pay =float(pay)
import turtle as t import random plantArray=[] t.bgcolor("orange") file = open("file.txt","w") def tdefault(): t.speed(0) t.pensize(3) t.hideturtle() def Printmap(): tdefault() t.penup() t.goto(0,-300) t.pendown() t.color(0,1,0) t.begin_fill() t.circle(300...
# The prime factors of 13195 are 5, 7, 13 and 29. # What is the largest prime factor of the number 600851475143 ? def is_prime(number): if number <= 1: return False elif number <= 3: return True elif (number % 2 == 0) or (number % 3 == 0): return False i = 5 while i * i <= ...
fahrenheit = float(input("Digite o valor em Graus Celsius para a Conversão : ")) celsius = 5 * (fahrenheit-32)/9 print ("O seu valor convertido de {} fahrenheit para Celsius foi de : {}".format(fahrenheit,celsius))
# import Tkinter as tk # Python 2 import tkinter as tk # Python 3 root = tk.Tk() # The image must be stored to Tk or it will be garbage collected. root.image = tk.PhotoImage(file='startup.gif') label = tk.Label(root, image=root.image, bg='white') root.overrideredirect(True) root.geometry("+850+250") # root.lift...
def countdown(num): if num <= 0: print('카운트다운을 하려면 0보다 큰 입력이 필요합니다.') else: for i in range(num,0,-1): print(i) countdown(0) countdown(10)
import sys input=sys.stdin.readline words=input().strip() ans=0 for word in words: if word=='A' or word=='B' or word=='C': ans+=3 elif word=='D' or word=='E' or word=='F': ans+=4 elif word=='G' or word=='H' or word=='I': ans+=5 elif word=='J' or word=='K' or word=='L': ans+=6 elif word=='O' or word=...
word=input() if 65<=ord(word)<=90: print('{}(ASCII: {}) => {}(ASCII: {})'.format(word,ord(word),chr(ord(word)+32),ord(word)+32)) elif 97<=ord(word)<=122: #ord string 아스키 10진수로 print('{}(ASCII: {}) => {}(ASCII: {})'.format(word,ord(word),chr(ord(word)-32),ord(word)-32)) else: print(word)
import sys input = sys.stdin.readline def make_it(word): global is_pattern if not word: # 빈 문자열이 됐다면 제대로 된 패턴임 is_pattern = True return if word.startswith("01"): # 01로 시작할 때 make_it(word[2:]) elif word.startswith("100"): # 100으로 시작할 때 i = 3 while i < len(wo...
a=input() dict1={} for i in a: if i in dict1: dict1[i]+=1 else: dict1[i]=1 for key,value in dict1.items(): print("{},{}".format(key,value))
beer = {'하이트': 2000, '카스': 2100, '칭따오': 2500, '하이네켄': 4000, '버드와이저': 500} print(beer,' # 인상 전') beer = {key:value*1.05 for key,value in beer.items()} print(beer,' # 인상 후')
def find(x): if parents[x]==x: return x else: y=find(parents[x]) parents[x]=y return y def union(x,y): root1=find(x) root2=find(y) if root1!=root2: parents[root2]=root1 V,E=map(int,input().split()) dist=[] parents=[i for i in range(V+1)] for _ in range(E): ...
def solution(numbers, hand): answer = '' left=[0]*8 right=[0]*10 left_num=0 right_num=0 for num in numbers: if num==1 or num==4 or num==7: left_num=num answer+='L' elif num==3 or num==6 or num==9: right_num=num answer+='R' e...
# coding=utf8 import copy import random # 冒泡排序 时间复杂度:O(n2) def bubbleSort(arr): pass # 选择排序 时间复杂度:O(n2) def selectSort(arr): pass # 插入排序 时间复杂度:最优O(n) 最差O(n2) 不稳定 def insertSort(arr): if len(arr) < 2 or arr is None: return for i in range(len(arr)): for j in range(i, 0, -1...
#import math module import math #while loop while True: #print the user option print("\nchoose the operation.\n\n0-add\n1-sub\n2-mul\n3-div\n4-modulo\n5-power\n6-square root\n7-log\n8-sine\n9-cosine\n10-tangent") #opiton selection oper=input("\nYour option") #add if oper=="0": v1 = float(input("\nFi...
#!/bin/python3 # Link: https://www.hackerrank.com/challenges/py-if-else/problem import math import os import random import re import sys if __name__ == '__main__': n = int(input().strip()) if (n % 2 == 1): print('Weird') elif (n % 2 == 0 and n in range(2, 6, 1)): print('Not Weird') elif (n % 2 == 0 an...
import hashlib # https://www.hackerrank.com/challenges/python-tuples/problem if __name__ == '__main__': n = int(input()) integer_list = map(int, input().split()) mylist = tuple(integer_list) answer = 0 for x in range(0,n): answer = answer + mylist[x] answers= hash(mylist) print(an...
''' very efficient! but need to cheat, sorted Time Complexity O(log_2 n) Space Complexity O(1) psudocode TODO 或許需要雙指標來跳出死回圈 middle = (len(input) + 1) // 2 if not middle: return false if middle > value_you_want: find the left if middle < value_you_want: find the right if middle == value_you_want: retur...
import os.path def check_file(path): if os.path.isfile(path) == False: print ("File not exist") exit() def init(): f = open('translate.txt', 'r') big_text = f.read() parts = big_text.split('\n') f.close return parts def create_dictionary(parts): words=[] ...
# Create a class Ball. # Ball objects should accept one argument for "ball type" when instantiated. # If no arguments are given, ball objects should instantiate with a "ball type" of "regular." class Ball(object): def __init__(self, argument=None): self.ball_type = "regular" if argument != None: ...
# Створити батьківський клас Figure з методами __init__: ініціалізується колір, # get_color: повертає колір фігури, # info: надає інформацію про фігуру та колір, # від якого наслідуються такі класи як Rectangle, # Square, які мають інформацію про ширину, # висоту фігури, метод square, який знаходить площу фігури. clas...
# Write a program that finds the summation # of every number from 1 to num. # The number will always be a positive integer greater than 0. def summation(num): numbers = [] for i in range(1, num + 1): numbers.append(i) return sum(numbers)
r=float(input("enter radius")) import math area=math.pi*r**2 print(area)
#!/usr/local/bin/python3.9 # -*- coding: utf-8 -*- # write program to convert temperatures to and from celsius,fahrenheit #temperature = int(input("saisir une temperature :") #degre = str(input("indiquer si la temperature rentrée est en C (celsius) ou F (fahrenheit)")) #définition des fonctions de conversi...
menu = {} print("""----order---- 1: Add item 2: Remove item 3: View order 4: Cancel order """) option = int(input("Enter an option: ")) while option != 0: if option == 1: item = input("Enter an item: ") price = int(input("Enter the price: ")) menu[item] = price ...
import argparse import math import marble_path """ Produces the bottom part of a limacon curve, specifically, the loop. The defaults produce a nice looking curve. python generate_limacon.py The hole can be generated as follows: python generate_limacon.py --tube_radius 10.5 --wall_thickness 11 --tube_start_angle 0 ...
import argparse import math import marble_path def calculate_slope_angle(helix_radius, vertical_displacement): """ tube_radius is adjacent, vertical_displacement is opposite returns asin in degrees this is the slope of the ramp """ helix_distance = helix_radius * math.pi * 2 slope_distance ...
sum=0 num=0 while num<15: num1=int(input("enter the number")) sum=sum+num1 num=num+1 print("average is",sum/15)
""" Project Euler Problem 2 Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be: 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ... By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the...
import time import math n = 2000000 counter = 2 sum_of_primes = 0 def is_prime(prime): for i in range(2, int(math.sqrt(prime)) + 1): if prime % i == 0: return False return True t0 = time.time() while True: if is_prime(counter): sum_of_primes += counter if counter == n: ...
import streamlit as st import numpy as np import matplotlib.pyplot as plt import math st.write("# Hello") x = 1000 x """ # Docstrings get rendered as markdown * markdown is simplfied HTML * to get some examples: [visit stackedit.io](https://stackedit.io) """ st.sidebar.header("Sidebar") st.sidebar.selectbox(label = "...
""" Author: Mark Frydenberg Description: text file examples """ REGFILE = "registration.txt" def linebyline(): print("Line By Line") # print all the records in the file within range specified lowAge = int(input("Enter the lower age :")) highAge = int(input("Enter the upper age: ")) # find all ...
# The plot server must be running import numpy as np from bokeh.plotting import * x = np.linspace(-7, 7, 100) y = np.sin(x) # Go to http://localhost:5006/bokeh to view this plot output_server("color example") hold(True) scatter(x,y, tools="pan,zoom,resize") scatter(x,2*y, tools="pan,zoom,resize") scatter(x,3*y, colo...
height = int(input("Please enter your height in inches: ")) age = int(input("Please enter your age in years: ")) can_ride_rollercoaster = height > 48 and age >= 10 if can_ride_rollercoaster: print("Welcome aboard the Iron Dragon") print("Please keep your hands an feed inside the coaster at all times") els...
#!/usr/bin/python ''' Stage II: Needle in a haystack ================================ Next, let’s check your skills for working with collections. We’re going to send you a dictionary with two values and keys. The first value, needle, is a string. The second value, haystack, is an array of strings. You’re going to tel...
if input("Is de kaas geel? (J/N) : ") == 'J': if input("zitten er gaten in? (J/N) : ") == 'J': if input("Is de kaas blechelijk duur? (J/N) : ") == 'J': print("Emmenthaler") else: print("Leerdammer") else: if input("Is de kaas hard als steen? (J/N) : ") == 'J': ...
class AdvancedArithmetic(object): def divisorSum(n): raise NotImplementedError class Calculator(AdvancedArithmetic): def divisorSum(self, n): i = 1 total = 0 while i <= n: if (n % i == 0): total += i i += 1 return total # n = int...
#!/usr/bin/env python3 ''' input: n, i, pv, pmt, fv calc: Financial functions return: dict and json ''' # -*- coding: utf-8 -*- # Code styled according to pycodestyle # Code parsed, checked possible errors according to pyflakes and pylint import locale import json locale.setlocale(locale.LC_ALL, 'pt_BR.U...
from Command import Command from utils.Direction import Direction class DirectionHelper: """ Helper class that helps robot turn left or right """ @classmethod def turn(cls, current_direction: Direction, instruction: tuple[Command, int]) -> Direction: """ It uses robot`s current dir...
import random sc=0 ch=1 print(""" WELCOME TO THE FIRST EVER GAME BY SWAPNIL GARG, THIS IS THE ADDITION QUIZ, YOU CAN PLAY A GAME OF YOUR PREFERRED LENGTH AND VIEW YOUR FINAL SCORE AT THE END""") while ch==1: n=int(input("How long of a game you wish to play?")) r=0 while r<n: x=rando...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Fri Nov 16 18:17:04 2018 @author: David """ #%% #from functools import reduce #def create_product(name,price): # return {"name":name, "price":price} def create_product(name,price): return {"name":name, "price":price} def print_cart(cart): pri...
var=[40,12,60,70,4,11] z=var[0] for x in var: if z > x : z=x print('The string is var:', z)
import matplotlib.pyplot as plt from pandas import read_csv import os # Load data data_path = os.path.join(os.getcwd(), "data/blood-pressure.txt") dataset = read_csv(data_path, delim_whitespace=True) # We have 30 entries in our dataset and four features. The first feature is the ID of the entry. # The second feature ...
import pandas as pd # Define function for cleaning dataframe def clean_lineups(df): """Removes the posistions from each of the lineups dataframes in order to better combine with the names from the batting/pitching stats dataframes""" positions = ['1','2','3','4','5','6','7','8','9'] pos_count = 0 ...
i=0 while i<10: if i%2==0: i=i+1 continue else: print(i) i=i+1:
import random correct = 'you guessed correctly!' too_low = 'too low' too_high = 'too high' min_range = 1 max_range = 100 def configure_range(): '''Set the high and low values for the random number''' while True: try: low = 0 while low <= min_range or low >= max_range: ...
times = input("How many times do I have to tell you?") times = int(times) for times in range(times): print(f"time {times + 1}: CLEAN UP YOUR ROOM!!!")
#String Formatting name = "John" age = 23 print("%s is %d years old." % (name, age)) print ("%f" % age)
import re import sys def load_file(filepath): with open(filepath, "r", encoding="utf-8") as file: # first line is text text = file.readline().strip() # second line is word bank word_bank = file.readline().strip().split(" ") return text, word_bank def cut_words(te...
import re import sys class Student: """ representing a single student with references to their wished packages """ def __init__(self, number, wishes): self.number = number # tuple with one package number per wish (1st wish, 2nd wish...) self.wishes = wishes de...
from typing import Iterable, List, Tuple FORMAT = """ followed: {} navigated: {} """ def solve(instream): instructions = read(instream) return manhattan(follow(instructions)), manhattan(navigate(instructions)) def read(source: Iterable[str]) -> List[Tuple[str, int]]: return [(arg[0], int(arg[1:])) for...
n=input() sum=0 for i in str(n): x=int(i) sum=sum+(x*x) print sum
number=int(raw_input()) sum=0 for i in range(number+1): sum+=i print sum
# Define your "TreeNode" Python class below class TreeNode: def __init__(self, value): self.value = value self.children = [] def add_child(self, child_node): print("Adding " + child_node.value) self.children.append(child_node) root = TreeNode("I am Root") child = TreeNode("A wee sappling") root.ad...
class MinHeap: def __init__(self): self.heap_list = [None] self.count = 0 # HEAP HELPER METHODS # DO NOT CHANGE! def parent_idx(self, idx): return idx // 2 def left_child_idx(self, idx): return idx * 2 def right_child_idx(self, idx): return idx * 2 + 1 # END OF HEAP HELPER METHODS ...
# TODO # input: total, per_page, page # output: # a range of item numbers to display for each page (showing 1-10, 10-20, ..etc) # has next method (whether the next page exists) # has previous method (whether the previous page exists) import math from math import ceil class Pagination(): def __init__(self, total,...
import random import re class GameDie: @classmethod def roll(cls, name, args: tuple): if len(args) == 0: count = 1 sides = 20 elif len(args) == 1: count, sides = cls.parse_dice(args[0]) else: return "Sorry, combining dice is not implemen...
print ("____________________") print ("Rock, Paper, Scissors, account setup") print ("____________________") while True: username = raw_input ("Pick a username: ") password = raw_input ("Pick a password: ") password_confirm = raw_input ("please confirm your password: ") if password != passwo...
def validate_tiny_int(val): return val >= 0 and val <= 255 def validate_val(val): try: return isinstance(int(val),int)#aca valida si es una instancia de la clase int #en python todo es un objeto #se intenta convertir un string a entero con int(val...
''' 什么是队列,队列是一系列元素的集合,新元素的加入在队列的一端,这一端叫做“队尾(rear)” 已有元素的移除发生在队列的另一端,叫做“队首(front)” --------------------------------------------- rear front --------------------------------------------- 特点:先进先出(FIFO) 抽象数据类型(ADT) Queue():创建一个空队列对象...
class TitleToNumber(object): def titleToNumber(self, s): """ :type s: str :rtype: int """ slist = list(s) l = len(s) num = 0 for a in slist: num *= 26 num += ord(a) - 64 return num if __name__ == '__main__': s = ...
class IntersectionOfTwoArrays(object): def intersection(self, nums1, nums2): """ :type nums1: List[int] :type nums2: List[int] :rtype: List[int] """ s1 = set(nums1) s2 = set(nums2) ss = s1 & s2 return list(ss) if __name__ == '__main__': n...
class Fib(object): def __init__(self): self.a=0 self.b=1 def __str__(self): return str(self.a) __repr__ = __str__ def __iter__(self): return self def __next__(self): self.a, self.b = self.b, self.a + self.b # 计算下一个值 return self.a # 返回下一个值 d...
dl320@soetcse:~/udaya$ python3 add6.py enter the value of a56 enter the value of b65 enter the value of c67 c is greater than b dl320@soetcse:~/udaya$ python3 add6.py enter the value of a01 enter the value of b69 enter the value of c96 c is greater than b dl320@soetcse:~/udaya$ python3 add6.py enter the value of a87...
def fibonacci(n): fib_n = [0, 1] for i in range(2, n + 1): fib_n[0], fib_n[1] = fib_n[1], fib_n[0] + fib_n[1] return fib_n[1] n = int(input()) print(fibonacci(n))
import sqlite3 # conectando... conn = sqlite3.connect('clientes.db') # definindo um cursor cursor = conn.cursor() # criando a tabela (schema) cursor.execute("""CREATE TABLE IF NOT EXISTS clientes ( id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, nome TEXT NOT NULL, idade INTEGER, cpf VARCHAR(11) NOT NULL, email T...
import os def treewalk(root, nspaces=0): # nspaces : aantal spaties dat ingesprongen wordt a = os.listdir(root) for f in a: print(' '*nspaces,end = '') if os.path.isdir(root + '/' + f): print('[' + f + ']') treewalk(root + '/' + f,nspaces+3) # recursieve aanroep ...
a = [1,99,2,98,3,97] print(a[-1]) print(a[-3]) print() a1 = [1,2,3] a2 = [101,102,103] print(a1+a2) print() a1 = [1,2,3] a2 = [101,102,103] print(4*a1) print(a2*3) print() n = 25 b = [0]*n print(b) print() a = [1,2,3,4,5,6,7,8] del a[6] ; print(a) # verwijder het zevende element del a[1:3] ; print(a) # verwijder ...
class myqueue(list): def __init__(self,a=[]): list.__init__(self,a) def dequeue(self): return self.pop(0) def enqueue(self,x): self.append(x) class Vertex: def __init__(self, data): self.data = data def __repr__(self): # voor afdrukken ...
""" Given an integer array nums, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum. Example: Input: [-2,1,-3,4,-1,2,1,-5,4], Output: 6 Explanation: [4,-1,2,1] has the largest sum = 6. """ class Solution(object): def maxSubArray(self, nums): """ ...
def get(a,l,r): # 递归(分治法) if l==r: return {'isum':a[l],'lsum':a[l],'rsum':a[l],'msum':a[l]} m = int((l+r)/2) isum = get(a,l,m)['isum'] + get(a,m+1,r)['isum'] # isum为[l,r]的区间和 # lsum为[l,r]内以l为左端点的最大子段和 lsum = max(get(a,l,m)['lsum'] , get(a,l,m)['isum'] + get(a,m+1,r)['lsum']) # rsum为...
""" Given a string containing just the characters '(' and ')', find the length of the longest valid (well-formed) parentheses substring. Ex_1: Input: "(()" Output: 2 Explanation: The longest valid parentheses substring is "()" Ex_2: Input: ")()())" Output: 4 Explanation: The longest valid parentheses substring is "()()...
""" Given a roman numeral, convert it to an integer. Input is guaranteed to be within the range from 1 to 3999. Symbol Value I 1 V 5 X 10 L 50 C 100 D 500 M 1000 Note:There are six instances where subtraction is used: I can be pla...
""" Given two binary trees, write a function to check if they are the same or not. Two binary trees are considered the same if they are structurally identical and the nodes have the same value. Example 1: Input: 1 1 / \ / \ 2 3 2 3 [1,2,3], [1,2,3] Output: true Ex...
""" Given preorder and inorder traversal of a tree, construct the binary tree. Note: You may assume that duplicates do not exist in the tree. For example, given preorder = [3,9,20,15,7] inorder = [9,3,15,20,7] Return the following binary tree: 3 / \ 9 20 / \ 15 7 """ # Definition for a binary tree...
""" Implement next permutation, which rearranges numbers into the lexicographically next greater permutation of numbers. If such arrangement is not possible, it must rearrange it as the lowest possible order (ie, sorted in ascending order). The replacement must be in-place and use only constant extra memory. Here are s...
#fizzbuzz def fizzbuzz(num, i, j): for n in range(1,num+1): result = "" if n%i == 0: result = "fizz" if n%j == 0: result += "buzz" if not result: result = n print(result) def main(): n = int(input("a number: ")) n1 = int(input("a number less than {} :".format(n))) n2 = int(input("a number less...
""" 1155. Number of Dice Rolls With Target Sum You have d dice, and each die has f faces numbered 1, 2, ..., f. Return the number of possible ways (out of fd total ways) modulo 10^9 + 7 to roll the dice so the sum of the face up numbers equals target. Example 1: Input: d = 1, f = 6, target = 3 Output: 1 Explanation: ...
""" Merge Sort ---------- Uses divide and conquer to recursively divide and sort the list Time Complexity: O(n log n) Space Complexity: O(n) Auxiliary """ def merge(left, right): """Compares and Merges arrays.""" left_index, right_index = 0, 0 result = [] while left_index < l...
import random board = {} end = False win_commbinations = ((0, 1, 2), (3, 4, 5), (6, 7, 8), (0, 3, 6), (1, 4, 7), (2, 5, 8), (0, 4, 8), (2, 4, 6)) def board(): print(' | | ') #print(' ' + board[7] + ' | ' + board[8] + ' | ' + board[9]) print(' | | ') print('------------------') print(' | ...
#Largest Continuous Sum #Given an array of integers (positive and negative) find the largest continuous sum. def largestcontsum(arr): if len(arr) == 0: return currentSum = maxSum = int(arr[0]) print currentSum, maxSum for num in arr[1:]: print num, currentSum + num, currentSum currentSum = max(num, curr...
# print tuple elements a = [('a',4), ('b',9), ('c',16), ('d', 25)] for k, v in a: print "%s has value %s" % (k,v)
## SHUFFLING A DECK OF CARDS ## A deck of cards has 13 cards each of 4 suits: heart(♥), spade(♠), diamond(♦), club(♣). ## THOUGHT PROCESS: Construct an unshuffled deck by using two lists, one for suits, another for cardValues ## Shuffle the deck by iterating over all cards one by one using their indexes, and swapping...
def bubbleSort(array): tamanhoDoArray = len(array) - 1 for i in range( tamanhoDoArray ): for j in range( tamanhoDoArray - i ): if array[j] < array[j + 1]: array[j], array[j + 1] = array[j + 1], array[j] return array array = [2, 1, 5, 4, 3] bubbleSort(array)
# -*- coding: utf-8 -*- """ Created on Wed Jun 13 09:06:01 2018 @author: Acer """ a=[1,2,3,4,5,6,7,8,9,10] sum = 0 n = len(a) #ความยาวใน array number = 1 for i in range (sum,n): #i คือตัวที่ อยู่ใน array ไล่ไปจนครบจำนวน n if number < len(a) : #จำนวนลูป น้อยกว่าจำนวนใน array sum = sum + a[...