text stringlengths 37 1.41M |
|---|
# python3
def cal_fibo_memo(n):
if n <= 0:
return 0
fibo = [0] * (n + 1)
fibo[0] = 0
fibo[1] = 1
for i in range(2, n + 1):
fibo[i] = fibo[i-1] + fibo[i-2]
return fibo[n]
if __name__ == '__main__':
n = int(input())
print(cal_fibo_memo(n)) |
def longest_palindrom(sequence, index, n):
if n == 0 or n == 1:
return n
if sequence[index] == sequence[n - index - 1]:
return 2 + longest_palindrom(sequence, index + 1, n - 2)
return max(longest_palindrom(sequence, index, n - 1), longest_palindrom(sequence, index + 1, n - 1))
def longest_palin(sequence)... |
def _minJump(arr, s, e):
if s == e:
return 0
if arr[s] == 0:
return float('inf')
min = float('inf')
for i in range(s+1, e+1):
if i < s + arr[s] + 1:
jumps = _minJump(arr, i, e)
if jumps != float('inf') and jumps + 1 < min:
min = jumps + 1
return min
def minJump(arr):
n = l... |
def string_compress(s):
count = 1
result = ""
for i in range(1, len(s)):
if s[i] == s[i - 1]:
count += 1
else:
result += s[i-1] + str(count)
count = 1
return result + s[len(s) - 1] + str(count)
s = "aabcccccaaa"
print(string_compress(s)) |
def solve_nqueen(board):
n = len(board)
return _solve_nqueen(board, 0, n)
def is_safe(board, row, col, n):
for i in range(col):
if board[row][i] == 1:
return False
for i, j in zip(range(row, n), range(col, -1, -1)):
if board[i][j] == 1:
return False
for i, j in zip(range(row, -1, -1), ran... |
from graph import Graph, Vertex
from collections import deque
def dfs(G, start):
visited = set()
stack = deque()
stack.append(start)
while len(stack) > 0:
v = stack.pop()
if v not in visited:
visited.add(v)
child = G.get_vertex(v)
if child is not None:
for key, val in child.i... |
class Vertex:
def __init__(self, key):
self.key = key
self.connections = {}
def addNeighbour(self, nb, weight = 1):
self.connections[nb] = weight
class Graph:
def __init__(self):
self.vertexList = {}
self.numVertices = 0
def addVertex(self, key):
self.numVertices += 1
vertex = V... |
class Node:
def __init__(self, key):
self.key = key
self.left = None
self.right = None
self.height = 1
class AvlTree:
def __init__(self):
self.root = None
def height(self, node):
if node is None:
return 0
return node.height
def getBlance(self, node):
if node is None:
... |
# python3
import sys, threading
from collections import deque
sys.setrecursionlimit(10**7) # max depth of recursion
threading.stack_size(2**27) # new thread will get stack of such size
class Node:
def __init__(self, data):
self.data = data
self.children = []
self.parent = None
def add_child(self, ... |
from binarytree import BinaryTree, Node
def isIdentical(root1, root2):
if root1 is None and root2 is None:
return True
if root1 is None or root2 is None:
return False
return (root1.data == root2.data and
isIdentical(root1.left, root2.left) and
isIdentical(root1.right, root2.right)
... |
def maxHeapify(arr, n, index):
left = 2* index + 1
right = 2* index + 2
if left < n and arr[index] < arr[left]:
largest = left
else:
largest = index
if right < n and arr[largest] < arr[right]:
largest = right
if largest != index:
arr[index], arr[largest] = arr... |
from main.binary_search_tree import Node, BinarySearchTree
from collections import deque
from form_bst_2 import make_tree
class LinkedNode:
def __init__(self, data):
self.data = data
self.next = None
# def add(self, node):
# if self.next is None:
# self.next = node
# root = self.next
# ... |
def get_tree_count(num):
if num == 0 or num == 1:
return 1
total = 0
for i in range(1, num + 1):
total += get_tree_count(i-1) * get_tree_count(num - i)
return total
def get_tree_count_dp(num):
T = [0] * (num+1)
T[0] = 1
T[1] = 1
import pdb; pdb.set_trace()
for i in range(2, num+1):
total ... |
from collections import deque
class Vertex:
def __init__(self, data):
self.data = data
self.connections = {}
def add_neighbours(self, nb):
self.connections[nb] = 1
def get_connections(self):
return self.connections
def __str__(self):
return str(self.data) + ' connected to: ' + str([x.dat... |
class Node:
def __init__(self, data):
self.data = data
self.next = None
self.prev = None
class DoubleLinkList:
def __init__(self):
self.head = None
self.tail = None
def insertFront(self, n):
node = Node(n)
tmp = self.head
if tmp == None:
... |
import ctypes
class DynamicArray:
def __init__(self):
self.size = 0
self.capacity = 1
self.array = self.makeArray(self.capacity)
def __length__(self):
return self.size
def getItem(self, n):
if not 0 <= n < self.size:
return IndexError('Index Out of Bo... |
#Uses python3
import sys
import queue
class DirectedGraph:
def __init__(self):
self.vertexes = {}
self.all_edges = []
self.size = 0
def add_vertex(self, data):
self.size += 1
self.vertexes[data] = []
def add_edge(self, fr, to, wt):
if fr not in self.vertexes:
self.add_vertex(fr)
... |
class SingleLinkList:
class Node:
def __init__(self, data):
self.data = data
self.next = None
def __init__(self):
self.head = None
self.tail = None
def make_intersect(self, node1, node2):
if node1 is None or node2 is None:
return None
node1.next = node2
def append(self, ... |
class Node:
def __init__(self, data):
self.data = data
self.left = None
self.right = None
self.parent = None
class Tree:
def __init__(self, data):
self.root = Node(data)
def insertLeft(self, node, n):
tmp = None
if node is None:
return node
if node.left is None:
... |
def is_even(num):
return num % 2 == 0
print(callable(is_even))
is_odd = lambda num: num % 2 == 1
print(callable(is_odd))
print(callable(list))
print(callable(list.append))
class NoCall:
def __init__(self):
pass
class Call:
def __init__(self):
pass
def __call__(self):
pass
print(callable(N... |
from stack import Stack
class StackMin:
def __init__(self):
self.stack = Stack()
self.stack_min = Stack()
def push(self, data):
self.stack.push(data)
if self.stack_min.is_empty():
self.stack_min.push(data)
else:
top = self.stack_min.peek()
if top > data:
self.stack_... |
class Heap:
def __init__(self, heap):
self.heap = heap
self.size = len(heap)
def parent(self, index):
return (index - 1) // 2
def leftChild(self, index):
return (index * 2) + 1
def rightChild(self, index):
return (index * 2) + 2
def build_heap(self):
n = self.size
for i in r... |
class Node:
def __init__(self, key = None, value = None):
self.key = key
self.value = value
self.next = None
self.prev = None
class HashTable:
def hash(self, key):
return ord(str(key)) % self.size
def chaining(self):
pass
def __init__(self, size = 16):
self.size = size
self.ke... |
def add_paren(result, left_rem, right_rem, string, index):
if left_rem < 0 or right_rem < left_rem:
return
if left_rem == 0 and right_rem == 0:
result.append(''.join(string))
else:
string[index] = '('
add_paren(result, left_rem - 1, right_rem, string, index + 1)
string[index] = ')'
add... |
#Uses python3
from random import randint
import sys
def largest_number(a):
#write your code here
res = ""
while len(a) > 0:
max_digit = 0
for i in range(len(a)):
if int(a[i]) > int(a[max_digit]):
max_digit = i
res += a[max_digit]
a.pop(max_digit)
for x in a:
res += x
return r... |
class Node:
def __init__(self, data):
self.data = data
self.next = None
class SingleLinkList:
def __init__(self):
self.head = None
self.tail = None
def addToStart(self, n):
tmp = self.head
node = Node(n)
self.head = node
node.next = tmp
... |
# python3
import sys
class Node:
def __init__(self, data):
self.data = data
self.prev = None
class Stack:
def __init__(self):
self.top = None
def push(self, data):
node = Node(data)
node.prev = self.top
self.top = node
def pop(self):
top = self.top
self.top = self.top.pre... |
# python3
def cal_last_digit(n):
fibo = [None] * (n + 1)
fibo[0] = 0
fibo[1] = 1
for i in range(2, n + 1):
fibo[i] = (fibo[i-1] + fibo[i-2]) % 10
return fibo[n]
if __name__ == '__main__':
n = int(input())
print(cal_last_digit(n)) |
from singleLinkList import SingleLinkList
def length(head):
count = 0
tmp = head
while tmp is not None:
tmp = tmp.next
count += 1
return count
def mergeList(head1, head2):
result = SingleLinkList()
return _mergeList(head1, head2, result)
def _mergeList(head1, head2, result):
if head1 is None:
... |
class DoubleQueue:
def __init__(self, capacity = 16):
self.front = -1
self.rear = -1
self.capacity = capacity
self.size = 0
self.queue = [None] * self.capacity
def enqueueEnd(self, n):
if self.front == -1:
self.front = 0
if self.size == self.... |
def get_subset(set, index):
if len(set) == index:
all_subset = []
all_subset.append([])
else:
all_subset = get_subset(set, index + 1)
print('1',index, all_subset)
item = set[index]
more_subset = []
for subset in all_subset:
print(2, subset)
new_subset = []
new_subset.ex... |
import ctypes
class BinaryHeap:
def __init__(self, capacity = 16):
self.heap = self.makeArray(capacity)
self.capacity = capacity
def addHeap(self, arr):
for i in range(len(arr)):
self.heap[i] = arr[i]
self.capacity = len(arr)
def parent(self, i):
ret... |
from collections import deque
class Node:
def __init__(self, data):
self.data = data
self.left = None
self.right = None
self.parent = None
class BinaryTree:
def __init__(self):
self.root = None
def insertLeft(self, data, parent=None):
node = Node(data)
if parent is not None:
... |
from binarytree import BinaryTree, Node
from collections import deque
def leftView(root):
if root is None:
return
queue = deque()
queue.append(None)
queue.append(root)
done = False
while not done:
node = queue.popleft()
if node is None:
if len(queue) > 0:
node = queue.popleft()
... |
def inverse_bwt(bwt):
last = [(value, index) for (index, value) in enumerate(bwt)]
# print('last', last)
first = sorted(last)
# print('first', first)
first_to_last = {f: l for f, l in zip(first, last)}
next = first[0]
result = ''
for key, value in first_to_last.items():
print(key, '->', value)
for... |
from graph import Graph
from collections import deque
def dfs_rec(G, start):
visited = set()
vertex_cc = {}
cc = 1
for v in G.all_vertexes():
if v not in visited:
explore(G, v, visited, cc, vertex_cc)
cc += 1
return (vertex_cc)
def explore(G, v, visited, cc, vertex_cc):
visited.add(v)
ve... |
import pgzrun
import random
WIDTH = 1920
HEIGHT = 1080
R = 10
balls = []
def draw():
screen.fill('white')
for ball in balls:
screen.draw.filled_circle((ball[0], ball[1]), ball[4], (ball[5], ball[6], ball[7]))
for x in range(1, ball[4], 10):
screen.draw.filled_circle((ball[0], ball... |
#A permutation is an ordered arrangement of objects. For example, 3124 is one possible permutation of the digits 1, 2, 3 and
#4. If all of the permutations are listed numerically or alphabetically, we call it lexicographic order. The lexicographic permutations of 0, 1 and 2 are:
#012 021 102 120 201 210
... |
class Node:
def __init__(self,key):
self.key = key
self.next = None
def printList(head):
curr = head
while(curr!=None):
print(curr.key,end=" ")
curr =curr.next
def insertAtTail(head,data):
if(head==None):
return Node(data)
curr = head
while(curr.next!=None... |
"""
Exercise 10.5
Escreva uma função chamada is_sorted que tome uma lista como parâmetro e retorne True se
a lista estiver classificada em ordem ascendente, e False se não for o caso. Por exemplo:
>>> is_sorted([1, 2, 2])
True
>>> is_sorted(['b', 'a'])
False
"""
def is_sorted(t):
""" Returns if a list is sorted
... |
"""
Exercise 10.3
Escreva uma função chamada middle que receba uma lista e retorne uma nova lista com
todos os elementos originais, exceto os primeiros e os últimos elementos. Por exemplo:
>>> t = [1, 2, 3, 4]
>>> middle(t)
[2, 3]
"""
def middle(t):
"""Returns a list without first and last index
t: list
... |
"""
Exercise 11.1
Escreva uma função que leia as palavras em words.txt e guarde-as como chaves em um dicionário.
Não importa quais são os valores. Então você pode usar o operador in como uma forma rápida de
verificar se uma string está no dicionário.
"""
def make_dict():
words = dict()
fin = open('words.txt'... |
"""
Exercise 9.4
Escreva uma função chamada uses_only que receba uma palavra e uma série
de letras e retorne True, se a palavra só contiver letras da lista.
Você pode fazer uma frase usando só as letras acefhlo?
Que não seja “Hoe alfalfa?”
"""
def uses_only(word, letters):
""" Checks if a word uses only letter ... |
"""
Exercise 12.2
Mais anagramas!
Escreva um programa que leia uma lista de palavras de um arquivo (veja “Leitura de listas de
palavras”, na página 133) e imprima todos os conjuntos de palavras que são anagramas.
Aqui está um exemplo de como a saída pode parecer:
['deltas', 'desalt', 'lasted', 'salted', 's... |
"""
Exercise 12.1
Escreva uma função chamada most_frequent que receba uma string e exiba as letras
em ordem decrescente de frequência. Encontre amostras de texto de vários idiomas
diferentes e veja como a frequência das letras varia entre os idiomas.
Compare seus resultados com as tabelas em http://en.wikipedia.org/... |
for i in range(5):
print(i)
if i == 4:
print("Too big - I'm giving up!")
break
else:
print("Completed successfully")
|
'''
1. What is the branching factor at depth 0? At depth 1?
The initial branching factor is 9. As all fields are empty.
2. What is the maximal depth?
The depth has a maximum depth of 9 as there will at max only be 9 moves to achieve terminal.
(!9 nodes)
3. Will a MIN move attempt to minimize or maximize t... |
'''
1. Run the module.
2. Enter: run(10)
Current New
location status action location status
A Dirty Suck A Clean
A Clean Right B Dirty
B Dirty Suck B Clean
B Clean Left A Clean
A ... |
class Tree(object):
"""A simple Tree class"""
def __init__(self, cargo, leaves=None):
"""cargo is the information of the node, leaves is the list of leaves"""
self.cargo = cargo
if leaves is None:
self.leaves = []
else:
self.leaves = leaves
def __str__(self):
return str(self.carg... |
from enum import Enum, unique
@unique
class ShapeEnum(Enum):
CIRCLE = 1
SQUARE = 2
TRIANGLE = 3
class Station(object):
def __init__(self, shape):
try:
self.shape = ShapeEnum[shape.upper()]
except KeyError:
print("Shape '" + shape + "' not found in ShapeEnum")
... |
import csv
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
# 設定値
chromedriver_path = 'ChromeDriverのパス'
max_page = 3
def main():
'''
メインの処理
「メンズ新着アイテム」のリンクをたどり、商品の情報を取得
'''
options = Options()
options.add_argument('--headless') # ヘッドレスモードを有効にする
driv... |
import abc
class DriveAbstractStragegy(object):
__metaclass__ = abc.ABCMeta
@abc.abstractmethod
def drive(self):
"""Required method"""
class HigherDriveStrategy(DriveAbstractStragegy):
def drive(self):
print('I drive higher off the ground')
class LowerDriveStrategy(DriveAbstractStrag... |
# Python decorators are different from the decorator pattern
def multiply_by_two(func):
def _multiply_by_two(a, b):
return func(a, b) * 2
return _multiply_by_two
@multiply_by_two
def add(a, b):
return a + b
@multiply_by_two
def subtract(a, b):
return a - b
print(add(10,5))
print(subtract(60... |
#The Spy Chat Application
from spy_details import spy,Spy,friend,Chat_Message #importing various spy details from the file spy_details
from steganography.steganography import Steganography #importing the Steganography module
from colorama import init
init()... |
cube = lambda x: x**3
def fibonacci(n):
n1, n2 = 0, 1
final = []
count = 0
while count < n:
final.append(n1)
nth = n1 + n2
# update values
n1 = n2
n2 = nth
count += 1
return final
if __name__ == '__main__':
n = int(input())
print(list(map(c... |
arr = list(map(int, input().rstrip().split()))
total = []
for i in range(arr[1]):
total.append(list(map(float, input().rstrip().split())))
# arr2 = list(map(float, input().rstrip().split()))
# arr3 = list(map(float, input().rstrip().split()))
main = zip(*total)
final = []
# print(arr1, arr2, arr3)
for element in ... |
def swap_case(s):
new = []
for i in s:
if i.isupper():
new.append(i.lower())
elif i.islower():
new.append(i.upper())
else:
new.append(i)
return "".join(new)
print(swap_case("Rishabh !@#$5678"))
|
def difference(arr):
odd_sum = even_sum = 0
for i, j in enumerate(arr):
if i % 2 == 0:
even_sum += j
else:
odd_sum += j
return abs(odd_sum - even_sum)
print(difference([16, 76, 63, 42, 74, 53, 13, 94, 48, 46, 77, 15, 26, 78, 47, 65, 36, 66, 98, 80, 34, 19, 68, 29, ... |
from collections import defaultdict
def get_canonical(word):
return "".join(sorted(word))
def group_anagrams(words):
# words = sorted(words)
dic = defaultdict(lambda: [])
for i in words:
# cp = i
cf = get_canonical(i)
dic[cf].append(i)
# temp.append("".join(sorted(i)... |
def detectLoop(head):
check = set()
check.add(head)
node = head
while node.next is not None:
if node.next in check:
return True
else:
check.add(node.next)
node = node.next
return False
# {
# Driver Code Starts
# Initial Template for Python 3
# Nod... |
def compare_triplets(a, b):
alice = bob = 0
for i in range(3):
if a[i] > b[i]:
alice +=1
elif b[i] > a[i]:
bob += 1
else:
pass
return alice, bob
print(compare_triplets([5, 6, 7], [3, 6, 10]))
|
n = int(input())
vowels = {'a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U'}
for _ in range(n):
word = input()
count = 0
for i in range(len(word)):
if word[i] in vowels:
count += (len(word) - i) * (i + 1)
print(count)
|
# MAGIC 8-BALL (25pts)
# Create a tkinter app which acts as a "Magic 8-ball" fortune teller
# The user asks a yes/no question that they want an answer to.
# Then the user clicks a button, and your program displays
# the "magic" random answer to their question.
# Your program will have the following properties:
# - Use ... |
prefixes = "JKLMNOPQ"
suffix = "ack"
for p in prefixes:
if p=="O" or p=="Q":
print(p + "u"+suffix)
else:
print(p+suffix)
|
from test import testEqual
def is_palindrome(text):
# your code here
left=0
rigth=len(text)-1
while left<=rigth:
if text[left]==text[rigth]:
return True
else:
return False
testEqual(is_palindrome('abba'), True)
testEqual(is_palindrome('abab'), False)
testEqual(is_... |
myList = [76, 92.3, 'hello', True, 4, 76]
myList.append("apple")
myList.insert(3,"cat")
myList.insert(0,99)
myList.index("hello")
myList.count(76)
myList.remove(76)
myList.pop(myList.index(True))
print (myList)
|
"""Program for Matrix addition"""
n1=int(raw_input('Enter how many row'))
n2=int(raw_input('Enter how many columns'))
a=[[0 for i in range(n1)]for j in range(n2)]
print "Enter Matrix A Elements"
for i in range(0,n1):
for j in range(0,n2):
a[i][j]=int(raw_input('Enter the number'))
b=[[0 for i in range(n1)]for j in r... |
#!usr/bin/env python3
import random
# Given a fixed length array arr of integers, duplicate each occurrence of zero
# shifting the remaining elements to the right. Note that elements beyond the
# length of the original array are not written. Do the above modifications
# to the input array in place, do not return anyt... |
graph = {'1': ['2', '3'],
'2': ['1', '3', '4', '5'],
'3': ['1', '2', '5', '7', '8'],
'4': ['2', '5'],
'5': ['2', '3', '4', '6'],
'6': ['5'],
'7': ['3', '8'],
'8': ['3', '7']
}
class Node:
def __init__(self, name, adjacent):
self.name... |
def monthly_rate(annual_growth):
"""Calculates the monthly rate from the given annual growth rate."""
return annual_growth ** (1/12.0)
def monthly(initial_deposit, monthly_deposit, annual_growth, years):
"""
Calculates the total value of an investment based on regular monthly deposits,
a steady growth rate, ... |
board = list(range(1, 10))
wins = [(1,2,3),(4,5,6),(7,8,9),(1,4,7),(2,5,8),(3,6,9),(1,5,9),(3,5,7)]
def draw_board():
for i in range(2):
print('|', board[i*3], '|', board[1+i*3], '|', board[2+i*3], '|','\n-------------')
print('|', board[6], '|', board[7], '|', board[8], '|')
def take_input(token):
... |
class LetterChange:
def LetterChanges(str):
str = "fun times*3"
alphabet = ['a','b','c','d','e','f','g','h'
,'i','j','k','l','m','n',
'o','p','q','r','s',
't','u','v','w','x','y','z']
vowels = ['a', 'o', 'e', 'i', 'u']
new... |
import unittest
from Car import Car
class TestCar(unittest.TestCase):
def setUp(self):
self.car = Car()
class TestInit(TestCar):
def test_initial_speed(self):
self.assertEqual(self.car.speed, 0 )
def test_initial_odometer(self):
self.assertEqual(self.car.odometer, 0)
def tes... |
empty_list = []
even = [2, 4, 6, 8]
odd = [1, 3, 5, 7, 9]
# list concatenation
numbers = even + odd
print(numbers)
# return a list form a function
sorted_numbers = sorted(numbers)
print(sorted_numbers)
# see how sorted will sort the sequence of chars, this will return a list of chars
digits = sorted("4346534")
print... |
# the size of the sequence can be changed without creating a problem when iterating backwards
data = [104, 101, 4, 105, 308, 103, 5, 107, 100, 306, 106, 102, 108]
min_valid = 100
max_valid = 200
# the data is not sorted here
for index in range(len(data) - 1, -1, -1):
if data[index] < min_valid or data[index] > ma... |
from collections import defaultdict
from dataclasses import dataclass
from math import pi, atan2
from typing import Sequence, Tuple
@dataclass
class Point:
x: int
y: int
def load_asteroid_map(file: str) -> Sequence[Sequence[str]]:
asteroid_map = []
with open(file) as f:
for line in f:
... |
def count(s):
a = []
for i in s:
if i not in a:
a.append(i)
result = dict()
for i in a :
temp = 0
for j in s:
if i == j:
temp += 1
result.update({i:temp})
result.update({i:temp})
return result
... |
class Node:
def __init__(self,data):
self.data = data
self.left = None
self.right = None
class Tree:
def __init__(self,data):
self.root = Node(data)
def insert(self,data):
if self.root is None:
self.root = Node(data)
else:
self._inser... |
class Node:
def __init__(self,data):
self.data = data
self.next = None
class linkedlist:
def __init__(self):
self.head = None
def insert(self,data):
if self.head is None:
self.head = data
else:
currentNode = self.head
while True:... |
def sub(s):
l = len(s)
print(l)
if l==1:
return "Empty String"
elif l>1 and l<3:
a =[]
result = ""
for i in s:
a.append(i)
for i in s:
a.append(i)
for i in a:
result += i
return result
else:
start = 0... |
s = input("Enter a string: ")
l = s.split()
for i in range(0,len(l)):
if l[i] == "poor" or l[i] == "not":
l[i] = "good"
result = " ".join(l)
print(result)
|
s = input("Enter a string: ")
a = s.split()
print(a)
large = ""
small = ""
temp = 0
ans = 0
for i in range(0,len(a)):
if len(a[temp]) < len(a[i]):
temp = i
elif len(a[ans]) > len(a[i]):
ans = i
large += a[temp]
small += a[ans]
print("large :",large)
print("small :",small)
|
import math
k = int(input("Enter n: "))
#Uses central binomial coefficients.
#Source http://www.robertdickau.com/lattices.html
n = 2 * k
n_k = n - k
up = math.factorial(n)
down = math.factorial(k) * math.factorial(n_k)
print(up/down)
|
import math
num = str(math.factorial(100))
res = 0
for x in range(0, len(num)):
res = res + int(num[x])
print(res)
|
import random
def generate_random_dna(length: int) -> str:
"""generate_random_dna generates a random DNA string given a length.
Args:
length (int): desired dna length.
Returns:
str: DNA string. E.g.: 'AGCTCACTGACTT' for length = 13
"""
dna = ''.join([random.choice('ACGT') for _ in range(len... |
def reverse_complement(dna: str) -> str:
"""reverse_complement computes the reverse complement of a DNA sequence.
Args:
dna (str): input DNA sequence
Returns:
str: reverse complementary of the input sequence
"""
complement = {'A': 'T', 'T': 'A',
'C': 'G', 'G': 'C'... |
"""
Loyd's Fifteen puzzle - solver and visualizer
Note that solved configuration has the blank (zero) tile in upper left
Use the arrows key to swap this tile with its neighbors
"""
#testing
import poc_fifteen_gui
LR_DICT = {
-1: "l",
1: "r"
}
class Puzzle:
"""
Class representat... |
'''
# recursive LCM algorithum imeplented in python
# python LCM recusive algorithm were funtion calling itself many time until finding Longest common subsequence LCM
'''
def lcs(x,y,m,n):
if m==0 or n==0:
return 0;
elif x[m-1] == y[n-1]:
return 1+ lcs(x,y,m-1,n-1);
else:
return max(... |
# Christopher Brown 000968168
# Class for custom hash table functionality.
from datetime import datetime
import re
class HashTable:
# Sets the size of the hash table to 40 items and initializes each item to None.
# Time Complexity O(1), Space Complexity O(1)
def __init__(self):
self.size = 40
... |
import sqlite3
conn = sqlite3.connect('desafio.db')
c = conn.cursor()
c.execute("create table if not exists funcionarios (id integer primary key autoincrement, idade int, nome text, cargo text)")
c.execute("create table if not exists acoes (id integer primary key autoincrement, metodo text, retorno text, data_hora ... |
#英小文字の文字コードの範囲を確認
print(ord('a'),ord('z')) #97 122
def cipher(text):
result = []
for i in text:
if i.islower():
result.append(chr(219-ord(i)))
else:
result.append(i)
return ''.join(result)
test_txt = "I have a pen."
ans = cipher(test_txt)
print('暗号化:',... |
def pow(x, n):
if n < 0:
return pow(1/x, -n)
elif n == 0:
return 1
elif n == 1:
return x
elif n%2 == 0:
return pow(x*x, n/2)
else:
return x*pow(x*x, (n-1)/2)
x = int(input())
print(pow(3, x)%(pow(2, 31) - 1))
|
a = 400
b = 540
c = 120
d = 9
e = 550
while(True):
print("")
print("Write action (buy, fill, take, remaining, exit):")
x = input()
if x == "remaining":
print("The coffee machine has:")
print(str(a)+" of water")
print(str(b)+" of milk")
print(str(c)+" of coffe... |
#!/usr/bin/python3
'''
Description:
------------
This Python script retrieves stock data from Yahoo finance and store them in different SQL databses.
It teaches you how to do that in SQLite.
Requirements:
------------
Make sure that Pandas is installed
Depending on what SQL RDMS you are using whether sq... |
import pygame
import random
import sys
# Define some colors
BLACK = ( 0, 0, 0)
WHITE = (255, 255, 255)
RED = (255, 0, 0)
class Block(pygame.sprite.Sprite):
speed=0
"""
This class represents the ball.
It derives from the "Sprite" class in Pygame.
"""
def __init__(self, color, wid... |
import json
"""
#
# Save dictionary to JSON file
#
"""
def save_dictionary_to_json(dictionary, json_file):
print("Saving {} results file to {}".format(str(len(dictionary)), json_file))
with open(json_file, 'w') as save:
json.dump(dictionary, save)
"""
#
# Load dictionary from JSON file
#
"""
def load_... |
def multiply_list(num , *args):
if args:
return [i**num for i in args]
else:
return "you didn't pass any args"
print(multiply_list(4,*[3,4,5]))
|
# FOR READ THE CSV FILES
# from csv import reader
# with open('csv1.csv','r') as f:
# csv_reader = reader(f)
# for row in csv_reader:
# print(row)
# from csv import DictReader
# with open('csv1.csv' , 'r') as f:
# csv_reader = DictReader(f, delimiter = '|')
# for row in cs... |
#def convert_string(l):
# string_list = []
# for i in l:
# if type(i) == int:
# string_list.append(str(i))
#return string_list
def convert_string2(l):
return [str(i) for i in l if (type(i) == int or type(i) == float)]
numbers = [1,2.0,3, [4,5,6] ,'true','false']
print(con... |
def greatest(a,b,c):
if c < a > b :
return a
elif a < b > c :
return b
else:
return c
num1 = int(input("enter first number : "))
num2 = int(input("enter second number : "))
num3 = int(input("enter third number : "))
biggest = greatest (num1,num2,num3)
print(... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.