text
stringlengths
37
1.41M
''' for i in range(6): print(i) if i > 2: print("i is bigger than 2") print('Done iterating') print('All done') ''' for j in range(7): if j >= 4.5: print('Hooray! You are a first class student') elif j >= 3.5: print('You have second class upper division') elif j >= 2.5: print('You have sec...
array = [5, 7, 9, 0, 3, 1, 6, 2, 4, 8] def quick_sort(array, start, end): if start >= end: # 원소가 1개이면 종료 return pivot = start # 피벗, 시작요소 left = start + 1 right = end while left <= right: # 왼쪽과 오른쪽이 교차 되면 종료 # 큰 데이터 찾으면 종료 while left <= end and array[left] <= array[piv...
from search.problem import Problem class Pawns: def __init__(self, world): self.clients = [] self.world = world self.index = 0 def __iter__(self): return self def __next__(self): try: result = self.clients[self.index] except IndexError: ...
class userinput: def __init__(self): self.command = [] def userCommand(self): i = input("Enter Your Command :") self.command.append(i) def checkid(self): i = self.command if len(i[0]) ==5: if i[0][0].isdigit() == True: if int(i[0]...
#!/usr/bin/env python3 # -*- coding:utf-8 -*- # 繳交日期:2016.10.17 # 作業內容: # 1. 請閱讀 Wikipedia 維基百科 IEEE754 條目 (https://zh.wikipedia.org/wiki/IEEE_754) # 2. 請試玩 http://armorgames.com/play/17826/logical-element # 3. 請利用以下空白範本設計一支程式。程式可輸入一段字串,並自動計算出字串中包括空白字元出現的機率。 # 並由高排到低。 if __name__== "__main...
from abc import ABCMeta, abstractmethod class World(metaclass=ABCMeta): def __init__(self, name): self.name = name self.children = [] @abstractmethod def show(self): pass def add(self, obj): self.children.append(obj) def remove(self, obj): self.children....
#!/usr/bin/env python """ CLI timer for the Rubik's Cube Usage: cubetimer.py [-hbs] [-p TIME] [-f FILE] cubetimer.py [-hs] [-a FILE] Options: -h, --help print this help and exit -a FILE return the average time on 5 on in competition -b use bell -f FILE store the time in FIL...
class ShapeArea(): pi=3.142 def __init__(self): pass def circle(self): radius=input("radius=") return int(radius)**2*self.pi def triangle(self): length=input("length=") width=input("width=") return int(length)*int(width)/2 def rectangle(se...
#--------------------------------------------------------- #define odd_number function & return statement def prime_number(start_point=0,end_point=1,step=1): prime_number=[] for number in range(start_point,end_point,step): if number%2!=0 and number%3!=0 and number%5!=0 and number%7!=0 and number%9!=0 or...
from Module_dir.ClassShapeAreaCalculator2_OOP import ShapeArea as SA class Circle(SA): #we can inherit multiple class like class Car(Vehicle,Xxxx,Yyyy) pass class MathCalc(SA): def circle_perimeter(self): radius=input("radius=") return float(radius)*self.pi*2 return self.circle(int(ra...
#Area of a shape - Algorithm #1. Great User #2. Present options #3. Evaluate options #4. Collect values based on selected option #5. Evaluate values #6. Calculate #7. Throw result #1. Great User print ("Hello, Welcome to our page") #2. Present options positive_response=["Y","Yes","yes","y"] response=input ("Do you wa...
a = "Hola,Mundo" print(len(a)) #Longitud de una cadena #print(a[1]) for x in "pepe": #Recorrer una cadena print(x)
# La variable creada dentro de la funcion es local solo se puede usar dentro de la funcion. x = "asombroso" def myfunc(): x = "fantastico" print("Python es "+x) myfunc() print("Python es "+x)
import random import pygame def make_2d_array_of(rows,cols,value): """creates and returns a 2d array filled with 'value' that can be indexed with [r][c]. Typically rows correspond to the "y" direction and cols to the "x" direction. be careful with indexes. """ return [[value for i in range(cols)] for ...
import pygame import pygame.locals as pl pygame.init() from vgd import colors screen_width = 800 screen_height = 600 main_surface = pygame.display.set_mode((screen_width, screen_height)) # Helper functions def create_square_centered_at(center, size, color): mid_x, mid_y = center left = mid_x - size / 2 ...
""" 3. Write a function that reverses a string. The input string is given as an array of characters (Please Do not use the default function for the reverse) Input: s = ["h","e","l","l","o"] Output: ["o","l","l","e","h"] """ """ METHOD-1 """ class Reverse: def reverseList(self, arr: list): # Function to reverse ...
""" Write a function called generate_matrixthat takes two positional arguments – m and n – and a keyword argument default that specifies the value for each position. It should use a nested list comprehension to generate a list of lists with the given dimensions. If default is provided, each position should have the gi...
class PetShop: def __init__(self, name, pets, total_cash): self.name = name self.pets = pets self.total_cash = total_cash # To fulfill test_pet_shop_pets_sold_starts_at_0 from pet_shop_test.py # It is property self.pets_sold = 0 def stock_count(self): ret...
# Question Statement:- # Pooja would like to withdraw X $US from an ATM. The cash machine will only accept the transaction if X is a multiple of 5, # and Pooja's account balance has enough cash to perform the withdrawal transaction (including bank charges). # For each successful withdrawal the bank charges 0.50 $US. ...
# Question:- # Shivam is the youngest programmer in the world, he is just 12 years old. Shivam is learning programming and today he is writing his first program. # Program is very simple, given two integers A and B, write a program to add these two numbers. # Input:- # The first line contains an integer T, th...
# Question: # The office where the Chef works, has two guards who count how many times a person enters into the office building. Though the duty of a guard # is 24 hours in a day, sometimes they fall asleep during their duty and do not track the entry of a person in the office building. But one good # thing is ...
import copy import time import levels class Game: # Constructor def __init__(self): board = self.chooseLevel() self.board = self.createBoard(board) self.size = len(self.board) self.solution = self.createSolution() algorithm = self.chooseAlg() ...
import tkinter as tk import math import time class MyFrame(tk.Frame): def __init__(self, master=None): super().__init__(master) self.size = 200 self.clock = tk.Canvas(self, width=self.size, height=self.size, background="white") self.clock.create_oval...
# Normal Calculator using Function while True: num1 = int(input("Enter first number :")) num2 = int(input("Enter second number :")) print(""" Press + for Addition Press - for subtraction Press * for Multiplication Press / for Division """) choice = input("Enter the operator: ") def calc(digit1, d...
#from mpltoolkits_basemap import Basemap import matplotlib.pyplot as plt import numpy as np # Numpy array is a gift to Data scientists and statisticians # If you already have the data in hand and it is small, you can directly create a numpy array # If it is obtained dynamically, the efficient way is to create a list ...
""" Environment.py Represents an environment (world state) for the Pet Detective game. """ from prog2.UniformCostAgent import UniformCostAgent __author__ = "Chris Campell" __version__ = "9/19/2017" class Environment: puzzle_id = None game_board = None # agent_location measured from top left (matrix nota...
""" Convert an input CSV file into a JSON file 1st line in the CSV is used as the keys for the JSON/dict """ def main(): csv_filename = input("Enter the CSV filename: ") json_filename = input("Enter the JSON filename: ") csv2json(csv_filename, json_filename) print("JSON saved to the file '{}'".format(json_filenam...
""" Module: ex04 Author: Vinod Kumar Kayartaya <vinod@vinod.co> Version: 1.0 """ # Working with user defined function # define the function def say_hello(name="World", char="*"): """ prints a decorated greeting message Parameters: 1 -> a name 2 -> a character symbol """ print(char*50) print(char*3, end="")...
import os ,sys ### a script that reads a batch file then outputs a shellcode of the batch file ## a function to output the shell code to txt file with the name shellcode.txt def write_shellcode(): try: if sys.argv[2]=="txt": output = open("shellcode.txt","w") output.write(shellcode)...
import tkinter as tk # 計算機能のための変数とイベント用の関数定義 # 2 項演算のモデル # 入力中の数字 current_number = 0 # 第一項 first_term = 0 # 第二項 second_term = 0 # 結果 result = 0 def do_plus(): "+ キーが押されたときの計算動作 , 第一項の設定と入力中の数字のクリア " global current_number global first_term first_term = current_number current_number = 0 def do_...
# -*- coding: utf-8 -*- """ Created on Sun Sep 5 00:21:59 2021 @author: Admin """ def oraliq(min,max,step = 1): ans=[] while min<max: ans.append(min) min+=step return ans print(oraliq(-51, 60,20))
N = int(input()) S = str(input()) logo = "b" cnt = 0 def can_make(logo): if S == logo: print(cnt) exit() if S == logo: print(0) exit() while len(logo) <= len(S): cnt += 1 if cnt % 3 == 1: logo = "a" + logo + "c" can_make(logo) elif cnt % 3 == 2: logo =...
""" Binghamton ACM February 7th, 2017 A python solution to the problem posed here: https://www.hackerrank.com/contests/buacm/challenges/maximum-in-a-unimodal-array/ """ # Input parsing length = int(input()) arr = [int(x) for x in input().split(' ')] # Binary search function to find max # Takes in the array, start...
#! /usr/bin/env python """ lossfunctionlib.py Loss Function Library Module -- Contains loss function for SVM and Softmax Based on CS231n course by Andrej Karpathy Created by Jeremy Smith on 2016-04-07 University of California, Berkeley j-smith@berkeley.edu """ from __future__ import division import logging import ...
print("LIST") fruitlist = ["apple", "banana", "cherry","grapes","mango","orange"]#display list print(fruitlist) fruitlist = ["apple", "banana", "cherry","grapes","mango","orange"]#get the 1st element print(fruitlist[1]) fruitlist = ["apple", "banana", "cherry","grapes","mango","orange"]#get the last elemen...
class Employee: id = 10 name = "KEERTHANA" officename="qrs" def display (self): print("EMPLOYEE ID :",self.id) print("EMPLOYEE NAME:",self.name) print("OFFICE NAME:",self.officename) # Creating a emp instance of Employee class emp = Employee() emp.displ...
class father():#base class F_name="vijaya kumar" Age=48 class mother():# base class M_name="rani" Age=48 class son(father,mother):#child class Son_name="vignesh" Age=24 obj=son() print(" FATHER NAME IS:",obj.F_name) print(" FATHER AGE IS:",obj.Age) print("MOTHER NAME IS:",obj.M_na...
## ##StingValue1=input("ENTER ANY STRING") ##StringValue=int(StingValue1) ##count = 0 ##for letter in StringValue: ## if(letter == 'l'): ## count += 1 ##print(count,'letters found') count = 0 for letter in 'Multidimentional array': if(letter == 'i'): count += 1 print(count,'letters fou...
s=input("") n=len(s) a=0 while(a<n): b=a+1; if b<n: print(s[b],end="") print(s[a],end="") a=a+2
n= int(input("")) l=int(input("")) if l<0 or n<0: print("enter positive integer") else: s=[] for a in range(n): b=int(input("")) s.append(b) b=0 while(b<l): d=s[0] for a in range(1,n): c=s[a] s[a]=d d=c s[0]=d b=b+1 for a in s: print(a,end=" ")
# Enter your code here. Read input from STDIN. Print output to STDOUT from collections import deque d = deque() for i in range(int(input())): method_name, *value = input().split() if not value: _ = getattr(d, method_name)() else: getattr(d, method_name)(value) print(' '.join(r for v in d f...
# Enter your code here. Read input from STDIN. Print output to STDOUT n = input() values = list(input().split()) is_palindromic = any(n[::-1] == n for n in values) is_positive = all(int(i) > 0 for i in values) print(is_palindromic & is_positive)
# Enter your code here. Read input from STDIN. Print output to STDOUT from collections import namedtuple n = int(input()) Student = namedtuple("Student", input().split()) sum = 0 for i in range(n): line = input().split() student = Student(*line) sum += int(student.MARKS) print(sum/n)
#!/usr/bin/env python # coding=utf-8 import this # 元组元素不可重新赋值,其他用法和列表list一样 tuple = ("c", 1, 2.0, ["c", 2]) print(tuple) print(tuple * 2) l = list(tuple) print(l[0:-1]) dictionary = {} dictionary['n'] = 'nevermore' if 'f' not in dictionary: print(False)
#!/usr/bin/env python # coding: utf-8 # In[18]: #Question: Create a list and swap the second half of the list with the first half of the list and print this list on the screen List=[1,2,3,4,5,6,7,8,9,10] Length=len(List) half=int(Length/2) Firsthalf=List[:half] Secondhalf=List[half:] Swapped_List=[Secondhalf+Fi...
def sieve(end): primes = [True] * (end+1) primes[0] = False primes[1] = False for i in range(2, end+1): if primes[i]: cur = i while cur <= end: cur += i if cur <= end: primes[cur] = False return primes def quadrati...
""" Name: Chris Cook Email: c.w.cook@live.com Assignment: Program 01 - Easy Cipher Due: 03 Oct @ 1:00pm """ """ @ Name: ShiftCipher @ Description: Simple class to do a shift cipher """ class ShiftCipher(object): """ @ Name: __init__ @ Description: @ Params: None """ def __init__(self): self.plainTe...
def LetterCapitalize(str): return " ".join(word.capitalize() for word in str.split()) print LetterCapitalize(raw_input())
n = int(input("Podaj maksymalna wartosc permutacji: ")) T = [[1]] def list_print(T): for i in range(0, len(T)): print(T[i]) for k in range(2, n+1): #licznik max wartości permutacji pom = 0 # zmienna pomocnicza do wstawiania elementów for i in range (0, len(T)): #pętla po wszystkich elemen...
n = int(input("Wprowadź n - ilość elementów zbioru: ")) k = int(input("Wprowadź k - ilość cykli: ")) #Dodatkowa funkcja wypisująca wszystkie możliwości od s(0,0) #do s(n, k), gdzie n >= k #def sPrint(s): # for i in range(0, len(s)): # for j in range(0,len(s[i])): # print(s[i][j], end=" ") # ...
n = int(input("Podaj liczbe n (maksymalna wartosc elementu w podzbiorze): ")) k = int(input("Podaj k (ilość elementow w podzbiorze): ")) def SuperPrint(n,k, a): for i in range(0, n+1): print(A[i]) A = [] P = [] POM = [] for i in range (0, n+1): A.append([ [[]] for j in range(0,i+1) ]) fo...
# You are given two linked lists representing two non-negative numbers. # The digits are stored in reverse order and # each of their nodes contain a single digit. # Add the two numbers and return it as a linked list. class ListNode(object): def __init__(self, x): self.val = x self.next = None d...
lst = [1,2,3,4,5] print(lst) print(type(lst)) for i in lst: print(lst[:i]) x=list(range(1,11)) print(x) print(x[:5]) print(x[-5:]) print('index increased by 2') print(x[::2]) print(x[1::2]) a = ['a', 'b', 'c'] print(a) b=[10,20,a,5,True] print(b[0]) print(b[2]) print(b[2][0]) print(b[2][1:]) print(b[3:]) num...
height = int(input('height: ')) starCount = 0 for x in range(1, height+1): print("* " * x) starCount += x print(starCount)
string = "abc" print(len(string)) for s in string : print(s) lstset = [1,2,3,4,5] for e in lstset: print('e: ', e) i=0 while i<10: i +=1 if i==3: continue if i==6: break print(i, end=' ') num1 = range(10) print('num1: ', num1) num2 = range(1, 10) print...
import random def coin(n): result=[] for i in range(n): r=random.randint(0,1) if(r==1): result.append(1) else: result.append(0) return result print(coin(10)) def montaCoin(n): cnt=0 for i in range(n): cnt += coin(1)[0] result=cnt/n ret...
class Employee: name=None pay=0 def __init__(self, name): self.name=name def pay_calc(self): pass class Permanent(Employee): def __init__(self, name): super().__init__(name) def pay_calc(self, base, bonus): self.pay=base+bonus print('total: ', format(sel...
print("hi") def ayesha(): print("nice girl") ayesha() class Emp: def __init__(self,eid,ename,eage,esal,eaddress='Pune'): self.empId = eid self.empName = ename self.empAge = eage self.empSalary = esal self.empAddress = eaddress def __str__(self): retur...
import math class Coordinate(object): def __init__(self,x,y): self.x = x self.y = y def getDistance(self, point): r = ((self.x - point.x) ** 2 + (self.y - point.y) ** 2) ** 0.5 return r def getAngle(self, point): theta = math.atan2((point.y - self.y) , (point.x - ...
#!/usr/bin/python3.3 import math #answer math.factorial(20) answer = 2*3*4*5*6*7*11*13*17*19 divisors = [20,19,18,17,16,15,14,13,12,11,10,9,8,7,6,5,4,3,2] #primes 1 2 3 5 7 # 11 13 17 19 #total 1 2 3 4 5 6 7 8 9 10 # 11 12 13 14 15 16 17 18 19 20 def divisible(n): ...
from sys import stdin from heapq import heappop,heappush delta = [(-1,0),(0,-1),(0,1),(1,0)] ## derecha izquierda arriba abajo fronteras INF = float('inf') #Carlos Saul Arboleda # 0061863 #Codigo sssp del profesor Camilo Rocha # Se tuvo que preguntar como hacer la entrada a Juan sebastian Rivera y aconsejo como ignora...
""" It's worthwhile at this point to explain that Big O can be used to determine three cases with an algorithm: * Best Case: In the telephone book search, the best case is that we find the name in one comparison. This is O(1) or constant complexity; * Expected Case: As discussed above this is ...
""" Unique Characters in String Problem Given a string,determine if it is comprised of all unique characters. For example, the string 'abcde' has all unique characters and should return True. The string 'aabcde' contains duplicate characters and should return false. Solution We'll show two possible solutions, one usin...
#Runtime: 68 ms, faster than 93.66% of Python3 online submissions for Longest Substring Without Repeating Characters. #Memory Usage: 13.4 MB, less than 5.05% of Python3 online submissions for Longest Substring Without Repeating Characters. class Solution: def lengthOfLongestSubstring(self, s: str) -> int: m...
import re def get_matching_words(regex): words = ["aimlessness", "assassin", "baby", "beekeeper", "belladonna", "cannonball", "crybaby", "denver", "embraceable", "facetious", "flashbulb", "gaslight", "hobgoblin", "iconoclast", "issue", "kebab", "kilo", "laundered", "mattress", "millennia", "natural", "obsessive", "...
print("Advent of Code - Day 3") f = open("input3-1", "r").read() wire1_moves = f.split(',') f = open("input3-2", "r").read() wire2_moves = f.split(',') from math import* def manhattan_distance(x,y): # distance += abs(x_value - x_goal) + abs(y_value - y_goal) return sum(abs(a-b) for a,b in zip(x,y)) # Tes...
print("Advent of Code - Day 6") f = open("input6", "r") orbits = [] for x in f: orbits.append(x) test_orbits = [ 'COM)B', 'B)C', 'C)D', 'D)E', 'E)F', 'B)G', 'G)H', 'D)I', 'E)J', 'J)K', 'K)L', ] class Node: def __init__(self, identifier): self.id = identifi...
import random """ Generates random words from a dictionary, depending on the selected difficulty (increasing from 1 to 5). Give the player 4 chances to select the correct password, otherwise they lose the game. """ def falloutHacking(): # # Recieve the input data, determine length of string # number = ...
# Homework hs def update(n): if (n % 2 == 0): n = n // 2 return(n) print(n) else: n = 3*n + 1 return(n) print(n) def update2(n): x = 1 while (n != 1): n = update(n) print(n) x = x + 1 print(x) def hs(n): if (n != 1): ...
class LinkedList: class Node: def __init__(self, value): self.val = value self.next = None def __init__(self): self.__head = None def add(self, value): if self.__head is None: self.__head = LinkedList.Node(value) else: p = sel...
from threading import Thread from time import sleep class Lock: def __init__(self): self.flag = 0 def acquire(self): while(self.__compare_and_swap(0, 1) == 1): continue def release(self): self.flag = 0 # overwrite the existing value only if # it is equal to th...
def is_sorted(a, i): if i + 1 == len(a): return True return a[i] <= a[i+1] and is_sorted(a, i + 1) assert(not is_sorted([1,2,3,5,4], 0)) assert(is_sorted([1,2,3,4,5,], 0)) assert(not is_sorted([1,4,3], 0)) assert(is_sorted([1], 0)) assert(is_sorted([1,2], 0)) assert(not is_sorted([2,1,], 0))
from threading import Thread from time import sleep class Lock: def __init__(self): self.ticket = 0 self.turn = 0 def acquire(self): my_turn = self.__fetch_and_add() while self.turn != my_turn: continue def release(self): self.turn += 1 # just incr...
""" Classes for char-to-int mapping and int-to-int mapping. :Author: James Taylor (james@bx.psu.edu) The char-to-int mapping can be used to translate a list of strings over some alphabet to a single int array (example for encoding a multiple sequence alignment). The int-to-int mapping is particularly useful for crea...
import sqlite3 ''' Creates a database file is one does not already exist. ''' def createTable(): conn = sqlite3.connect('downloaded.db') c = conn.cursor() c.execute('CREATE TABLE IF NOT EXISTS posts (perma TEXT NOT NULL UNIQUE, title TEXT, udate TEXT, author TEXT, url TEXT, PRIMARY KEY (perma))') c.clo...
myNames = 'Bridget', 'Britani', 'Jay', 'Jessica' for name in myNames: for x in range(1,4): # print "Hi {}! ".format(x) % name * x print "Hi %s! " % name * x # expand to tuple, dict, and strings.
#!/usr/bin/python number = raw_input('Pick number between 1-10\n') def TEST(arg): try: number = int(arg) except ValueError: print "Sorry {} is not a number." .format(arg) else: if 0 < number < 11: pass else: print '{} is out of range.'.format(arg) print "you entered {}!" .format(a...
TheBeatles = ['John', 'Paul', 'George', 'Ringo'] Wings = ['Paul'] for Beatle in TheBeatles: if Beatle in Wings: continue print Beatle
# attempt # Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode: num1 = 0 num2 = 0 multiplier = 1 while l1:...
#https://en.wikipedia.org/wiki/Multi-key_quicksort def quick3Sort(array): """ algorithm sort(a : array of string, d : integer) is if length(a) ≤ 1 or d ≥ K then return p := pivot(a, d) i, j := partition(a, d, p) (Note a simultaneous assignment of two variables.) sort(a[...
import math print('Task 4') a = float(input("Enter parametr:")) print() Strg = (a ** 2) * math.sqrt(3/4) rcrc = a * math.sqrt(3/6) Scrc = math.pi * (rcrc ** 2) if Strg >= Scrc: print("A) Success: Triangle Square >= Circle Square ") else: print("A) Error: Triangle Square < Circle Square ") rcrc = a * math.sqrt(3...
print('Task 2') print() a = [] b = [] for i in range(0,10): a.append(int(input('Enter number: '))) one = a[i]//10 two = a[i]%10 b.append(one - two) print(b)
def inp(a,n,m): for i in range(0,n): a.append([]) for j in range(0,m): a[i].append(int(input("Enter matrix number: "))) def outp(a,n,m): sum = 0 print('Matrix') for i in range(0,n): for j in range(0,m): print(a[i][j],end=' ') if i==1: ...
print('Task 3') print() k = int(input('Enter k: ')) pr = 1 sm = 0 for j in range(-3,k): pr = pr * ((j+2)*j)/j-3 for i in range(j,k+5): sm = sm + (i+5)/((i-11)-3.5*i) print('p: ',pr) print('s: ',sm) print('Result: ',pr*sm)
# 35. Search Insert Position # # Given a sorted array of distinct integers and a target value, return the index if the target is found. If not, # return the index where it would be if it were inserted in order. def binarySearch(arr, ele): low = 0 high = len(arr) - 1 while low <= high: mid = (low + ...
# 48. Rotate Image # LeetCode Solution class Solution: def rotate(self, matrix: List[List[int]]) -> None: """ Do not return anything, modify matrix in-place instead. """ n=len(matrix[0]) for i in range(n//2 + n%2): for j in range(n//2): tmp=matrix...
import os class Delete(object): #delete metods for file type objects def __init__(self, file): self.file = file def interactive(self): #interactive delete input = raw_input('Do you really want to delete %s? [N]/Y: ' % self.file) if input.upper...
from math import sqrt from sys import stdout h = 0 leap =1 for i in range(101,201): k = int(sqrt(i+1)) for j in range(2,k+1): if i % j == 0: leap = 0 break if leap == 1: print '%-4d' % i h += 1 if h%10 ==0: print '' ...
def fact(i): sum = 0 if i==0 : sum =1 else: sum = i * fact(i-1) return sum for i in range(5): print '%d! = %d' % (i,fact(i))
#!/usr/bin/env python import math import random import matplotlib.pyplot as plt #1/p=(4N)/(k(k-1)) is the average coalescence time mean of an exponetial distribution #p= 1/(4N)/(k(k-1)) #go back a number of generations drawn from an expoenetial distripution with the expectation was seen in the thingy above def cre...
#!/usr/bin/env python import math import random def drift(a,p): a=a #starting allele freq pop=p #pop size n= 0 #this is my counter gen= 0 #start counting generations to fixation while 0<a<1: gen +=1 for x in range(pop): x=random.random() #print x if float(x) <= a: #if random number is less than or...
''' Design a stack that supports push, pop, top, and retrieving the minimum element in constant time. push(x) -- Push element x onto stack. pop() -- Removes the element on top of the stack. top() -- Get the top element. getMin() -- Retrieve the minimum element in the stack. Example: MinStack minStack = new MinStack();...
''' Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists. ''' # Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # self.next = None class Solution(object): ...
''' Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity. Subscribe to see which companies asked this question ''' # Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: # pyt...
''' Given an absolute path for a file (Unix-style), simplify it. Examples: path = "/home/", => "/home" path = "/a/./b/../../c/", => "/c" Note that absolute path always begin with ‘/’ ( root directory ) Path will not have whitespace characters. ''' class Solution: def simplifyPath(self, path): """ ...
''' Given preorder and inorder traversal of a tree, construct the binary tree. Note: You may assume that duplicates do not exist in the tree. Example : Input : Preorder : [1, 2, 3] Inorder : [2, 1, 3] Return : 1 / \ 2 3 ''' # Definition for a binary tree node. # c...
''' 8 / \ 5 4 / \ \ 9 7 11 / \ / 1 12 3 / 2 ''' class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = None # construct binary tree from array # root = build_tree_from_list([8,5,4,9,7,None,11,None,None,1,12,3,None,N...
''' Given a binary search tree (BST), find the lowest common ancestor (LCA) of two given nodes in the BST. According to the definition of LCA on Wikipedia: “The lowest common ancestor is defined between two nodes v and w as the lowest node in T that has both v and w as descendants (where we allow a node to be a descen...
''' You are climbing a stair case. It takes n steps to reach to the top. Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top? Example : Input : 3 Return : 3 Steps : [1 1 1], [1 2], [2 1] ''' class Solution: ''' https://discuss.leetcode.com/topic/5371/basically-it-...
''' __ A __ / \ C __B__ | / \ | D E \ / \ / F _____/ ''' graph = {'A': set(['B', 'C']), 'B': set(['A', 'D', 'E']), 'C': set(['A', 'F']), 'D': set(['B']), 'E': set(['B', 'F']), 'F': set(['C...