text stringlengths 37 1.41M |
|---|
'''
Fahrenheit to Celsius:
Write the necessary code to read a degree in Fahrenheit from the console
then convert it to Celsius and print it to the console.
C = (F - 32) * (5 / 9)
Output should read like - "81.32 degrees fahrenheit = 27.4 degrees celsius"
'''
# I do not understand 'read...from the conole' but ... |
import itertools
def cumulative_sum(lst):
return list(itertools.accumulate(lst))
list1 = [1, 2, 3]
list2 = [1, -2, 3]
list3 = [3, 3, -2, 408, 3, 3]
print(cumulative_sum(list1))
print(cumulative_sum(list2))
print(cumulative_sum(list3))
# リスト内包表記 reference (shorturl.at/uBMW7)
# sum() could take a list as an arg... |
import collections
def palindrome(word: str):
c = collections.Counter(word)
count = 0
for c_val in c.values():
if c_val % 2 == 0 and count < 2:
count = count
elif c_val % 2 != 0 and count < 2:
count += 1
else:
return False
return True
|
"""
HTCS6702 - Cryptography Semester 1 2021
Week 3 Homework - Kris Pritchard / @krp
Homework: For Week 3 homework you're going to create a small Python program which
solves what you were doing with pen & paper in Week 2.
You don't need to change this file.
"""
from helper_functions import binary
"""
Firstly we need... |
# Using the print() function. Lines that begin with # are "comments" and are ignored by Python. They're used to tell other programmers (or yourself) what you want the code to do -- not necessarily what the code actually does.
print('hello')
print(123)
print(42.0324)
print(1 + 2) # Comments can also go at the end ... |
conversion_table = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A' , 'B', 'C', 'D', 'E', 'F']
def decTohex(n):
if(n<=0):
hexa = ''
else:
remainder = n%16
hexa = decTohex(n//16)+conversion_table[remainder]
return hexa
def str_to_hex(input_string):
for character in... |
'''
75. Sort Colors
https://leetcode.com/problems/sort-colors/
For this problem, your goal is to sort an array of 0, 1 and 2's
but you must do this in place, in linear time and without
any extra space (such as creating an extra array).
This is called the Dutch national flag sorting problem.
For example, if the input... |
'''
5. Longest Palindromic Substring
https://leetcode.com/problems/longest-palindromic-substring/
Given a string s, return the longest palindromic substring in s.
Example 1:
Input: s = "babad" -> "bab"
Note: "aba" is also a valid answer.
Input: s = "cbbd" -> "bb"
Input: s = "a" -> "a"
Input: s = "ac" -> "a"
'''
cl... |
"""
FIFO
enqueue: To add a new data element at the rear of the queue.
dequeue: To remove an element from the front of the queue.
isEmpty: To return True if the queue is empty, else return False.
size: To check the size of the queue, in other words count the number
of elements in the queue and return it.
show: To print ... |
# solution 1:
def reverse(str):
if str == '':
return ''
else:
return reverse(str[1:]) + str[0]
# solution 2:
def reverse(str):
if len(str) <= 1:
return str
else:
mid = len(str) // 2
leftPart = str[0:mid]
rightPart = str[mid:]
return reverse(righ... |
'''
146. LRU Cache
https://leetcode.com/problems/lru-cache/
Design a data structure that follows the constraints of a Least Recently Used (LRU) cache.
Implement the LRUCache class:
LRUCache(int capacity) Initialize the LRU cache with positive size capacity.
int get(int key) Return the value of the key if the key exis... |
'''
695. Max Area of Island
https://leetcode.com/problems/max-area-of-island/
Given a non-empty 2D array grid of 0's and 1's, an island is a group of 1's
(representing land) connected 4-directionally (horizontal or vertical.)
You may assume all four edges of the grid are surrounded by water.
Find the maximum area of a... |
'''
42. Trapping Rain Water
https://leetcode.com/problems/trapping-rain-water/
Given n non-negative integers representing an elevation map where the width of each bar is 1,
compute how much water it can trap after raining.
Example 1:
Input: height = [0,1,0,2,1,0,1,3,2,1,2,1]
Output: 6
Explanation: The above elevation... |
'''
LeetCode 152. Maximum Product Subarray
https://leetcode.com/problems/maximum-product-subarray/
Given an integer array nums, find the contiguous subarray within an
array (containing at least one number) which has the largest product.
Example 1:
Input: [2,3,-2,4] -> 6
Explanation: [2,3] has the largest product 6.
... |
'''
Check if N and its Double exits
'''
def checkExists(arr):
_hash = set(arr)
for num in arr:
half, double = num / 2, num * 2
if half in _hash or double in _hash:
return True
return False
assert checkExists([2, 5, 6, 4, 9]) == True
assert checkExists([8, 5, 6, 4, 1]) == T... |
'''
https://www.codespeedy.com/kmp-string-matching-algorithm-in-python/
'''
def KMP_String(pattern, text):
a = len(text)
b = len(pattern)
prefix_arr = get_prefix_arr(pattern)
initial_point = []
i, j = 0, 0
while i != a:
if text[i] == pattern[j]:
i += 1
j +=... |
'''
74. Search a 2D Matrix
https://leetcode.com/problems/search-a-2d-matrix/
https://levelup.gitconnected.com/make-way-for-the-matrix-a-complete-guide-to-solving-2d-array-coding-problems-725096d122d9
Write an efficient algorithm that searches
for a value in an m x n matrix. This matrix has the following properties:
In... |
# Tree traversals
# Traversing a tree means visiting every node in the tree.
class Node:
def __init__(self, item):
self.left = None
self.right = None
self.val = item
def preorder(root):
'''Root, Left, Right'''
data = []
def traverse(root):
if not root:
r... |
'''
Find the most frequent element in an array
Problem Description: Given an array A[] of size n, find the most frequent element in the array,
i.e. the element which occurs the most number of times.
It is assured that at least one element is repeated.
For example:
Input: A[] = [3, 9, 1, 3, 6, 3, 8, 1, 6]
Output: 3
... |
'''
Graph breadth first search
Given an undirected graph of integers graph, represented by an adjacency list,
and an integer root, create a function that prints its values in breadth first search,
by considering the vertex whose value is root as the arbitrary node.
Example 1:
Input: graph = {
"5" : [8, 1, 12],
... |
class enPiT:
def __init__(self,money,sales,item_price,sold_out):
self.money = money
self.sales = sales
self.item_price = item_price
self.sold_out = sold_out
#売上を読み込む
def read_sales(self):
f = open("sales.txt", "r")
sales = f.read()
f.close()
... |
import unittest
def determinant(matrix):
num_row = len(matrix)
for row in matrix:
if len(row) != num_row:
print("Not a square matrix.")
return None
if num_row == 1:
return matrix[0][0]
else:
sign = -1
result = 0
for i in range(num_row):
... |
from sys import argv
script, input_file = argv
def print_all(f):
print f.read()
def rewind(f):
f.seek(0) #goes to the 0 byte in file
def print_a_line(line_count, f):
print line_count, f.readline()
#it would be great if I would stop getting tripped up
#by lack of defined arguments WHILE STILL IN... |
#pythagorean expectation, from some guy on github
RS = float(raw_input("My crap team has scored this many runs: "))
RA = float(raw_input("My crap team has allowed this many runs: "))
pynum = RS**2
print pynum
pyden = (pynum+RA**2)
print pyden
pyth = pynum/pyden
print pyth
print "This should be your crap team\'s win rat... |
class Semiprime:
# -
# This function checks if the given natural number is semiprime, that is, if
# it's a natural number that is a product of exactly two (not necessarily
# distinct) primes.
#
def isSemiprime( self, x ):
x = int(x)
if( x ... |
"""
You are going to be given an array of integers. Your job is to take that array
and find an index N where the sum of the integers to the left of N is equal to
the sum of the integers to the right of N. If there is no index that would make this happen, return -1.
For example:
Let's say you are given the array {1,... |
# -*- coding: utf-8 -*-
# Brief: The simple drawer used to draw figures easily.
# Author: Gong
# Date: 2020.09.10
#
from matplotlib import pyplot as plt
import numpy as np
from mpl_toolkits.mplot3d import Axes3D
def draw3d(func, inputs=None, input_range=None):
fig = plt.figure()
ax = Axes3D(fig)
... |
class Student(object):
def __init__(self, name, age, cardnum, pin, ):
self.name = name
self.age = age
self.cardnum = cardnum
self.pin = pin
def CashWithdrawl (self, cashOut):
self.cashOut = cashOut
#Now we do the Magic bit.Now Now, you don't need to mess it ... |
manyThings = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
print("Show each number in the list:")
for number in manyThings:
print(number)
print("Show each number in the list times 6:")
for number in manyThings:
print(number * 6)
# try and add some things to the myList below and write a basic for loop:
listOfIntegers = [5, 1... |
# Simulate 7-sided die
# You have a function rand5() that generates a random integer from 1 to 5.
# Use it to write a function rand7() that generates a random integer from 1 to 7.
from random import randint
# use randint(0,4)
def rand7():
roll = randint(0,4) * 5 + randint(0,4) + 1
while (roll > 21):
... |
# Top score
# Write a function that takes:
# 1. a list of unsorted_scores
# 2. the highest_possible_score in the game
# and returns a sorted list of scores in less than O(nlgn) time.
def sort_scores(scores, highest_possible_score):
sorted = []
counts = [0] * (highest_possible_score + 1)
for score in sc... |
# Parenthesis matching
# "Sometimes (when I nest them (my parentheticals) too much
# (like this (and this))) they get confusing."
# Write a function that, given a sentence like the one above,
# along with the position of an opening parenthesis,
# finds the corresponding closing parenthesis.
def find_closing(string, ... |
#!/usr/bin/python
import os
import datetime
i = datetime.datetime.now()
#turns input of an array of chars into an array of integers from every two chars interpreted as hex values
def createHexIntValues(charValues):
i = 0
hexValues = []
while i < len(charValues):
#end condition is no more values
value = '0x' + ... |
import player
from player import *
def play_game(p1, p2):
g1 = Game()
while not g1.game_over:
if (g1.turn == p1.piece):
if (p1.ishuman):
print (g1)
p1.make_move(g1)
p2.correct_the_reward(g1)
else:
if (p2.ishuman):
... |
#!/usr/bin/env python
def isLeapYear(year):
return (year % 4 == 0 and year % 100 != 0) or year % 400 == 0
def getDaysOfMonth(year, month):
days = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
if isLeapYear(year):
days[1] = 29
return days[month - 1]
def countMonthsWithFirstDaySunday():... |
#!/usr/bin/env python
def isPythagoreanTriplet(a, b, c):
return a ** 2 + b ** 2 == c ** 2
def findPythagoreanTripletProduct():
for a in range(1, 1000):
for b in range(1, 1000):
c = 1000 - a - b
if isPythagoreanTriplet(a, b, c):
return (a * b * c)
print(findP... |
import emoji
import re
'''
Used for extracting emoji from raw text.
'''
emoji_re = ':[a-zA-Z0-9-_]+:'
emoji_re = re.compile(emoji_re)
# Remove content matched by the given compiled re list
def clean_text(compiled_re_list, text):
new_text = text
for compiled_re in compiled_re_list:
new_text = compile... |
# -*- coding: utf-8 -*-
def evaluate_board(board):
if board[0] + board[1] + board[2] != 15: return False
if board[3] + board[4] + board[5] != 15: return False
if board[6] + board[7] + board[8] != 15: return False
if board[0] + board[3] + board[6] != 15: return False
if board[1] + board[4] + board[7] != 15: retu... |
"""
https://en.wikipedia.org/wiki/Square_root_of_a_matrix
B is the sqrt of a matrix A if B*B = A
"""
import numpy as np
from scipy.linalg import sqrtm
from scipy.stats import special_ortho_group
def denman_beaver(A, n=50):
Y = A
Z = np.eye(len(A))
for i in range(n):
Yn = 0.5*(Y + np.linalg.inv(... |
import numpy as np
from sympy import *
"""
The transfer function is defined as
Y(s)/U(s) = G(s)
The state space equations is defined as
x' = Ax + Bu
y = Cx + du
Take the laplace transform of the state space equation and get
sX(s) - x(0) = AX(s) + BU(s)
Y(s) = CX(s) + DU(s)
The Laplace Transform assumes t... |
#!/usr/bin/env python
"""
https://tomroelandts.com/articles/how-to-plot-the-frequency-response-of-a-filter
The general idea is to take the fourier transform of the impulse response (the filter coefficients)
If it is a real coefficients, then just keep the first half of the fourier transform coefficients since it wil... |
# # Taking input
# name = input("Write your name here: ")
# print(f"Hello, {name}!")
# # Multi-line prompt
# prompt = "If you tell us who you are, we can personalize the messages you see."
# prompt += "\nWhat is your first name? "
# name = input(prompt)
# print(f"Hello, {name}!")
# # Using int() for numerical input
... |
import sys
user_list = input("Enter numbers to sum separated by spaces: ")
user_list = [int(num) for num in user_list.split(" ")]
def add(*args):
total = 0
for num in args:
total += num
print(f"The sum of the numbers in your list is {total}")
if __name__ == "__main__":
... |
dato = input('Ingrese Datos: ');
#contruimos una lista, para hacer una busqueda
lista = ['hola','mundo','soy','solitario avalos']
if lista.count(dato) > 0 :
print('El dato existe', dato);
else:
print('El dato no existe :(');
#print(dato) |
from random import shuffle, randint
from time import sleep
from snap.pile import Pile
from snap.player import Player
print("Welcome to SNAP\n")
# Instatiate players
no_of_players = 2
player1 = Player("Alex")
player2 = Player("Uncle Ben")
# Ask user for number of decks to use
user_input = ""
while not user_input.isdi... |
from datetime import datetime
def print_time(task_name):
print(task_name)
print(datetime.now())
print()
# print timestamps to see how long sections of code
#take to run
first_name = 'Susan'
print_time('printed first name')
for x in range(0,10):
print(x)
print_time('completed for loop')
print()
# ==... |
from collections import deque
class Bandeja(object):
def __init__(self, numhojas=1):
self.__hojas = numhojas
def retirar_hoja(self):
self.__hojas -= 1
def add_hoja(self, n):
self.__hojas += n
def verificar(self):
#Verifica que hayan hojas
if self.__hojas <=... |
import os
from core import *
if os.name == 'nt':
clear = 'cls'
else: clear = 'clear'
os.system(clear)
print "Seleccione la dificultad: "
LEVEL = int(raw_input("1. Facil\n2. Medio\n3. Imposible\n"))
while True:
if LEVEL == 1 or LEVEL == 2 or LEVEL == 3:
break
else:
os.system(clear)
LEVEL = int(raw_input("Opcio... |
import random
import os
#Human = 1
#PC = 2
class Triqui:
def __init__(self,l):
self.movpc = random.randint(0,8)
self.ganador = 0
self.movhuman= 0
self.level = l
self.printinit()
print "\nLos movimientos se introducen indicando el numero de la casilla.\n"
self.tablero = [0,0,0,0,0,0,0,0,0]
def comp... |
## Desarrollado por: Jose Alejandro Cardona V.
## Metodos Numericos: Aproximacion por minimos cuadrados
import numpy as np
import matplotlib.pyplot as plt
class AproxLineal:
def __init__(self, usrInput):
## Se espera una entrada como la siguiente:
## (1,2), (1,-2), (-1,2), (-1,-2)
## cualqui... |
'''
rstrip() method returns a copy of the string with trailing characters removed
(based on the string argument passed). If no argument is passed,
it removes whitespace spaces.
'''
# Python3 program to demonstrate the use of
# rstrip() method using optional parameters
# string which is to be stripped
string =... |
class Person:
def __init__(self, fname, lname):
self.firstname = fname
self.lastname = lname
def printname(self):
print(self.firstname, self.lastname)
#Use the Person class to create an object, and then execute the printname method:
x = Person("John", "Doe")
x.printname()
#Create a C... |
'''
Exercise: Write the output of the following code:
for i in range(1, 5):
print(i, end='->')
for j in range(11, 20):
print(j, end=' ')
# end for j
print()
# end for i
'''
#output
'''
1->11 12 13 14 15 16 17 18 19
2->11 12 13 14 15 16 17 18 19
3->11 12 13 14 15 16 17 18 19
4->11 12 13 14 15 16 17 18 19... |
from collections import namedtuple
n=int(input())
rows=(input().split())
sum=0;
index=0;
for k in range(len(rows)):
if(rows[k]=="MARKS"):
index=k
for i in range(n):
lst=list(map(str,input().split()))
for j in range(len(lst)):
if(j==index):
sum=sum+int(lst[j])
print('%.2f' %(sum... |
import re
import math
def isPerfectSquare(x):
s = int(math.sqrt(x))
return s*s == x
# Returns true if n is a Fibinacci Number, else false
def isFibonacci(n):
# n is Fibinacci if one of 5*n*n + 4 or 5*n*n - 4 or both
# is a perferct square
return isPerfectSquare(5*n*n + 4) or isPerfect... |
product = [(i, j) for i in range(1, 4) for j in range(2, 10, 2)]
print(product)
#output
#[(1, 2), (1, 4), (1, 6), (1, 8), (2, 2), (2, 4), (2, 6), (2, 8), (3, 2), (3, 4), (3, 6), (3, 8)] |
lst = [35, 38, 39, 40, 45]
grade = ''
for i in lst:
if i > 39:
grade = 'pass'
else:
grade = 'fail'
print("The result for", i, 'is', grade)
# Program to demonstrate conditional operator
a, b = 10, 20
# Copy value of a in min if a < b else copy b
min = a if a < b else b
print(min)
numlist ... |
ls = [12, 24, 1, 2, 23, 3, 22, 4, 21, 20, 5, 19, 6, 7, 18, 17, 8, 9, 16]
#this is the list we want to divide two parts
ln=len(ls)
i, j= 0,ln-1
while i < j:
while (ls[i] % 2 == 1): # left hand side part. (ls[i]) part is constant and logic is only %2==1
# it means put things to left part... |
import random
def run():
numero=random.randint(1,100)
elegido=int(input('Elige un número del 1 al 100'))
while numero != elegido:
if elegido < numero:
print("busca un número más grande")
else:
print("busca un número más pequeño")
elegido = int(input('elige otro número'))
print('Gan... |
from is_palindrome import is_palindrome
def Make_substrings(strIn):
"""
makes list of all possible substrings in a given string
input: string
output: list
"""
substring_list = []
str_len = len(strIn)
#all possible lengths of a substing
for substring_size in range(str_len):
#... |
'''
This script uses urllib to search greyhoundstats.co.uk for a
dog, whose name is passed as a command line arguement. The response
is saved as a file, with name runner-DOGNAME.html.
The script results in the creation of one file and one page request.
'''
'''
import urllib
import urllib2
import sys
url... |
from tkinter import *
from calculadora import Calculadora
root = Tk()
# ----------------------------------------
# funcoes
resultado = StringVar()
calc = Calculadora()
def somar():
numero1 = int(txt_numero1.get())
numero2 = int(txt_numero2.get())
resultado.set(calc.soma(numero1, numero2))
def subtracao... |
"""
Exercise 10.2-2
One singly linked list implement the stack.
"""
from singly_linked_list import SinglyLinkedList, SinglyLinkedListNode
class Stack(object):
def __init__(self):
self.S = SinglyLinkedList()
def is_empty(self):
return self.S.is_empty()
def push(self, element):
s... |
def shell_sort(array):
n = len(array)
step = n // 2
while step > 0:
# insertion sort.
for j in range(step, n):
min = array[j]
i = j - step
while i >= 0 and array[i] > min:
array[i + step] = array[i]
i -= step
arr... |
# 快速排序的随机化版本,很多人都选择随机化版本的快速排序作为大数据输入情况下的排序算法。
import random
def randomized_quick_sort(A, p, r):
if p >= r:
return
q = randomized_partition(A, p, r)
randomized_quick_sort(A, p, q - 1)
randomized_quick_sort(A, q + 1, r)
def randomized_partition(A, p, r):
i = random.randint(p, r)
A[i], A[... |
# Match simple Web domain names that begin with "www."
# and end with a ".com" suffix; for example, www.yahoo.com.
# Extra Credit: If your regex also supports other high-level
# domain names, such as .edu, .net, etc. (for example,
# www.foothill.edu).
urls = """
http://www.yahoo.com
ftp://archives.yahoo.com
https:... |
# Match any word and single letter separated by a comma and single space, as in last name, first initial
import re
def get_complete_name(name):
return "First: %s - Last: %s" % (name[1], name[0])
names = """
Aamir, Aaron
Abbey Abbie
Abbot, Abbott
Abby Abdel
Abdul, Abdulkarim
Abdullah, Abe
Abel Abelard
Abner, Abr... |
# Recognize the following strings: “bat,” “bit,” “but,” “hat,” “hit,” or “hut.”
import re
words = """
bat fish bit book keyboard but nose eye building hat try ok address hit ten lol hut
"""
pattern = re.compile("[bhaiu]{2}t")
result = pattern.findall(words)
print " ".join(result)
|
def duplicate_encode(word):
word = word.lower()
result = ""
for indx,char in enumerate(word):
if char in word[:indx] or char in word[indx+1:]:
result += ")"
else:
result += "("
return result
if __name__ == '__main__':
assert duplicate_encode("din") == "(((... |
# File Name: Virtual Pet
# Purpose: Models the action of a virtual pet
# Date: 2020-02-20
# Last modified: 2020-02-20
# Author: Josen Pottackal
# Copy right no copyright
# Version: 1.0
import random
import tkinter
from PIL import Image, ImageTk, ImageSequence
avatarName = "zog"
happiness = 1
hunger = ... |
#!/usr/bin/python
a = 10
b = a % 2
if b == 0 : print ("Given number is", a, "even")
else: print ("Given number is", a, "odd")
|
#!/usr/bin/python
a, b = 20, 10
c = a + b
print ("\n Addition of two numbers is",c)
c = a-b
print ("\n Subtraction of two numbers is",c)
c = a * b
print ("\n Multiplication of two numbers is",c)
c = a / b
print ("\n Division of two numbers is", c)
|
import pygame
import sys, random, copy
# variables do control the game
lost = False
eat = False
timer = 0
width = 800
height = 600
BG = 60,60,60
FOOD_C = 200,0,0
BODY_C =255,255,255
sqr_size = 20
SPEED = sqr_size
# Classes
class Snake(object):
def __init__(self):
self.pos = [random.randint(1,(width-sqr_... |
# Date: 03/12/2020 (lol ironic)
# Topic: Regular Expressions
#
# ### Practice Project ###
# Write a regular expression that can detect dates in the DD/MM/YYYY format. Assume that the days range from 01 to 31, the months range
# from 01 to 12, and the years range from 1000 to 2999. Note that if the day or month is a si... |
# stopwatch.py - A simple stopwatch program.
import time
# Display the porgram's instructions
print(
""" \n\nInstructions\n
press Enter to begin.\n
Afterwards press Enter to "click" the stopwatch.\n
Press Ctrl-C to quit"""
)
input() # press Enter to begin
print("Started")
startTime = time.time()
lastTime = star... |
# -*- coding: utf-8 -*-
"""
Created on Thu Jul 15 16:58:41 2021
@author: wooihaw
"""
# Task 4
from collections import Counter
with open('alice.txt', 'r') as f:
s = f.read()
# print(s)
t = [c.lower() if c.isalpha() else ' ' for c in s]
w = ''.join(t)
allwords = w.split()
print(allwords)
wor... |
"""
Date: 01/05/2020 - 20:36
Overview: A tool to make a MODO binder comprised of cards from a selected deck
(your colection), and exclude cards from another selected deck (your deck).
This is built to combat the fact that trade bots don't care if you thata card
is in your deck, the bot only cares that its in y... |
#
# OSMAN FURKAN KINLI
# S002969 - Computer Science in Engineering
# Ozyegin University - CS466 Introduction to Deep Learning
# Assignment-1 - MNIST CNN Multinominal Logistic Regression
#
# To execute program:
# "python furkan_kinli_training <network_name> <dataset_name> <path>"
#
# For network n... |
# exercise 1: find and replace
words = "It's thanksgiving day. It's my birthday,too!"
print words.find("day")
words2 = words.replace("day", "week")
print words2
# exercise 2: min and max
def min_max(arr):
print min(arr)
print max(arr)
x = [2,54,-2,7,12,98]
min_max(x)
# exercise 3: first and last
x = ["hello"... |
def insert_val_at(index, my_list, value):
if len(my_list) <= index:
return False
my_list.append(0)
for i in range(len(my_list)-1, index, -1):
my_list[i] = my_list[i-1]
my_list[index] = value
return my_list |
def change(cents):
coins = {'dollars': 0, 'quarters': 0, 'dimes': 0, 'nickels': 0, 'pennies': 0}
while cents > 0:
if cents % 100 == 0:
coins['dollars'] += 1
cents -= 100
elif cents % 25 == 0:
coins['quarters'] += 1
cents -= 25
elif cents % ... |
class Car(object):
def __init__(self, price, speed, fuel, milage):
self.price = price
self.speed = speed
self.fuel = fuel
self.milage = milage
if price > 10000:
self.tax = 0.15
else:
self.tax = 0.12
def display_all(self):
print... |
def type_list(arr):
#print type(arr[0])
printType = type(arr[0]).__name__
sameType = True
string = ""
sum = "No sum yet!"
for i in range(0, len(arr)):
if printType != type(arr[i]).__name__:
printType = "mixed"
if type(arr[i]) is str:
string += " " + arr[i]... |
#프로그래머스 시저 암호 https://programmers.co.kr/learn/courses/30/lessons/12926
#n자리 수만큼 알파벳을 이동하여 출력하는 암호.
def solution(s, n):
result = ''
for char in s:
if char ==' ':
result+=char
elif ord(char)>= 97: #소문자
if ord(char)+n >122: #z를 넘어 a로 넘어가야할 경우..
m = (... |
# coding:utf-8
import csv
import time
#https://blog.csdn.net/yzf0011/article/details/72903088
#处理编码问题
start = time.time()
with open('./data/dnacsv.csv','r',encoding="utf-8") as csvfile:
#print('true')
reader = csv.reader(csvfile)
i = 1
l = []
for row in reader:
print("=" * 100)
prin... |
# -*- coding: utf-8 -*-
"""
Created on Fri Mar 29 22:38:33 2019
Find the index in an array which is closest to a number
@author: ChiJuWu
"""
import numpy
def closest(number, array, lower=False, upper=False):
if lower:
idx = numpy.where(array == array[array <= number].max())[0]
elif upp... |
#!/usr/bin/env py
def countWays(top, bottom):
assert(top >= bottom)
assert(top >= 0)
assert(bottom >= 0)
assert(top == bottom or top == bottom + 1)
answer = -1
if top == bottom == 0:
answer = 1
elif top == bottom:
if top == 1:
answer = 2
else:
answer = 2 * countWays(top - 1, bott... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
t.py
~~~~~~~~~~~~~~
A brief description goes here.
"""
def main(argv):
n = int(raw_input())
indexes = []
for i in range(n):
index = int(raw_input())
indexes.append(index)
tree = [1]
max_cycle = max(indexes)
for i in ran... |
class Solution(object):
"""Google interview"""
def isMatch(self, s, p):
"""
:type s: str
:type p: str
:rtype: bool
"""
if s == p:
return True
if not p:
return not s
if not s:
return len(p) >= 2 and p[1] == "*" an... |
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
def debug(h):
res = []
while h:
res.append(h.val)
h = h.next
s = "->".join([str(x) for x in res])
print s
return s
def generate(l):
h = ListNode(0)
... |
'''
# https://www.hackerearth.com/practice/basic-programming/input-output/basics-of-input-output/practice-problems/algorithm/split-house-547be0e9/
name = input() # Reading input from STDIN
print('Hi, %s.' % name) # Writing output to STDOUT
# Warning: Printing unwanted or ill-formatted data t... |
## Usage: python day10.py input.test
import sys
import re
FILE = sys.argv[1]
MAXITER = (int)(sys.argv[2])
MAXZONE = (int)(sys.argv[3])
point = []
with open(FILE) as f:
for line in f:
m = re.search('position=<(.+?),(.+?)> velocity=<(.+?),(.+?)>', line[:-1])
if m:
x ... |
# Time Complexity : O(lg n) - first, last, searchRange
# Space Complexity : O(1)
# Did this code successfully run on Leetcode : Yes
# Any problem you faced while coding this : Tried tocombine two searches in one BS. (Attempted before class)
#
# Your code here along with comments explaining your approach
# 1. Run two bi... |
#!/usr/bin/env python
def insertion_sort(array):
# Start from left and work our way right
for i in range(1, len(array)):
# check to see if the one to the left is greater than current
# if so, we'll begin the sort process
if array[i] < array[i-1]:
#store current value
... |
# 1986. 지그재그 숫자
t = int(input())
# print("t:", t)
for i in range(1, t + 1):
# num 까지 반복
num = int(input())
# print("num : ", num)
# 더하거나, 뺄 값
howNum = 0
# 결과 낼 값
answer = 0
for j in range(1, num + 1):
# 짝수인 경우
if j % 2 == 0:
howNum = -j
# pri... |
# 1948. 날짜 계산기
def last_Date (month) :
if month == 1 or month == 3 or month == 5 or month == 7 or month == 8 or month == 10 or month == 12 :
return 31
elif month == 2 :
return 28
else :
return 30
def sec_first_minus (first_Mon, fist_date, second_Mon, second_date) :
if first_M... |
# 2029. 몫과 나머지 출력하기
a = input()
a = int(a)
for i in range(1, a + 1):
i1, i2 = input().split()
i1 = int(i1)
i2 = int(i2)
print("#" + str(i), i1 // i2, i1 % i2)
|
# This is capter 3
bicycles = ["trek","cannondale",'redline','specialize']
print(bicycles)
print(bicycles[1])
print(bicycles[0].upper())
print(bicycles[-1])
print(bicycles[-2].title())
message = f"My first bicycles is {bicycles[-3].lower()}"
print(message)
friends =['Tuhin','Shahed','Tohid','Munna']
print(friends... |
#!/bin/python3
import math
import os
import random
import re
import sys
# Complete the jumpingOnClouds function below.
def jumpingOnClouds(c,n):
f=0
i=0
while(i<n):
if(i==n-1):
break
else:
if(i+2<n):
if(c[i+2]==0):
... |
__author__ = 'Brown'
class Solution(object):
def totalValue(self,nums):
odd=even=0
for i in range(len(nums)):
if i%2==0:
even=max(odd,even+nums[i])
else: odd=max(even,odd+nums[i])
return max(odd,even)
def rob(self, nums):
"""
:type ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.