text stringlengths 37 1.41M |
|---|
print "I will now count my chickens:"
# print Hens count as summ of 25 and ratio for 30 to 6
print "Hens", 25.0 + 30.0 / 6.0
# print Roosters cont as substraction of 100 and (product 25 * 3) by module 4
print "Roosters", 100.0 - 25.0 * 3 % 4
print "Now I will count the eggs:"
# print formula result
print 3.0 + 2.0 +... |
# assign to cars integer value
cars = 100
# assign to space in the car floating point value
space_in_a_car = 4.0
# assign to drivers integer value
drivers = 30
# assign to passangers integer value
passengers = 90
# evalute substraction and assign its result to cars_not_driven
cars_not_driven = cars - drivers
# assign d... |
def sort_nd(l: list, d: int):
'''
N-dimentional merge-sort
l: input list
n: dimention to sort by
'''
n = len(l)
if n==1:
return l
else:
mid = n//2
left = sort_nd(l[ :mid], d)
right = sort_nd(l[mid: ], d)
i, j = 0, 0
result = []
while i... |
# tuple_stocks.py
import datetime
from collections import namedtuple
def middle(stock, date):
symbol, current, high, low = stock
return (((high + low) / 2), date)
def main():
# stock = "FB", 177.46, 178.67, 175.79
# stock2 = ("FB", 177.46, 178.67, 175.79)
# print(stock)
# print(stock2)
#... |
# using_dictionaries.py
stocks = {
"GOOG": (1235.20, 1242.54, 1231.06),
"MSFT": (110.41, 110.45, 109.84),
}
class AnObject:
def __init__(self, avalue):
self.avalue = avalue
def main():
# print(stocks["GOOG"])
# # print(stocks["RIM"])
# print(stocks.get("RIM"))
# print(stocks.get("RIM",... |
import numpy as np
def distance(v1, v2, d_type='d1'):
# check same shape
assert v1.shape == v2.shape, "shape of two vectors need to be same!"
if d_type == 'd1':
return np.sum(np.absolute(v1 - v2))
elif d_type == 'd2':
return np.sum((v1 - v2) ** 2)
elif d_type == 'd2-norm':
... |
"""SQLAlchemy models for Access Academy"""
from flask_bcrypt import Bcrypt
from flask_sqlalchemy import SQLAlchemy
bcrypt = Bcrypt()
db = SQLAlchemy()
class User(db.Model):
"""User of this app"""
__tablename__ = 'users'
id = db.Column(
db.Integer,
primary_key=True,
)
username =... |
import sys
import os
import array
def main():
start = 138241
end = 674034
hold_list = []
for current_passwd in range( start, end, 1 ):
if has_duplicates( current_passwd ) and is_ascending( current_passwd ):
hold_list.append( current_passwd )
print('Hold List size: {}'.format(le... |
class Car:
tax=0
def __init__(self, price, speed, fuel, mileage):
self.price = price
self.speed = speed
self.fuel = fuel
self.mileage = mileage
self.tax=.12
if (self.price>10000):
self.tax=.15
def displayAll(self):
print('Price: ',... |
"""
Name: Timothy McMahon
Student number: u5530441
"""
import numpy as np
import sys
def gen_matrix(length, b, epsilon):
"""
Generates an invertible, quasipositive matrix of dimensions length x length
length: int
b: int - the branch factor, the number of non-negligable transition probabilities
ep... |
'''
drawX function for tic tac toe.
drawX(Xturtle, x, y, d, color):drawX(Xtu
where
Xturtle is the turtle used to draw
x - is horizontal coordinate
y - is veritcle coordinate
d - diameter of the X
color is "red", "blue" or "green"
'''
i... |
fullname = raw_input("Enter Your Full Name ")
firstspace = fullname.find(" ",0)
firstname = fullname[0:firstspace]
#print("fname "+firstname)
secondspace = fullname.find(" ", firstspace+1)
middlename = fullname[firstspace+1:secondspace]
#print("mname "+middlename)
lastname = fullname[secondspace+1:]
#print("lname ... |
import random
option = ['rock', 'paper', 'scissor', 'Rock', 'Paper', 'Scissor']
computer = option[random.randint(0, 2)]
# Function for player to play using options
def plays():
playerWin = 0
computerWin = 0
ties = 0
player = True
while player == True:
player = input("\nEnter your choice ... |
'''
find_amulet: returns the chest index of the Amulet of Rivest
ARGS: magic_map(a,b): magic_map(a,b) returns true if the Amulet
is the chest index i where a <= i < b.
RETURN: index of chest containing amulet
HINT: magic_map(a,a+1) returns true iff the Amulet is in chest a
magic_map(1,float('inf')) will always return ... |
from collections import deque
from heapq import *
class Queue(object):
# Initialize an empty queue
def __init__(self):
self.items = deque()
# Return the length of this queue
def __len__(self):
return len(self.items)
# Add a new item
def push(self, item):
self.items.a... |
#Name: Lur Bing Huii
#Student ID: 6212748
#Subject Code: CSIT110
import csv
filePath = "data.csv"
# Display Menu and get's user input
def menu():
print("1: Display modules average scores")
print("2: Display modules top scorer")
print("0: Exit")
choice = int(input("Enter choice: "))
# ... |
while True:
userName = input("Username: ")
password = input("Password: ")
if userName == 'halil' and password == 'halil':
print("correct username and password")
break
else:
print("wrong username and password")
break
|
import random
def menu():
choice = input("----------------------------------------\nWelcome To 2Password\n1 - Check Password\n2 - Generate Password\n3 - Quit\n>>> ")
while choice != '1' and choice != '2' and choice != '3':
choice = input("ERROR\n>>> ")
print("--------------------")
if choice ==... |
import gym
from gym import spaces
from gym.utils import seeding
def cmp(a, b):
return float(a > b) - float(a < b)
# 1 = Ace, 2-10 = Number cards, Jack/Queen/King = 10
deck = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10]
def draw_card(np_random):
return int(np_random.choice(deck))
def draw_hand(np_random):
... |
import tensorflow as tf
import google.datalab.ml as ml
"""
Linear Regression:
An analysis on the relationship between 2 variables where one variable is taken
to be independent and the other a dependent.
y = mx + c
The linear regression could be thought as cause and effect, or a lock and key scenario
This could be pl... |
import tensorflow as tf
import google.datalab.ml as ml
"""
Tensors:
1. Building a graph
2. Running a graph
Tensor could be defined as a central unit of data in tensor flow.
A Tensor consists of a set of primitive values shaped into an array of any
number of dimensions.
Ho do we represent data in tensors?
If data ... |
import numpy as np
import matplotlib.pyplot as plt
"""
Covariance:
Measures how two variables vary in tandem from their means.
Measuring covariance:
Think of the data sets for the two variables as high dimensional vectors
Convert these to vectors of variances from the mean
Take the dot product(consine of the angle be... |
# def isPhoneNumber(text):
# if len(text) != 12:
# return False
# for i in range(0, 3):
# if not text[i].isdecimal():
# return False
# if text[3] != '-':
# return False
# for i in range(4, 7):
# if not text[i].isdecimal():
# ret... |
#! /usr/bin/env python3
# -*- coding: utf-8 -*-
'''Lecture 02, Exercise 08
Run dir(random). Find a function in random that you can use to return a
random item from your grocery list. Remember you can use help() to find out
what different functions do!
'''
import random
shopping_list = {'milk':9.42, 'eggs':5.67, 'brea... |
#! /usr/bin/env python3
# -*- coding: utf-8 -*-
'''Lecture 03, Exercise 04
Write an in_grocery_list function that takes in a grocery_item print a message
depending on whether grocery_item is in your grocery list.
'''
def in_grocery_list(grocery_item):
shopping_list = ['milk', 'eggs', 'bread', 'apples', 'tea']
... |
#! /usr/bin/env python3
# -*- coding: utf-8 -*-
''' Lecture 02, Exercise 24
Write a function called 'Volume2' which calculates the box volume, assuming
the height is 1, if not given.
'''
def volume2(width, length, height=1):
return(width * length * height)
print(volume2(2, 5))
|
#! /usr/bin/env python3
# -*- coding: utf-8 -*-
'''Lecture 03, Exercise 06
Challenge: Re-write the you_won function to randomly choose a number from your
price list and print an appropriate messsage depending on whether you won (the
number was greater than 10) or not. Also include the amount of change you will
be rece... |
#! /usr/bin/env python3
# -*- coding: utf-8 -*-
''' Lecture 02, Exercise 28
Make a function shout(word) that accepts a string and returns that string in
capital letters with an exclaimation mark.
'''
def shout(word):
return(word.upper() + '!')
print(shout('bananas'))
|
#! /usr/bin/env python3
# -*- coding: utf-8 -*-
'''Lecture 02, Exercise 12
You may have noticed that your all_the_snacks function prints all your snacks
squished together. Rewrite all_the_snacks so that it takes an additional
argument spacer. Use + to combine your snack and spacer before multiplying.
Test your functio... |
#! /usr/bin/env python3
# -*- coding: utf-8 -*-
'''Lecture 02, Exercise 18
Try running all_the_snacks with your favourite snack and the spacer '! ' and
no additional inputs. How would you run it while inputting your favourite snack
and 42 for num while keeping the default spacer? Can you use this method to enter
space... |
#! /usr/bin/env python3
# -*- coding: utf-8 -*-
'''Lecture 05, Exercise 03
Copy the sonnet from https://urn.nsa.ic.gov/t/tx6qm and paste into sonnet.txt.
Write the counts dictionary to a file, one key:value per line.
'''
def word_count_file(input_filename, output_filename):
input_file = open(input_filename, 'r')... |
import secrets
options = ['paper', 'rock', 'scissors']
computer = secrets.choice(options)
while True:
player = input("player: pick rock, paper or scissors ")
if player == "exit":
print("Thanks for playing friend! see you later.")
break
if player == computer:
print("it's a draw!")
elif player == "paper" and c... |
class GRAPH:
"""docstring for GRAPH"""
def __init__(self, nodes):
self.nodes=nodes
self.graph=[[0]*nodes for i in range (nodes)]
self.visited=[0]*nodes
def show(self):
print self.graph
def add_edge(self, i, j):
self.graph[i][j]=1
self.graph[j][i]=1
... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Aug 12 09:08:24 2018
@author: apb
"""
"""
print all the operations were performed element wise.
"""
import numpy as np
a=np.array([[2,4,6],[4,3,7]],dtype=np.float)
b=np.array([[5,4,2],[3,5,9]],dtype=np.float)
print(a)
print(b)
print('\nHere goes a-b')... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Aug 10 11:01:02 2018
@author: apb
"""
books=[]
books.append('c++')
books.append('java')
print(books)
books.reverse()
print(books)
books.insert(2,'new one')
print(books)
# del any book by index
del books[1]
print(books)
#remove books by name
books.rem... |
# car_game.py using pygame and pymunk
import random
import math
import numpy as np
import pygame
from pygame.color import THECOLORS
import pymunk
from pymunk.vec2d import Vec2d
from pymunk.pygame_util import draw
# initial variables to set up the pygame
width = 1000
height = 700
# initialize the game and set the s... |
def gcd(a: int, b: int) -> int:
""""Greatest Common Denominator.
"""
if a > b:
r = a % b
started = False
while r != 0:
started = True
r = a % b
a = b
b = r
if started:
return a
else:
return b
... |
#!/bin/python3
"""
A palindromic number reads the same both ways. The largest palindrome
made from the product of two 2-digit numbers is 9009 = 91 × 99.
Find the largest palindrome made from the product of two 3-digit numbers.
"""
def solLogic():
# Stores a list of all Palindrome found
listofpali = []
... |
'''
Created on Mar 31, 2017
@author: ankur.sethi
'''
mylist=[[300,101,200],['Paul',212,'dds'],[212,331,12]]
for val in mylist:
for v in val:
print(v, end=" ")
|
# used with the csv files mentioned...
# This program simply searches a database filled with names of cities
# and their corresponding postal codes, then matches it with a file full
# of postal codes and no city names. This was used because a exported
# copy of a client list did not include which city the client was fr... |
import json
import requests
import sqlite3
api_key = 'YgZQoqt8gAna0G0koZRFZrCoUgDOA14QK3zMYEYfgEzwzbtLqXRuanUqQdtlnqjQtRRhpNx1E-KBnyQrAqtSsjaH1-GI-Bi0DdqApdgcUbuIz6cj4SwnAcXoSUXlXXYx'
url = 'https://api.yelp.com/v3/businesses/search'
#authorization from Yelp
headers = {'Authorization': 'Bearer %s' % api_key,}
#cha... |
# -*- coding: utf-8 -*-
"""
Created on Mon Feb 15 10:42:43 2016
@author: raviteja
"""
import matplotlib.pyplot as plt
import numpy as np
# this function is used to find the mean square error
def mse(Z,theta,Y):
Yt =prediction(theta,Z) # this line takes to prediction function
difference = (Yt.T-Y)**2
... |
# Массив 10 строк на 10 столбцов служит игровым полем
# Map - с большой буквы чтобы не путалось с внутренней функцией пайтона (map)
Map = [[], [], [], [], [], [], [], [], [], []]
# Заполнение игрового поля нулями
row_number = 0
for row in Map:
for column in range(10):
row.append(0)
# Добавляет... |
#!/usr/local/bin/python
# -*- coding: utf-8 -*-
"""
This module uses an wikipedia api and PyMongo to store
information from wikipedia pages and save them into a database
in order to perform queries upon them
"""
import wikipedia
from threading import Thread, Semaphore
import schedule
import pymongo
MONTH_NAMES = ['... |
"""
push X: 정수 X를 큐에 넣는 연산이다.
pop: 큐에서 가장 앞에 있는 정수를 빼고, 그 수를 출력한다. 만약 큐에 들어있는 정수가 없는 경우에는 -1을 출력한다.
size: 큐에 들어있는 정수의 개수를 출력한다.
empty: 큐가 비어있으면 1, 아니면 0을 출력한다.
front: 큐의 가장 앞에 있는 정수를 출력한다. 만약 큐에 들어있는 정수가 없는 경우에는 -1을 출력한다.
back: 큐의 가장 뒤에 있는 정수를 출력한다. 만약 큐에 들어있는 정수가 없는 경우에는 -1을 출력한다.
"""
# class 풀이
# Class 정의
cla... |
from datetime import date
def examples():
d0 = date(2014, 1, 1)
d1 = date(2020, 8, 25)
delta = d1 - d0
print(delta.days + 1)
def calculate_days(idate):
#print(date)
# print( "{} - {} - {} ".format(idate[0:4], idate[4:6], idate[6:8]) )
f_date = date(2014, 1, 1)
l_date1 = dat... |
#!/usr/bin/env python
"""
This is the python script describing the game rules for Tower's of Hanoi Game Puzzle.
In this file exists 3 classes which are the game objects to create the game - TowerGame, Peg, Disk
"""
__author__ = "Adam Pucciano"
__date__ = "4/15/2021"
__version__ = "1.2"
__email__ = "adam... |
from pygame import Vector2
import pygame
from graphics.drawing_surface import DrawingSurface
class Screen:
"""A class for managing the application window.
Attributes:
`font`: A pygame.font.Font
`surface`: A DrawingSurface
Corresponds to the whole Screen area
About dirty rects:... |
class FloatRect:
"""Similar class to pygame.Rect but with floats"""
def __init__(self, x, y, width, height):
"""Initializes FloatRect
Arguments:
`x`: float
x coordinate of the top left corner
`y`: float
y coordinate of the top left corner... |
import logging
import sys
import math
from abc import ABC, abstractmethod
from game.shapes import Rectangle
from graphics.image import Image
from utils.float_rect import FloatRect
class Graphic(ABC):
"""A base class for movable and rotatable graphics.
Attributes:
`location`: A pygame.Vector2
... |
class Node():
def __init__(self,value):
self.value = value
self.left = None
self.right = None
def bst(arr):
bst1(arr,0,len(arr)-1)
def bst1(arr,start,end):
if start > end:
return
mid = (start + end) // 2
node = Node(arr[mid])
node.left = bst1(arr,start,mid-... |
import unittest
"""
Expressions written in postfix expression are evaluated faster compared to infix notation
as postfix does not require parenthesis. Write program to evaluate postfix expression.
"""
"""
Approach:
1. Scan postfix expression from left to right.
2. If element is operand, we push it on the stack.
3. If ... |
import unittest
"""
Given a string, find the longest substring which is a palindrome.
Input: forgeeksskeegfor
Output: geeksskeeg
"""
def longest_palindromic_substring(string):
n = len(string)
# table[i][j] is the length of palindromic substring starting at str[i] and ending at str[j].
# The max value in t... |
import unittest
"""
Given a string, find the length of the longest substring without repeating characters.
Input: ABDEFGABEF
Output: 6
"""
"""
Approach:
1. Scan the given string from left to right.
2. For each character, maintain the most recent index where that character was last seen.
3. If a repeated character is f... |
import unittest
"""
Given n non negative integers representing an elevation map where width of each bar is 1,
compute how much water it is able to trap after raining.
Input: 2 0 2
Output: 2
Input: 3 0 0 2 0 4
Output: 10
"""
"""
Approach:
1. A bar can store water if there are taller bars to its left and right.
2. We ca... |
import unittest
"""
Given an array with positive and negative numbers, find the maximum average subarray of given length.
Input: 1 12 -5 -6 50 3, k = 4
Output: 1 (12-5-6+50)/4
"""
def max_avg_subarray(list_of_numbers, k):
assert len(list_of_numbers) >= k
cur_max = sum(list_of_numbers[0:k])
cur_max_index ... |
import unittest
"""
Given an array, print next greater element. The NGE for an element x is the first greater
element on the right side of x in the array. Elements for which no greater element exist,
print -1.
Input: {4, 5, 2, 25}
Output: {5, 25, 25, -1}
"""
def next_greater(arr):
nge = [-1] * len(arr)
stack ... |
import unittest
"""
Given an array containing only 0s and 1s, find the largest subarray which contain equal
number of 0s and 1s.
Input: 1 0 1 1 1 0 0
Output: 1 to 6
Input: 1 1 1 1
Output: No subarray
Input: 0 0 1 1 0
Output: 0 to 3 OR 1 to 4
"""
"""
Approach:
1. Scan the array from left to right.
2. For each index i, ... |
import unittest
"""
There are n pairs and therefore 2n people. Everyone has a unique number ranging from 1 to 2n.
All these 2n persons arranged in random fashion in an array of size 2n. We are also given who is
partner of whom. Find the minimum number of swaps required to arrange these pairs such that all pairs
become ... |
"""
Given a singly linked list, swap kth node from beginning with kth node from end.
Swapping of data is not allowed, only pointers should be changed.
"""
def swap_kth_nodes(head, k):
n = count_nodes(head)
if k > n:
return head
# kth from beginning == kth from end
if n == 2*k-1:
retu... |
import unittest
"""
You are given n pairs of numbers. In every pair first number is always smaller than second number.
A pair (c,d) can follow another pair (a,b) if b < c.
Chain of pairs can be formed in this fashion.
Find the longest chain which can be formed from a given set of pairs.
Input: (5,24),(39,60),(15,28),(2... |
"""
Find whether a given undirected graph has a cycle. NOTE: Another way to do this is using Union-Find algorithm.
"""
"""
Approach:
1. The idea is to perform a DFS starting from every vertex.
2. Along with standard DFS stuff, we also pass the parent node which started the DFS.
Example, If we are doing DFS at u, a... |
import unittest
"""
Diameter of a binary tree is number of nodes on longest path between any two leaves in the tree.
Recursive definition of diameter =
max(diameter of left subtree, diameter of right subtree, 1 + height of left subtree + height of right subtree).
The first two cases are when diameter path does not incl... |
import unittest
"""
Given an array A, find the size of longest bitonic subarray A[i...j]
such that A[i] <= A[i+1] <= ... <= A[k] >= A[k+1] >= ... >= A[j-1] >= A[j]
Input: 12 4 78 90 45 23
Output: 5 (4 78 90 45 23)
"""
"""
Approach:
1. This is similar to finding max j-i such that a[j]>a[i]
2. Compute two auxiliary arra... |
import unittest
"""
Given an array of distinct integers, find the length of the longest subarray which contains
numbers that can be arranged in a contiguous sequence.
Input: 10 12 11
Output: 3
Input: 14 12 11 20
Output: 2
Input: 1 56 58 57 90 92 94 93 91 45
Output: 5
"""
"""
Approach:
1. Since all elements are distinc... |
import unittest
"""
Given two lists, generate all possible weaving of the lists such that the relative order is
maintained.
Input: [1, 2] and [3, 4]
Output:
[1, 2, 3, 4]
[3, 4, 1, 2]
[1, 3, 2, 4]
[3, 1, 2, 4]
[1, 3, 4, 2]
[3, 1, 4, 2]
"""
def weaving(list1, list2):
if len(list1) == 0:
return [list2]
i... |
"""
Given an array of length n, return the majority element - An element that occurs more than n/2 times.
Input : 3 3 4 2 4 4 2 4 4
Output : 4
Input : 3 3 4 2 4 4 2 4
Output : None
"""
import unittest
"""
Approach 1:
1. Initialize a dictionary
2. If item not present, insert it with count = 1
3. If item already present... |
import unittest
"""
Given a value N, if we want to make change for N cents, and we have an infinite supply
of each S = {S1, S2, ..., Sm} valued coins, how many ways can we make the change?
Input: N = 4, S = {1, 2, 3}
Output: {1,1,1,1}, {1,1,2}, {2,2}, {1,3} so total 4 ways.
"""
def coin_change_2(N, S):
num_denoms... |
"""
Print the left view of binary tree. These are the nodes which are visible if
binary tree is viewed from left direction.
"""
class Node:
def __init__(self, data, left=None, right=None):
self.data = data
self.left = left
self.right = right
class BinaryTree:
def __init__(self, root)... |
import unittest
"""
Given two strings, str and pat, find smallest substring in str containing all characters from pat.
NOTE: Assume str and pat only contain ASCII characters.
Input: str = "geeksforgeeks", pat = "ork"
Output: "ksfor"
"""
"""
Approach:
1. Use a sliding window.
2. Keep a count of each character in pat.
3... |
import unittest
"""
Given an array of positive and negative numbers in random order, rearrange the array elements
so that positive and negative numbers are placed alternatively. If one type of numbers is more
than half, the extra ones appear at end of array.
Input: -1 2 -3 4 5 6 -7 8 9
Output: 9 -7 8 -3 5 -1 2 4 6
"""
... |
"""
This Graph implementation maintains a vertex-indexed array of lists of integers. Every edge appears
twice: if the edge connects v and w, then w appears in v's list and v appears in w's list. The second constructor
reads a graph from an input stream, in the format V followed by E followed by a list of pairs of int v... |
import unittest
"""
Given a sorted array of positive numbers, find the smallest positive integer value that
cannot be represented as sum of any subset of given array.
Input: 1 3 6 10 11 15
Output: 2
Input: 1 1 1 1
Output: 5
Input: 1 1 3 4
Output: 10
Input: 1 2 5 10 20 40
Output: 4
Input: 1 2 3 4 5 6
Output: 22
"""
"""... |
import unittest
"""
You are given a binary tree in which each node contains an integer value (which might be positive or negative)
Design an algorithm to count the number of paths that sum to a given value. The path does not need to start or
end at the root or a leaf, but it must go downwards (traveling only from paren... |
import unittest
"""
Given a set of non-negative integers, and a value sum, determine if there is a subset of the given set
with sum equal to given sum.
Input: set: 3 34 4 12 5 2, sum: 9
Output: True (3,4,2) or (4,5)
"""
"""
Approach:
1. Let isSubsetSum(set, n, sum) denote if there is a subset within set of n elements ... |
import unittest
"""
Given an input string and a dictionary of words, find out if the input string
can be segmented into a space-separated sequence of dictionary words.
Consider the following dictionary
{ i, like, sam, sung, samsung, mobile, ice,
cream, icecream, man, go, mango}
Input: ilike
Output: Yes
The string ca... |
import random
count1=0
count2=0
n = random.randint(1,100)
print('''Welcome to the Banana Guessing Game
Dave hid some bananas. Your task is to find out the number of bananas he hid. Players have to compete bewteen each other to see who can guess the number of bananas first!.''')
while n>0:
y=int(input("Play... |
a=[]
y=0
while y<10:
L=input("Please enter a word.\n")
if L[0]=="A" or L[0]=="E" or L[0]=="I" or L[0]=="O" or L[0]=="U" or L[0]=="a" or L[0]=="e" or L[0]=="i" or L[0]=="o" or L[0]=="u":
a.append(L)
y=y+1
else:
y=y+1
while y==10:
print(a)
break
|
#122. Best Time to Buy and Sell Stock II
#Medium
#5241
#2172
#Add to List
#Share
#You are given an integer array prices where prices[i] is the price of a given stock on the ith day.
#On each day, you may decide to buy and/or sell the stock. You can only hold at most one share of the stock at any time. However, you... |
x = 2
y = 3
x = y
print(x)
print(x==y)
print(x>y)
print(x<y)
soma = x + y
print(soma == x)
print(soma == y)
print(soma < y)
print(soma > x) |
from collections import deque
def score(player):
result = 0
i = 1
while player:
x = player.pop()
result += x * i
i += 1
return result
def play(p1, p2):
while p1 and p2:
a = p1.popleft()
b = p2.popleft()
if a > b:
p1.append(a)
... |
# The football.csv file contains the results from the English Premier League.
# The columns labeled ‘Goals’ and ‘Goals Allowed’ contain the total number of
# goals scored for and against each team in that season (so Arsenal scored 79 goals
# against opponents, and had 36 goals scored against them). Write a program t... |
import sys
for query in sys.stdin:
# Take query and process it
query = query.strip().upper().split()
# If length of query is 1 (so 1 search term)
if len(query) == 1:
genre_first = query[0] # genre1 is genre to search for
with open('part3/movieInformation', 'r') as f:
for l... |
#O(n^2) time
#O(1) space
def bubblesort(lst):
swapped=True
size = len(lst)
while swapped:
swapped=False
for i in xrange(size):
if i+1<size and lst[i] and lst[i+1] and lst[i]>lst[i+1]:
lst[i],lst[i+1]=lst[i+1],lst[i]
swapped=True
return lst
if __name__ == '__main__':
print bubblesort([... |
import unittest
from typing import List
from utility.tree_node import TreeNode
class Solution:
# Recursive solution
def postorderTraversal_recursion(self, root: TreeNode) -> List[int]:
result = []
if root is not None:
if root.left is not None:
left = self.postorder... |
import random
name = input("enter your name : ").title()
print("Hello {} Welcome to Hangman Game".format(name))
print("Disclaimer: You need to guess the word within n+2 number of tries else you will lose the game where n is the length of the word")
print("lets start playing!!!")
words = ["apple","mango","orange","po... |
'''
Created on 2014. 4. 13.
@author: Alice
'''
def file_into_problem(file_name):
problem = {}
with open(file_name, 'r+') as f:
case_number = int(f.readline())
problem['case_number'] = case_number
problem['cases'] = []
for i in xrange(case_number):
problem_text = f.... |
class Coffee:
def __init__(self, hot_water, hot_milk, ginger_syrup, sugar_syrup, tea_leaves_syrup):
self.hot_water = hot_water
self.hot_milk = hot_milk
self.ginger_syrup = ginger_syrup
self.sugar_syrup = sugar_syrup
self.tea_leaves_syrup = tea_leaves_syrup
class HotT... |
#!/usr/bin/python3
import sys
import csv
import twitter
import time
import random
import configparser
def parse_file(file_name):
print(file_name)
people = list()
with open(file_name, 'r') as csvfile:
reader = csv.reader(csvfile, delimiter=';')
for line in reader:
people.append(... |
# 나이순 정렬 [ 티어 : 실버 5 ]
# https://www.acmicpc.net/problem/10814
from sys import stdin
N = int(stdin.readline())
member_list = []
for _ in range(N):
age, name = map(str, stdin.readline().split())
member_list.append((int(age), name))
member_list.sort(key = lambda member: (member[0]))
for member in member_list:
p... |
# age = 18
# name = 'bxl'
# print('{0} was {1} yeas old'.format(name,age))
# print('string must in "" by {0}'.format(name))
# printStr=name+'is'+str(age)+'yeas old'
# print(printStr)
# print('{0:.5f}'.format(1/6),end='this is end')
# print('{0:-^18}'.format('9'))
# i = 5
# print('{0}'.format(i))
# i = i+1
# print(i)
s ... |
import numpy
def survival_curve_from_lifespans(lifespans, uncertainty_interval=0):
"""Produce a survival curve from a set of lifespans with optional uncertainty.
If no uncertainty interval is provided, produce a standard, stair-step survival
curve (which indicates infinite precision in when the time of de... |
import numpy
def weighted_mean_and_std(x, w):
"""Return the mean and standard deviation of the data points x, weighted by
the weights in w (which do not need to sum to 1)."""
w = numpy.array(w, dtype=float)
w /= w.sum()
x = numpy.asarray(x)
weighted_mean = (w*x).sum()
squared_diff = (x - we... |
import numpy
import itertools
def fit_polynomial(image, mask=None, degree=2, poly_args=None):
"""Return an array containing the values of a polynomial fit to the input.
Parameters:
image: 2D array.
mask: if specified, use only the values in the image at points where
the mask is tru... |
import collections
import numpy
from scipy.stats import kde
from skimage import measure
def density_at_points(data):
"""Use KDE to calculate the probability density at each point in a dataset.
Useful for coloring points in scatterplot by the density, to better help
visualize crowded regions of the plot.
... |
# Create a function that will take all your coins and convert it to the cash amount.
# The function should look at each key (pennies, nickels, dimes and quarters) and perform the appropriate math on the integer value to determine how much money you have in dollars. Store that value in a variable named `dollarAmoun... |
from turtle import Turtle, goto
import turtle
class Scoreboard(Turtle):
def __init__(self):
super().__init__()
self.points = 0
self.pu()
self.color("white")
self.speed("fastest")
self.goto(0, 280)
self.ht()
self.write(f"Score = {self.points}", align... |
#-*- coding: utf-8 -*-
# 2016-2017 Programacao 1 (LTI)
# Grupo 60
# 43558 Nuno Amaral Soares
# 50021 Bruno Miguel da Silva Machado
from dateTime import *
from constants import *
def createHeader (day, time, type):
"""
Creates a header for an output file, according to
the project's specification
... |
import time
# Code by Matthew Freeman
# Use python 3 to run
class lfsr:
# Class implementing linear feedback shift register.
# This class helps produce psedo random numbers.
# algorithim was found here: https://www.maximintegrated.com/en/design/technical-documents/app-notes/4/4400.html
def ... |
# PROBLEM 1: PAYING THE MINIMUM
def interest_rate(balance, annualInterestRate, monthlyPaymentRate):
"""
balance = balance of the payment
annualInterestRate = self-explaining
monthlyPaymentRate = self-explaining
"""
monthlyInterestRate = (annualInterestRate/12.0)
totalPaid ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.