text stringlengths 37 1.41M |
|---|
import requests
from bs4 import BeautifulSoup
# Task 1-------------------------------------------------------------------------
url = input("Enter wiki url: ")
# for easy testing
#url= 'https://de.wikipedia.org/wiki/Pietro_Antonio_Lorenzoni'
def scraping_webpage(url): # web scraping function
page = requests.g... |
import time, sys
indent = 0
indent_increasing = True
try:
while True:
print(' ' * indent, end = '')#{end = ''} =
print('********')
time.sleep(0.1) #pause for 1/10 of a second
if indent_increasing: #increase the number of spaces
indent += 1
if indent == 10: #... |
opcion = ""
def obtener_valores(diccionario):
arreglo_numeros = []
valores_diccionario = diccionario.values()
for valor in valores_diccionario:
tipo = type(valor)
lista = isinstance(valor, list) == True
tupla = isinstance(valor, tuple) == True
es_lista = isinstance(v... |
import os
import csv
print("\nFinancial Analysis")
print("--------------------------------------------------")
# Relative path for input file
csvPath = os.path.join('Resources', 'budget_data.csv')
# Relative path for output file
output_path = os.path.join('analysis', 'py_bank_output.txt')
# List for all the dates... |
import unittest #Importing the unittest module
from user import User
class TestUser(unittest.TestCase):
'''
Test class that defines test cases for the User class behaviors
Arg:
unittest.Testcase: A TestCase class that helps in creating test case classes
'''
def setUp(self):
''... |
"""
This module contains the connect four game board and it's operations.
"""
from datetime import datetime
class ConnectFourGame:
""" A game of connect four played by the twitter bot.
"""
def __init__(self, game_id, user1, user2, last_tweet,
last_active, boardstring, num_turns, user1_is_... |
# -*- coding: utf-8 -*-
"""
Created on Tue Jul 10 20:51:38 2018
@author: yinjiang
"""
# quick sort in a unsorted array
# step 1: convert txt file into array
l = []
filename = 'QuickSort.txt'
with open(filename, 'r') as f:
for item in f.readlines():
l.append(int(item.strip()))
# ste... |
r=1
while r < 8:
print(r)
if r==5:
break
r+=1 |
"""
Interpolates the temperature data over height (1D) and then over a surface to try to understand the three dimensional
temperature distribution
"""
import pickle
import numpy as np
from scipy import interpolate
import matplotlib.pyplot as plt
import pandas as pd
# upload the processed and corrected data
file_addr... |
def dongmachine(dongamount):
dongamount=int(dongamount)
for x in range(1,dongamount):
print("dong")
dongamount=input("Hi how much do you like dongs?")
dongmachine(dongamount)
|
class MyLinkedList:
def __init__(self):
"""
Initialize your data structure here.
"""
self.val = None
self.next=None
def get(self, index: int) -> int:
"""
Get the value of the index-th node in the linked list. If the index is invalid, return -1... |
import sys
import argparse
parser = argparse.ArgumentParser(description='Give me oracle file.')
parser.add_argument('-p', type=str, help='oracle file')
args = parser.parse_args()
count = 0
for test_line in open(args.p):
if test_line.startswith("#"):
count = 1
else:
if count > 0:
co... |
def convert(number):
# initialize flags such that we start with no factors
factor3 = False
factor5 = False
factor7 = False
# initialize the output as type string
string_output = ''
# evaluate the moduli for each division, checking for zeroes
if (number%3 == 0):
factor3 = True
... |
'''
该文件简单的创建了Card, Deck, Player, Game类,Game类中auto_play函数使用了1个MonteCarloAI和3个相同的规则策略完成了13回合的游戏
@author: pipixiu
@time: 2018.9.30
@city: Nanjing
'''
from encapsule import MonteCarloPlay
import random
import collections
Card = collections.namedtuple('Card', ['point', 'suit'])
'''
使用namedtuple创建Card类型,包含point,suit两个属性
p... |
# Variables are information stored in Memory
# snake_case
# Start with lowercase or underscore
# Case sensitive
# Don't override keywords
iq = 190 # (Here iq is the variable). We are binding 190 to the variable (iq)
name = ('Abhishek kabi')
course = ('CPython')
_intrest_ = ('ML') ... |
#max and min num of array
arr={10,20,30,40,50}
a=0
#MAX
for i in arr:
if i>a:
a=i
print(a)
#MIN
a
for i in arr:
if i<a:
a=i
print(a) |
n=int(input("Enter The number : "))
i=1
while i<=n :
print(i)
#i=i+1 |
# Write a program to do arithmatic operation using function
def sumnum(a, b):
ans = a + b
print("Addition is :", ans)
def subtraction(a, b):
ans = a - b
print("Subtraction is :", ans)
def division(a, b):
ans = a / b
print("Division is :", ans)
def multiply(a, b):
ans =... |
def day5(text):
steps = 0
num_list = []
with open(text) as f:
for line in f:
num_list.append(int(line))
x = 0
while x >= 0 and x < len(num_list):
steps += 1
old = x
x += num_list[x]
num_list[old] += 1
print steps
def day5b(text... |
number=1
while True:
if number<11:
print(number)
number=number+1
else:
break
|
# Rock paper scissors from chapter 2
import random, sys
print('ROCK, PAPER, SCISSORS')
#these variables keep track of the number of wins, losses and ties.
wins=0
losses=0
ties=0
while True:
print('%s Wins, %s Losses, %s Ties' % (wins, losses, ties))
while True: # The player input loop
print('Enter yo... |
def discounted(price, discount):
price = abs(float(price))
discount = abs(float(discount))
if discount >= 100:
price_with_discount = price
else:
price_with_discount = price - (price * discount / 100)
return price_with_discount
price1 = -100
discount1 = 10
discounted(price1, discoun... |
import statistics
def mmmv():
i = [int(x) for x in input('Enter your numbers(seperate by spaces" "): ').split()]
print('Mean:',statistics.mean(i))
print('Median:',statistics.median(i))
print('Variance:',statistics.variance(i))
try:
print('Mode:',statistics.mode(i))
except statistics.StatisticsError as e:
pri... |
n=int(input("enter n value:"))
i=1
sum=0
while i<n:
if i%2==0:
sum+=i
i=i+1
print("sum of even numbers",sum) |
list[]
print("enter the digits in list")
x=int(input())
for i in range(0,x)
y=int(input())
list.append(y)
if y>1
for y in range(2,y)
if(num%i)==0:
print(y,"it is not a prime number")
else:
print(y,"it is a prime number")
else:
print(y,"it is not a prime number")
print list
|
import heapq
def do_math(medians, num):
# print(num)
max_medians = (num + medians) % 10000
return max_medians
def _heappush_max(heap, num):
heapq.heappush(heap, -num)
def _pushpop_max(heap, num):
popped = heapq.heappushpop(heap, -num)
return -popped
def peek_max_heap(heap):
retur... |
# coding: UTF-8
#
# 条件分岐
#
### if
# 条件分岐のブロックの中はインデントの深さで判断しています
print "---- if ----"
int = 50
if int > 20:
print "true"
if int > 20 and int < 60:
print "true"
if 20 < int < 60:
print "true"
if int < 50:
print "if"
elif int < 60:
print "elif"
else:
print "else"
# 変わった書き方
print "true" if in... |
#This program calculates the body mass of a person.
#It asks for height in meters and provides weight in kg
print("This program calculates your Body Mass Index (BMI) and its classification")
weight = float ( input("Type your Weight in Kg (example 80): ") )
height = float ( input("Type your Height in Meters (example 1... |
grade1 = float ( input("Type the grade of your first test: ") )
grade2 = float(input("Type the grade of your second test: "))
absences = int(input("Type many times have you been absent: "))
total_classes = int(input("Type the total number of classes: "))
avg_grade = (grade1 + grade2) / 2
attendance = (total_classes... |
# coding: utf-8
# # Heaps
# ## Overview
#
# For this assignment you will start by modifying the heap data stucture implemented in class to allow it to keep its elements sorted by an arbitrary priority (identified by a `key` function), then use the augmented heap to efficiently compute the running median of a set of... |
n1 = int(input("digite o primeiro numero: "))
n2 = int(input("digite o segundo numero: "))
n3 = int(input("digite o terceiro numero: "))
if n1>n2>n3:
print ("o maior numero e", n1, "e o maior numero e",n3)
if n1>n3>n2:
print ("o maior numero e", n1, "e o menor numero e", n2)
if n2>n1>n3:
print ("o m... |
import math
def dist_between(start,end):
return math.sqrt(pow((start[0]-end[0]),2)+pow((start[1]-end[1]),2))
def get_best_f_score(input_set,scoredict):
idx = input_set.pop()
input_set.add(idx)
best = idx
bv = scoredict[idx]
for idx in input_set:
if scoredict[idx] < bv:
bes... |
list_num = []
list_num.extend([1, 2]) # extending list elements
print(list_num)
list_num.extend((3, 4, 5.5, 6.8)) # extending tuple elements
print(list_num)
list_num.extend('ABC') # extending string elements
print(list_num)
evens = [2, 4, 6]
odds = [1, 3, 5]
nums = odds + evens
print(nums) |
#coding=utf-8
#定义求质数的函数
def getprim(n):
#我们从3开始,提升效率,呵呵,微乎其微啦
p=3
x=0
while(x<n):
result=True
for i in range(2,p-1):
if(p%i==0):
result=False
if result==True:
x=x+1
rst=p
#注意:这里加2是... |
from ListNode import ListNode
class Solution:
def middleNode(self, head: ListNode) -> ListNode:
fast = low = head
while fast and fast.next:
fast = fast.next.next
low = low.next
return low |
def another_merge_sort(array, start, end):
if start >= end:
return
mid = int((start + end) / 2)
print(start, end, mid)
another_merge_sort(array, start, mid)
another_merge_sort(array, mid + 1, end)
i = start
j = mid + 1
newarray = []
while(i <= mid and j <= end):
i... |
from ListNode import ListNode
class Stack:
def __init__(self):
self.head = None
def push(self, item):
newnode = ListNode(item)
if self.head:
newnode.next = head
head = newnode
else:
self.head = newnode
def pop(self):
if ... |
from ListNode import ListNode
# 回文串单链表实现
def is_palindrome_linked_list(head):
left_head = None
slow_pointer = head
fast_pointer = head
is_odd = True
while fast_pointer.next is not None:
if fast_pointer.next.next is not None:
fast_pointer = fast_pointer.next.next
else:
... |
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def inorderSuccessor(self, root: TreeNode, p: TreeNode) -> TreeNode:
self.queue = []
self.inOrder(root)
for i in ... |
class BetterSolution:
def isValid(self, s: str) -> bool:
mapping = {"]": "[", "}": "{", ")": "("}
first = []
for i in s:
if i in mapping.keys():
if len(first) == 0:
return False
if (mapping.get(i) != first.pop()):
... |
import random
print("Welcome to the fortune telling game!!")
ques = ""
response = "y"
while response == "y":
ques = input("You may ask a question\n")
choice = random.randrange(1,5)
if choice == 1:
print("Yes")
elif choice == 2:
print("Yes, definitely")
elif choice == 3:
print... |
NUM_QUESTIONS = 5
questions = (
'Are Connor and Brendan the same person, moving between two positions so quickly as to trick the eye into believing there are two Fletchalls',
'Does James sleep with his 12-inch MacBook under the pillow',
'Are expletives more than 20% of Chris Deng\'s vocabulary',
'Is Ni... |
import random
HEADS, TAILS = True, False
RED = (HEADS, TAILS)
BLUE = (TAILS, HEADS)
red_wins = 0
blue_wins = 0
red = None
blue = None
while True:
red_win = False
blue_win = False
p_red = red
p_blue = blue
red = random.choice((HEADS, TAILS))
blue = random.choice((HEADS, TAILS))
if RED =... |
#To design an ATM mock up project
# Initialize page
import random
import validation
import database
import os
import funds
def init ():
print('Welcome to bank PHP')
haveAccount = int(input("""
Do you have an account?
1 for yes
2 for no
"""))
if haveAccount == 1:
print('****... |
#Original Author: u/gonano4
print("Unknown:Hello, welcome to the fantastic world of Ksea,what is your name?")
name=input()
print(name+",","a great name for and adventurer,i am Valder, The Master of the fire")
import time
time.sleep(2)
print("Valder:as you are new to Ksea i´ll ask you a question")
time.sleep(2)
print("... |
def login(name,password):
print ("logged in")
def register(name,password):
print ("registered")
def begin():
print("Welcome to Password Generator login")
option = input("login or registor (login,reg): ")
if(option!="login" and option!="reg"):
option = begin()
return option
#opt = begin(... |
def Fibonacci(n):
# write code here
f1 = 0
f2 = 1
if n == 0: return f1
elif n == 1: return f2
for _ in range(n-1):
f2, f1 = f1+f2, f2
return f2
print(Fibonacci(3))
# ⷨ
class Solution:
def Fibonacci(self, n):
# write code here
res = [0, 1, 1, 2]
while len(... |
# -*- coding:utf-8 -*-
def DFS(matrix, row, col, path, visited):
if row < 0 or row >= len(matrix) or col < 0 or col >= len(matrix[0]) or (row, col) in visited:
return False
if path[0] == matrix[row][col]:
if len(path) == 1:
return True
return DFS(matrix, row+1, col, path[1:]... |
class TreeLinkNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
self.next = None
class Solution:
def GetNext(self, pNode):
# write code here
if not pNode: return None
p = pNode
if pNode.right: # 有右子树
p = pNo... |
### IOT Course 4 Week 3 ###
while True:
numbers = [1,2,3]
i = 0
while i < 3:
numbers[i] = input("Enter a number: ")
print ("")
i += 1
numbers.sort(key=int)
print (', '.join(map(str, numbers)))
print ("")
again = input("Would you like to play again? Type Y or N. ")
if again == 'n' or again == 'N':
break... |
x = 0;
for x in range (1,100, 10):
print (x)
if x>50:
break
y = 10;
while y<100:
print(y)
y+=1
age = 27
if (age<10):
print("You are baby")
elif (age>10) and (age<20):
print ("you are teenager")
else:
print("you are old")
|
import urllib2
import json
url = "https://questions.aloc.ng/api/q/7?subject=chemistry"
json_obj = urllib2.urlopen(url)
data = json.load(json_obj)
num =0
score =0
for item in data[u'data']:
num +=1
print str(num)+')',item[u'question']
print ' a)'+item[u'option'][u'a']+'.\n b)'+item[u'option'][u'b']+'.\n ... |
authou='zhenyu'
product_list=[
('iphone',5800),
('Sunsung s7',5688),
('Watch',199),
('Coffee',32),
('Mac Pro',9800),
('Bicycle',1200),
]
shopping_list=[]
salary=int(input("input your salary: "))
while True:
for index,item in enumerate(product_list):
print(index,item)
user_choise... |
# ---------------------------------------------------------------------
#
# File : week3_q2.py
# Created : 04/10/2021 16:05
# Authort : Lukasz S.
# Version : v1.0.0
# Licencing : (C) 2021 Lukasz S.
#
# Description : Week 3 question 2
# ---------------------------------------------------... |
import random
random_list = [random.randrange(-100,100) for i in range(30)]
print("\nRandom list of numbers from -100 to 100 is: ", random_list)
maxNumber = max(random_list)
maxNumberId = 1 + random_list.index(maxNumber)
print("\nMax number:", maxNumber, "\nMax number id:", maxNumberId, "\n\n")
for i in range(29)... |
import random
symbol_wall = '|'
symbol_floor = ' '
num_columns = 50
num_lines = 20
my_labyrinth = []
def create_tile(num_columns, num_lines, column_number, line_number):
random_even = [symbol_wall] * 6 + [symbol_floor] * 6
random_odd = [symbol_wall] * 4 + [symbol_floor] * 4
if line_number == 0 or colum... |
coordinates = (1, 2, 3)
x, y, z = coordinates #shorthand for applying tuple values to variables!
print(x * z)
#can be done with a normal list as well. |
# import unittest
# unittest.main('test_wrap_nicely')
import unittest
import wrap_nicely
class TestWrapNicely(unittest.TestCase):
def test_wrap_nicely(self):
"""
test text wraps properly
"""
# Setup
string = 'A string of text to test to see if it wraps nicely'
ma... |
# Create 3 dictionaries (dict1, dict2, dict3) with 3 elements each. Perform following operations
dict1 = {"Name": "Kapil", "LastName": "Yadava", "Age": 30}
dict2 = {'CompanyID': 39, "Name": "Wipro", "Location": "Bangalore"}
dict3 = {'AssetID': 12, 'Name': 'Mac Laptop', 'Age': 2}
# a) Compare dictionaries to determine... |
# Using the built-in functions on Numbers perform following operations
import math
import random
number = 1.780838373
# a) Round of the given floating point number. Example:
# n=0.543 then round it next decimal number, i.e n=1.0 Use round() function
print(round(number))
# b) Find out the square root of a given numb... |
import sys
import time
import datetime
def vraag23():
print("de politie bied jou een verblijfsverguning aan.")
print("ze geven je ook gelijk een plekje om te verblijven met je vrienden")
time.sleep(1)
print("neem je het aan of niet")
print("A : ja je neemt het aan!")
print("B : nee je neemt nie... |
import itertools
import functools32 as functools
import networkx as nx
import utilities
def preprocess(tree, root):
"""Compute the expected distance of all possible equivalence
classes in the tree
Parameters
----------
tree : networkx.Graph()
an undirected tree
root : integer
... |
# -*- coding:utf-8 -*-
# This is the sample about the walk function in OS module
# @author Tang Ling
# @email tangling.life@gmail.com
import sys
import os,stat
import argparse
def rmdir(path):
"""Recrusivly delete all files in the given directory
Arguments:
- `path`:
"""
if os.path.exists(pat... |
# Imports
from sense_hat import SenseHat
# Global variables
sense = SenseHat()
# Functions
def celsius_to_fahrenheit(celsius):
""" Return fahrenheit as an integer. """
fahrenheit = 1.8 * celsius + 32
return int(fahrenheit)
def decimal_to_binary(num):
""" Convert a decimal integer to a list of bits. "... |
import collections
def flatten(l):
"""
Flatten a list of lists, even if they are irregular.
Original Code from https://stackoverflow.com/a/2158532/1950432
"""
for el in l:
if isinstance(el, collections.Iterable) and not isinstance(el, (str, bytes)):
yield from flatten(el)
... |
num=int(input())
carct=1
simb=1
a=1
while a<=num:
if simb%2!=0:
value='#'
elif simb%2==0:
value='%'
print(str(carct)+'-'+str(value))
carct=carct+1
simb=simb+1
a=a+1
|
#!/usr/bin/env python3
import sys
from argparse import ArgumentParser
from pathlib import Path
from deeplator import Translator, SOURCE_LANGS
if __name__ == "__main__":
parser = ArgumentParser(
description="Deeplator is an application enabling translation via the DeepL translator."
)
parser.add_a... |
def air_condition(troom, tcond, mode) -> int:
if mode == 'fan':
return troom
elif mode == 'auto':
return tcond
elif mode == 'heat':
return troom if troom > tcond else tcond
elif mode == 'freeze':
return troom if tcond > troom else tcond
def main():
troom, tcond = l... |
from collections import Counter
import re
def get_the_most_frequent_word(c, d, text, n):
is_digit_first = True if d == 'yes' else False
is_case_sensitive = True if c == 'yes' else False
text_counter = Counter()
key_words = set()
if n:
for line in text[:n]:
line = line.strip()
... |
def get_table_size(
a1, b1,
a2, b2):
tables = [
[a1+a2, max(b1, b2)],
[a1+b2, max(b1, a2)],
[b1+b2, max(a1, a2)],
[b1+a2, max(a1, b2)],
]
min_table = tables[0]
min_square = min_table[0]*min_table[1]
for table in tables:
if min_table is table... |
class Node:
def __init__(self, data=None):
self.data = data
self.out_edges = []
self.in_edges = []
def outgoing_edges(self):
return self.out_edges
def incoming_edges(self):
return self.in_edges
def edges(self):
return self.out_edges + self.in_edges
... |
"""
Tugas UAS Viky Ardiansyah
171011400218
07TPLE004
Image Processing menggunakan OpenCV untuk mendeteksi objek sederhana
IDE: Pycharm
"""
import os
from ShapeClassifier import ShapeClassifier
import argparse
# handle Command Line Arguments
parser = argparse.ArgumentParser(description='Process some integers.')
par... |
class PriceBasedAllocator():
'''
1) Resources are grouped based on regions, since each region has different price per hour for its instances
2) Alogrithm adds each resource mutliple times so that total price doesnot exceed the given cap.
3) Since the total price of each subset should not be... |
#! /usr/bin/python
# quick sort
import time
def partition(myList, start, end):
print "Called. start:%d end:%d List:" %(start, end)
print myList[start:end+1]
pivot = myList[start]
left = start+1
# Start outside the area to be partitioned
right = end
done = False
while not done:
sl... |
#! /usr/bin/python
import utils
import sys
import logging
import sortClass
class QuickSort (sortClass.SortClass):
@staticmethod
def basicSort(myList):
# If the length is one or zero
# Nothing more to do.
# List is already sorted.
size = len(myList)
if size <= 1:
return myList;
# Simplest implementat... |
p = float(input("what's the principle "))
r = float(input("what's the rate "))
n = int(input("how many periods "))
t = int(input('how many payments per period '))
pv = p * (pow((1 + r/100/n),n*t))
print(pv)
def compound_interest(p,r,n,t):
balance = p * (pow((1 + r/100/n),n*t))
ci = balance - p
print('ba... |
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution(object):
def pathSum(self, root, sum):
"""
:type root: TreeNode
:type sum: in... |
import sqlite3
# The location of the database.sqlite file, used when accessing the database.
_sqlite_file = "../../data/database.sqlite"
# The papers we have imported as an object.
papers = []
# A set of paper ids.
paper_ids = set()
# A mapping from paper id to paper.
paper_id_to_paper = {}
# The authors we have i... |
'''
* Python program to use contours to crop the objects in an image.
*
* usage: python ContourCrop.py <filename> <threshold>
'''
import cv2, sys, numpy as np
# read command-line arguments
filename = sys.argv[1]
t = int(sys.argv[2])
# read original image
img = cv2.imread(filename)
# create binary image
gray = cv2... |
def factorial(n):
i = 1
a = 1
while i <= n:
a = a * i
i = i + 1
return a
b = int(input())
print(b,"! =", factorial(b))
|
#to randomly select a word
import random as rd
#to implement GUI
import tkinter as tk
#create main window
main_window = tk.Tk()
#window size
main_window.geometry("250x250")
icon = tk.PhotoImage(file="hangman_icon.png")
main_window.iconphoto(False,icon)
main_window.title("Hangman!")
main_frame = tk.Frame(m... |
import matplotlib.pyplot as plt
import numpy as np
def line(w, th=0):
w2 = w[2] + .001 if w[2] == 0 else w[2]
return lambda x: (th - w[1] * x - w[0]) / w2
def plot(fs, s, t):
x = np.arange(-2, 3)
col = 'ro', 'bo'
for c, v in enumerate(np.unique(t)):
p = s[np.where(t == v)]
plt... |
'''
Created on Sep 17, 2010
@author: ashwin
Licensed to Ashwin Panchapakesan under one or more
contributor license agreements. See the NOTICE file distributed with
this work for additional information regarding copyright ownership.
Ashwin licenses this file to You under the Apache License, Version 2.0
(the "Lic... |
'''
Created on Sep 24, 2010
@@author: ashwin
Licensed to Ashwin Panchapakesan under one or more
contributor license agreements. See the NOTICE file distributed with
this work for additional information regarding copyright ownership.
Ashwin licenses this file to You under the Apache License, Version 2.0
(the "Li... |
import random
while True:
try:
usernumber = int(input("Guess a number, 1 through 100... "))
while usernumber != random.randrange(1,101):
print(int(input("Try again: ")))
else:
print("Congratulations, You've guessed correctly!")
input(... |
###########################################################################
##temperatures = [60,65,73,54,78,75]
##
##def avg(x):
## return sum(x) / len(x)
##
##i = 0
##while i < len(temperatures):
## print(temperatures[i], "Degress Fahrenheit")
## i += 1
##
##print("The average of all the tempe... |
import sys
while True:
def grade(x):
if x > 100:
print("Error")
elif x >= 90 and x <= 100:
print("A")
elif x >= 80 and x <= 89:
print("B")
elif x >= 70 and x <= 79:
print("C")
elif x >= 60 and x <= 69:
... |
def fib_standard(n):
if n < 2:
return 1
else:
return fib(n-1)+fib(n-2)
def fib_dynamic_programming_aux(n,F):
if n < 2:
return 1
else:
if not F[n-1]:
F[n-1] = fib_dynamic_programming_aux(n-1,F)
if not F[n-2]:
F[n-2] = fib_dynamic_programming_aux(n-2,F)
return F[n-1]+F[n-2]
def fib_dynamic_program... |
# Time: O(nlog(n) + mlog(m)), time for sorting first and second array
# Time for iteration ( which is O(max(n, m)) ) is dominated by time for sorting
# Space: O(1)
def smallestDiff(arrayOne, arrayTwo):
arrayOne.sort()
arrayTwo.sort()
i = 0
j = 0
smallest = float("inf")
current = 0
pai... |
# Time: O(log(n)) and space: O(log(n))
def binarySearch(array, target):
binarySearchHelper(array, target, 0, len(array) - 1)
def binarySearchHelper(array, target, left, right):
if left > right:
return -1
middle = (left + right) // 2
if target == array[middle]:
return middle
elif ta... |
'''
Idea is, we will use the concept of peeks and valleys, whenever we found valley we will start
expnading towards it's left and right, if we are heading to the peek, then continously increase
reward.
'''
def minRewards(array):
n = len(array)
# setting the initial reward as 1 for all students
... |
# Time: O(n^2) | Space: O(1)
def insertionSort(array):
for i in range(1, len(array)):
j = i
while j > 0 and array[j] < array[j - 1]:
array[j], array[j - 1] = array[j - 1], array[j]
j -= 1
return array
print(insertionSort([5, 10, 11, 6, 8]))
|
# Exercise 1:
# Write a WHILEloop that will print the numbers from 1 to 10 on the screen.
def printer():
i = 1
while i <= 10:
print(i)
i = i + 1
# uncomment the function caller to get the output
# printer()
# Exercise 2:
# Write a FOR loop that will print the numbers from 1 to 10 on the scree... |
##
## First Lecture
##
# Exercise 1:
# Write a Python program to ask the user for their name
# (e.g. John) and print "Hello John" on the screen
name = input("Please insert your name: ")
print("Hello {0}".format(name))
# Exercise 2:
# Write a Python program to ask the user for their name and age,
# and print them on ... |
list = []
def showError(msg):
print("输入有误,请从新输入"+msg)
def is Num(num):
if num.isdigit()
return True
else:
return false
def add():
stu = {}
while True:
name = input("请输入学生姓名")
if len(name) >= 2 and len(name)<=4:
stu["name"] = name
break
else:
showError("学生姓名必须大于2小于4")
while True:
age = input("... |
# Date : 18th August, 2021
# Given a binary array nums, return the maximum number of consecutive 1's in the array.
# Example 1:
# Input: nums = [1,1,0,1,1,1]
# Output: 3
# Explanation: The first two digits or the last three digits are consecutive 1s. The maximum number of consecutive 1s is 3.
# Example 2:
# Input: nu... |
import random as rn
print("\t\t\t\t\tHey let's play a game !")
print("\t\t\t\t\t-----------------------",end='\n\n')
print(""""How does it sounds !!
I'll pick a number randomly between 1 to 10 and you have to guess it !!!""")
ap = 0
while True:
n = rn.choice(range(1,11))
print("Enter the number you guessed :",... |
# compare x with the middle element
# if x > mid --> x is on the right
# applt again..
def bin(a,low,high,x):
if high >= low:
mid = (high + low) // 2
if a[mid] == x:
return mid
elif a[mid] > x:
return bin(a,low,mid-1,x)
else:
return bin(a,mid... |
# we have 1 number N
# find all 3 number sums combinations that are equal to N
# input: 3
# out: 90
# explain: (1*1*1) + (1*1*2) +(1*1*3) + ... = 1+2+3+4+6+9+8+12+18+27 = 90
import itertools
n = int(input('give me num: '))
c = []
for x in range(1,n+1):
for y in range(1,n+1):
for z in range(1,n+1):
... |
# the sum of 3 nums in the list should be equal to a target number, return them in sorted array or empty if none
target = 24
random_list = [12,3,4,1,6,9]
pair_list = [(random_list[x],random_list[y],random_list[z]) for x in range(len(random_list))\
for y in range(x+1, len(random_list)) for z in range(y+1,... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.