text stringlengths 37 1.41M |
|---|
# multiply two values and print the result
def multiply(a,b):
c=a*b
print(c)
def add(a,b):
c=a+b
print(c)
def sub(a,b):
c=a-b
print(c)
def div(a,b):
c=a/b
print(c)
def rem(a,b):
c=a%b
print(c)
def exp(a,b):
c=a**b
print(c)
def multab(d):
for b in range(1,11):
... |
# Link: https://leetcode.com/problems/first-bad-version/
# The isBadVersion API is already defined for you.
# def isBadVersion(version: int) -> bool:
class Solution:
def firstBadVersion(self, n: int) -> int:
""""
Apply binary search to the array from 1 to n.
Initialization: left = 1, right... |
# https://www.interviewcake.com/article/python3/logarithms?course=fc1§ion=algorithmic-thinking
from typing import List
def merge_sort(list_to_sort: List[int]) -> List[int]:
# Base case: lists with fewer than 2 elements are sorted
if len(list_to_sort) < 2:
return list_to_sort
# Step 1: divide ... |
# Given the rootnode of a tree, print all the nodes from the tree using
# breadth-first traversal
from collections import deque
from typing import Optional
class BinaryTree:
def __init__(self, val=0):
self.val = val
self.left = None
self.right = None
def breadthFirstTraversal(node: Optio... |
# https://leetcode.com/problems/3sum/
from typing import List
class Solution:
def threeSum(self, nums: List[int]) -> List[List[int]]:
"""
+ Save all the numbers into a dictionary where a key is the the number and the respective
value is a set of indices from the nums list whose nums[index]... |
# https://leetcode.com/problems/flood-fill
from typing import List
class Solution:
def recursiveFloodFill(self, image: List[List[int]], sr: int, sc: int, new_color: int, old_color: int) -> List[List[int]]:
# Fill the pixel with the new color
image[sr][sc] = new_color
# top
if sr -... |
from typing import List
class Solution:
def spiralOrder(self, matrix: List[List[int]]) -> List[int]:
"""
Have two variables called m and n as the running coordinator to travel throw the matrix, where m represents the current row, and n represents the current column we're at.
we have a vari... |
# https://leetcode.com/problems/majority-element/
from typing import List
class Solution:
def majorityElement(self, nums: List[int]) -> int:
"""
Have a dictionary to check the frequencies of elements appear in the array.
1. Iterate through the nums list & save the frequencies of each eleme... |
# https://leetcode.com/problems/binary-tree-level-order-traversal
from typing import Optional, List
from collections import deque
# Definition for a binary tree node.
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
cl... |
class Solution:
# mark the duplicate elements in a sorted array and return the duplicates count
def markDuplicates(self, nums: List[int]) -> int:
dupCount = 0
for i in range(len(nums)):
if nums[i] == nums[i +1]:
# Mark the element as duplicate by assigning an out-of-r... |
# https://leetcode.com/problems/most-common-word/
from typing import List
def split_words(paragraph):
word = ""
words = []
for char in paragraph:
if (char == " " or char in "!?',;."):
if word != "":
words.append(word)
word = ""
else:
... |
########################################
# ex5
# FILE: crossword3d.py
# WRITERS: Nir Krieger, nirkr & Oded Fogel, fogrid
# DESCRIPTION: a script that searches a 3d matrix of letters for words given
# by the user, in the directions given by the user. outputs the
# words found and the number of t... |
# Description ------------------------------------------------------------------
# Advent of code day 2 -- find the valid passwords based on different policies
# Attempted in R first and then converted into python. For this one I used a better
# solution that I found online in R to convert to python.
# set up -----... |
# 1
# 2
class SLLNode:
def __init__(self, data):
self.data = data
self.next = None
# this method returns a readable anyobjest we have. It returns as string format our self.data
def __repr__(self):
return "SLLNode object: data={}".format(self.data)
def data(self):
"""Re... |
def main():
txt = input('Text: ')
numLetters = cont_letters(txt)
numWords = cont_words(txt)
numSentences = cont_sentences(txt)
indexGrade = index(numLetters, numWords, numSentences)
if(indexGrade < 1):
print('Before Grade 1')
elif(indexGrade > 16):
print('Grade 16+')
els... |
#!/usr/bin/python3
# -*- coding: utf-8 -*-
import unicodedata
import sys
def strip_accents(text):
try:
text = unicode(text, 'utf-8')
except NameError: # unicode is a default on python 3
pass
text = unicodedata.normalize('NFD', text)\
.encode('ascii', 'ignore')\
.dec... |
def gcd(a,b):
if a==0:
return b
return gcd(b%a,a)
def lcm(a,b):
return (a*b)/gcd(a,b)
a,b=map(int,input().split())
print(gcd(a,b))1 8 |
#range
for i in range(1,10):
print(i)
print("/////////////")
#for loop
a=[1,2,3,4,8,6,4,3]
for i in a:
print(i)
print("/////////////")
#for usingrange(start, stop, step)
for i in range(0,15,3):
print(i)
print("/////////////")
# step argument to iterate backwards
for i in range(100,0,-10):
print(i... |
import math
def calculateMex(Set):
Mex = 0
while (Mex in Set):
Mex += 1
return (Mex)
for _ in range(int(input())):
n=int(input())
a=list(map(int,input().split()))
a.sort()
Set=set()
Set2=set()
for num in a:
if num in Set:
Set2.add(num)
Set... |
def calculateMex(Set):
Mex = 0
while (Mex in Set):
Mex += 1
return (Mex)
# A function to Compute Grundy Number of 'n'
# Only this function varies according to the game
def calculateGrundy( n, dp):
if (n == 0):
return (0)
if dp[n]!=-1:
return dp[n]
... |
def maxcoinchange(coin,N):
size=len(coin)
t=[[0 for j in range(N+1)]for i in range(size+1)]
for i in range(size + 1):
t[i][0] = 1
for i in range (1,size+1):
for j in range(1,N+1):
if j>=coin[i-1]:
t[i][j] = t[i-1][j] + t[i][j-coin[i-1]]
else:
... |
n = int (input ("Nhập n: "))
giaithua = 1
for i in range (1, n + 1):
giaithua = giaithua * i
print ('Kết quả: ',giaithua)
|
print('Введите a для символа Якоби (a/m) - произвольное целое:')
a = int(input())
print('Введите m символа Якоби (a/m) - нечетное натуральное):')
m = int(input())
s = 0
#Код программы:
flag = 0 #Сигнал о том, что ответ не найден (обнуляем).
if (a == 0): #Если a символа Якоби (a/m) равен 0,
answ = 0 #т... |
"""
Problem 4.
Largest palindrome product
https://projecteuler.net/problem=4
"""
def is_palindrome(n):
"""Determine whether n is palindrome."""
# Convert the given number into list.
number_original = list(map(int, str(n)))
# First, store a copy of the list of original number.
number_reversed = n... |
#################################
# Quick Sort #
#################################
list1 = [2, 5, 1, 8, 4, 6, 9, 3, 7]
def partition(A, p, r):
pivot = A[r]
i= p-1
for j in range(p,r):
if A[j]<= pivot:
i += 1
A[j], A[i] = A[i], A[j]
A[i+1], A[r] =... |
sys = int(input())
stud = int(input())
while True:
if (sys!=1 and stud!=1) or (sys==1 and stud==1):
print('YES')
else:
print('NO') |
# [1,2,3,4,1,4]
# 1 2
# 2 1
# 3 1
# 4 1
arr=[1,2,3,4,1,4]
result={}
for each in arr:
result.update({each:arr.count(each)})
for (a,b) in result.items():
print(a,b)
|
import util
import time
startTime = time.time()
a = 1
b = 0
n = 1
while len(str(a)) != 1000:
a, b = a+b, a
n = n + 1
print(str(a) + " has 1000 digits, n = ", str(n))
print("Run Time = " + str(time.time() - startTime)) |
import util
import time
startTime = time.time()
def findRepeatLength(d):
remainders = []
work = 1 % d
while True:
if work == 0 or work in remainders:
return len(remainders)
remainders.append(work)
work = (work * 10) % d
longestRepeat = 0
dValue = 0
for d in range(7, 1001):
repeat = findRepea... |
import random # because life is random no mather what...
from pynput import keyboard
import os, time
import sys, termios
import player
humans = int(input('Specify number of human players [1]: ') or 1) # default is one (you)
temp_robots = 0 if humans > 1 else 1
robots = int(input('Specify number of robot players [' + s... |
text = input()
print("The given string:",text)
print("The USA/usa count is:",text.count("USA") + text.count("usa"))
print(text.lower().replace("usa","Armenia")) |
import datetime
import time
import calendar
bday = datetime.date(1996,8,15)
print(bday)
print(bday.year)
print(bday.month)
print(bday.day)
print(bday.weekday())
print(datetime.date(2020,8,15) - datetime.date.today())
print(calendar.month(2017,5))
tdelta = datetime.timedelta(days = 1)
print(datetime.datetime.today() - t... |
#1. WAP to create a dictionary of numbers mapped to their negative value for numbers from 1-5.
#The dictionary should contain something like this:
#Do with both with and without range based for loop.
f = {}
for i in range(1,6):
f[i] = -i
print(f)
#2. Check which of the following declarations will work
#1
d ={1=2,3=4... |
#Custom for loop
#for num in [1,2,3] #inside the for loop: iter([1,2,3]) -> returns iterator, then for loop keeps calling next(iter([1,2,3])) until catches error
def my_for(iterable, func):
iterator = iter(iterable)
while True:
try:
item = next(iterator)
except StopIteration:
... |
from robot import Robot
import unittest
class RobotTests(unittest.TestCase):
#instead of the writing mega_man = Robot("Megaman", battery = 50) for every test, we can write setUp
def setUp(self):
self.mega_man = Robot("Megaman", battery = 50)
def test_charge(self):
#mega_man = Robot("Megama... |
def fib_list(max):
final = []
a = 0
b = 1
while len(final) < max:
final.append(b)
a, b = b, a+b
return final
def fib_gen(max):
a, b = 0, 1
count = 0
while count < max:
yield a
a, b = b, a+b
count+=1
print(fib_list(10))
fib = fib_gen(10)
print(... |
class Human:
def __init__(self, first, last, age):
self.first = first
self.last = last
if age >= 0:
self._age = age #private for the class
else:
self._age = 0
"""
def get_age(self):
return self._age
def set_age(self, new_age):
... |
# Given a person variable:
# person = [["name", "Jared"], ["job", "Musician"], ["city", "Bern"]]
# Create a dictionary called answer , that makes each first item in each list a key and the second item
# a corresponding value. That's a terrible explanation. I think it'll be easier if you just look at the end goal:
#... |
#generator - a special type of iterator. All generators are iterators, but not all iterators are generators.
# reg func vs generator functions
"""
uses return vs uses yield
returns once vs can yield multiple times
returns value vs returns a generator
"""
def count_to_max(max):
c... |
# Simplest possible class
class User: #capitalized camelcase - convention
def __init__(self, first, last, age):
self.first = first
self.last = last
self.age = age
user1 = User("Perry", "Smith", 68)
user2 = User("Joe", "Lopez", 41)
print(user1.first, user1.last)
print(user2.first, user2.l... |
################################
'''
return_day(1) # "Sunday"
return_day(2) # "Monday"
return_day(3) # "Tuesday"
return_day(4) # "Wednesday"
return_day(5) # "Thursday"
return_day(6) # "Friday"
return_day(7) # "Saturday"
return_day(41) # None
'''
def return_day(day_number):
days = {
1 : "Sunday",
2 ... |
import requests
from bs4 import BeautifulSoup
import random
from pyfiglet import figlet_format
# the function that will take the url it is given and parse it accordingly.
def quote_parser(url):
# getting the response from the url
response = requests.get(url)
# creating a variable to store the markup of t... |
# Given the provided dictionary of donations: donations = dict(sam=25.0, lena=88.99, chuck=13.0,
# linus=99.5, stan=150.0, lisa=50.25, harrison=10.0) Use a loop to calculate the total value of the donations. Save the result to a variable
# total_donations
donations = dict(sam=25.0, lena=88.99, chuck=13.0, linus=99.5,... |
import re
# define the phone number regex
# r is used as raw string, so that we don't have to escape characters
pattern = re.compile(r'\d{3} \d{3}-\d{4}')
# search a string with our regex - returns a match object
res = pattern.search('Call me at 813 895-6015!')
res.group() # extracts the match for us - but only the ... |
def square(num): return num*num
#syntax - lambda parameter: code in one line without return - you usually don't store that in variable
square2 = lambda num: num * num
add = lambda num: num + num
print(square2(3))
print(square2.__name__)
#use case - passing in a function as a parameter into another function. short ... |
# since 2010 it is possible define the type of parameter
def climbstair(n:int):
if(n==2):
return 2
if(n==1):
return 1
return climbstair(n-1) + climbstair(n-2)
n=int(input("Stair count:"))
print("Total:" + str(climbstair(n))) |
import math
import random
import timeit
from motion_plan_state import Motion_plan_state
import matplotlib.pyplot as plt
import numpy as np
class Node:
# a node in the graph
def __init__(self, parent=None, position=None):
self.parent = parent
self.position = position
self.g = 0
... |
import numpy as np
arr = np.arange(50).reshape((10,5))
#print(arr)
#print(arr.T)
dot_arr = np.dot(arr.T,arr)
#print(dot_arr)
arr3d = np.arange(50).reshape((5,5,2))
#print(arr3d)
#print('............')
#print(arr3d.transpose((1,2,0)))
#change the order of the numbers to change the way it is transposed
arr1 = np.array... |
from random import randint
from tkinter import *
display = Tk()
display.title("Kandji")
display.minsize(400, 600)
display.maxsize(400, 600)
display.iconbitmap("klogo.ico")
display.config(background='#4C93E5')
titre = Frame(display, bd=5, relief=RAISED, width=100, height=20,)
titre.pack()
text1 = Label(titre,... |
from math import ceil, floor
from typing import List, Union
from .alignment import Alignment
from .options import Options
class TableToAscii:
"""Class used to convert a 2D Python table to ASCII text"""
def __init__(self, header: List, body: List[List], footer: List, options: Options):
"""Validate ar... |
# The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like this:
# (you may want to display this pattern in a fixed font for better legibility)
# P A H N
# A P L S I I G
# Y I R
# And then read line by line: "PAHNAPLSIIGYIR"
# Write the code that will take a string and m... |
'''
Das lives in a city which is having skyscrapers. Das has a wish and wants to see the buildings on which sunlight falls when the sun sets.
Help him in counting the number of buildings receiving the sunlight. Note: A taller building casts a shadow on a shorter building.
Given an array H denoting heights of buildin... |
def main ():
print("=============================================")
print("Selamat Datang Di Parkiran Nation")
print("=============================================")
type_v = input("Masukkan Tipe Data Kendaraan Anda \n1."\
" Untuk Mobil <Mobil>\n2. Untuk Motor <Motor>\nSilahkan Masukkan Tipe Ke... |
# 定义函数
def my_abs(x):
if x >=10:
return '大于10'
else:
return '小于10'
# print(my_abs(12))
def test(x):
a = 2
print(test(2))
def nop():
pass
|
def begin():
print("1 - change mod percent (default 3% down, 5% up)\n2 - change values\n3 - Start")
start = int(input("-->"))
upPerc = .05
downPerc = .03
if start == 1:
print("set percent to increase when bought (default 5%)\n*ENTER AS DEC 5% == .05*\n")
upPerc = input("-->")
... |
# printing duplicate letter from string
ifPresent = False
a = 'suveds'
a1 = []
for i in range(len(a)-1):
for j in range(i+1,len(a)):
if a[i]==a[j]:
if a[i] in a1:
break
else:
a1.append(a[i])
ifPresent = True
if (ifPresent):
... |
#Given three numbers b, e and m. Fill in a function that takes these three positive integer values and outputs b^e mod m.
a = int(input())
b = int(input())
c = int(input())
d = (a**b)%c
print(d) |
""" Some convenience routines for parsing interval inputs
"""
from __future__ import division
from __future__ import print_function
import datetime
from matplotlib.dates import date2num,num2date
import pytz
units_to_days = {'d':1.0,
'h':1.0/24.0,
'm':1.0/(60.0*24.0),
... |
#Inporting all the required libraries
import pandas as pd
import matplotlib.pyplot as plt
print("Task Submitted by :Shruti Goel\n")
print("The Sparks Foundation - Data Science & Business Analytics Internship\n")
print("Task 1 - Prediction using Supervised Machine Learning")
# Reading data from remote link
... |
def shift_list_values_left(list):
for i in range(1, len(list)):
list[i - 1] = list[i]
if i == len(list) - 1:
list[i] = 0
print list
shift_list_values_left([1,2,3,4,5]) |
def print_ints_and_sum():
sum = 0
for i in range(0, 255 + 1):
print 'i is currently ' + str(i)
sum = sum + i
print 'Current sum is ' + str(sum)
print_ints_and_sum() |
import time
import itertools
from crypt import crypt
def brute_force_cracker(shadowfull):
start = time.time()
chars = "1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ`~!@#$%^&*()_-+=[{]}|:;'\",<.>/?"
attempts = 0
for i in range(1, 9):
for letter in itertools.product(chars, repea... |
#!/usr/local/bin/python3
#https://github.com/behruzpino/BCH5884-Behrouz.git
import math
x=float(input("please enter the temparature in Fahrenheit and I will tell you that in Kelvin: "))
print (x)
y=(((x-32)*5)/9)+273.15
print (y)
print("right?!")
|
'''
https://leetcode.com/problems/palindrome-number/
숫자가 주어졌을 때
거꾸로 뒤집어도 순서가 같을 때
'''
# 배운 점
'''
xs[3:0:-1] # 0번 인덱스부터 3번 인덱스까지 역순 출력
xs[0:3] # 0번 인덱스부터 3번 인덱스까지 출력
'''
class Solution:
def isPalindrome(self, x: int) -> bool:
xs = str(x)
# NOTE: 가운데부터 뒤집는게 더 성능 up! 할 수 있음
if xs == xs[::-1]:
... |
def f(A):
A.sort()
return A[len(A)-3]
t = int(input())
for _ in range(t):
A = list(map(int, input().split(' ')))
print(f(A)) |
#!/usr/bin/python
import psycopg2
from config import config
"""
execute the DELETE statement. If you want to pass values to the DELETE statement, you use the placeholders ( %s) in the DELETE statement and pass input values to the second parameter of the execute() method.
The DELETE statement with a placeholder for th... |
from Value.Value import Value
from Exception.DivisionByZero import DivisionByZero
class DigitValue(Value):
"""
Численное значение
"""
def __init__(self, p_data):
"""
Конструктор
:param p_data: Данные
"""
Value.__init__(self, p_data)
def to_double(self):
... |
from Variable.Variable import Variable
class VariableList(object):
"""
Массив переменных
"""
def __init__(self):
"""
Конструктор
"""
self.items = []
def __getitem__(self, p_name):
"""
Индексатор
:param p_name: Имя переменной
:return... |
# -*- coding: utf-8 -*-
"""
CSC 221
Bob's fishing trip
Jesse Watts
Goal: Gold
30 Jan 19
"""
"""Write a program that asks Bob how many fish he caught over a 3 day period
and calculates the average number of fish caught per day."""
"Use a for and range statement to get Bob's number of fish."
for i in ra... |
# An interface for creating an object.
from pypattyrn.creational.factory import Factory # This is just an interface
class Cat(object):
def speak(self):
print('meow')
class Dog(object):
def speak(self):
print('woof')
class AnimalFactory(Factory):
def create(self, animal_type):
if animal_type == 'cat... |
#
# board.py (Final project)
#
# A Board class for the Eight Puzzle
#
class Board:
""" A class for objects that represent an Eight Puzzle board.
"""
def __init__(self, digitstr):
""" a constructor for a Board object whose configuration
is specified by the input digitstr
... |
# import packages to be used for this program
from random import randint
from statistics import mean
import time
# Selection sort algorithm, adapted from https://www.pythoncentral.io/selection-sort-implementation-guide/
def selectionSort(arr):
for i in range(len(arr)):
# Find the element with lowest value... |
def maxpProfit(prices, fee):
if len(prices) == 0 or prices is None:
return 0
profit = 0
for i in range(len(prices)-1):
if (prices[i+1] - prices[i] - fee) > 0:
profit += prices[i+1] - prices[i] - fee
return profit
print(maxpProfit(prices = [1, 3, 2, 8, 4, 9], fee = 2)) |
def reverseString(s):
if len(s) % 2 == 0:
begin = 0
end = len(s)-1
for i in range(int(len(s)/2)):
temp = s[begin]
s[begin] = s[end]
s[end] = temp
begin += 1
end -= 1
else:
begin = 0
end = len(s) -1
for i ... |
def longestCommonPrefix(strs):
if len(strs) == 0:
return ''
if len(strs) == 1:
return strs[0]
longest_common_prefix = ''
first_word = strs[0]
for i in range(len(first_word)):
if isThere(strs, i+1):
longest_common_prefix = first_word[0:i+1]
return longest_commo... |
def search(nums, target):
left = 0
right = len(nums)-1
while left <= right:
med = (left + right) // 2
if nums[med] == target:
return med
elif nums[med] > target:
right = med - 1
elif nums[med] < target:
left = med + 1
return - 1
print... |
def firstBadVersion(n):
start = 1
end = n
while start <= end:
med = (start+end)//2
temp = isBadVersion(med)
if start == end and temp:
return med
elif temp is False:
start = med + 1
elif temp:
end = med-1
print(firstBadVersion()) |
def numRescueBoats(people, limit):
people.sort()
l, h = 0, len(people) -1
total_boats = 0
while l <= h:
total_boats += 1
if people[l] + people[h] <= limit:
l += 1
h -= 1
return total_boats
print(numRescueBoats([5,1,4,2], 6))
|
def majorityElement(nums):
was_checked = []
for num in nums:
if num in was_checked:
continue
else:
if nums.count(num) > len(nums)//2:
return num
was_checked.append(num)
print(majorityElement([2,2,1,1,1,2,2])) |
def singleNumber(nums):
while True:
num = nums[0]
nums.remove(nums[0])
if num not in nums:
return num
else:
nums.remove(num)
print(singleNumber([2,2,1])) |
def findMedianSortedArrays(nums1, nums2):
merged = nums1 + nums2
merged.sort()
if len(merged)%2==0:
return (merged[len(merged)//2] + merged[(len(merged)//2)-1]) / 2
else:
return merged[len(merged)//2]
print(findMedianSortedArrays(nums1 = [1, 3], nums2 = [2])) |
def frequencySort(s):
d = dict()
for i in s:
d[i] = d.get(i, 0) + 1
sorted_list = sorted(d.items(), key=lambda x:x[1], reverse=True)
ans = ''
for i in sorted_list:
ans = ans + i[0] * i[1]
return ans
print(frequencySort('Aabb')) |
def merge(nums1, m, nums2, n):
nums1[m::] = nums2[0:n]
temp = 0
for i in range(len(nums1)-1):
for j in range(i+1, len(nums1)):
if nums1[i] > nums1[j]:
temp = nums1[i]
nums1[i] = nums1[j]
nums1[j] = temp
return nums1
print(merge([1,2... |
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def addTwoNumbers(self, l1: ListNode, l2: ListNode):
if l1 is None and l2 is None:
return None
elif l1 is None:
return l2
elif l2 is None:
return l1
... |
def wordSubsets(A, B):
result = []
b_word_dict = {}
for b_word in B:
for letter in b_word:
count = b_word.count(letter)
if b_word_dict.get(letter,0) < count:
b_word_dict[letter] = count
for a_word in A:
flag = True
for key, value in b_word_... |
def maxSubarray(nums):
global_max = nums[0]
current_max = nums[0]
for i in range(1, len(nums)):
current_max = max((nums[i], current_max+nums[i]))
global_max = max(global_max, current_max)
return global_max
print(maxSubarray([-2,1,-3,4,-1,2,1,-5,4],))
|
def findTheDifference(s, t):
s_dict = dict()
t_dict = dict()
for letter in s:
s_dict[letter] = s_dict.get(letter, 0) + 1
for letter in t:
t_dict[letter] = t_dict.get(letter, 0) + 1
for key,value in t_dict.items():
if value > s_dict.get(key, 0):
return key
print(... |
def arrangeCoins(n):
if n == 0:
return 1
len_stairs = 1
count = 0
while n >= len_stairs:
count += 1
n -= len_stairs
len_stairs += 1
return count
print(arrangeCoins(1)) |
def nextGreatestLetter(letters, target):
int_letters = []
for letter in letters:
if ord(letter) > ord(target):
int_letters.append(ord(letter))
else:
int_letters.append(1000)
return letters[int_letters.index(min(int_letters))]
print(nextGreatestLetter(["c", "f", "j"]... |
def add(a):
return lambda b: a + b
def sub(a):
return lambda b: a - b
def fib(n):
return n if n < 2 else add(fib(sub(n)(2)))(fib(sub(n)(1)))
print(fib(35)) |
#
# Generación de grafico.
# www: https://youtu.be/i8ruymr85Gg
#
# -- IMPORTAR MÓDULOS. --
import math
import numpy as np
from matplotlib import pyplot as plt
# -- GENERAR LOS DATOS PARA EL GRÁFICO. --
x = np.array(range(20))*0.2
y = np.zeros(len(x))
for i in range(len(x)):
y[i] = math.sin(x[i])... |
# -*- coding: utf-8 -*-
"""
ROBOT LOCALIZATION ASSIGNMENT
"""
import numpy as np
class HMM():
"""
This class represents a Hidden Markov Model (HMM), consisting of
eight random variables, with the following structure:
(X1)---(X2)---(X3)---(X4)
| | ... |
class Rect(object):
def __init__(self, x, y, w, h):
self.x1 = x
self.y1 = y
self.x2 = x + w
self.y2 = y + h
def center(self):
return (self.x1 + self.x2) / 2, (self.y1 + self.y2) / 2
def intersects(self, other):
return (
self.x1 <= other.x2 and
... |
# -*- coding: utf-8 -*-
#############################################
# raw_input() 내장 함수를 통해 사용자에게 Standard Input을 받을 수 있습니다.
result = raw_input("무엇이든 입력해보세요.")
print "당신이 입력한 내용은 {0}입니다.".format(result)
#############################################
# raw_input()을 이용해 사용자 인터랙티브한 프로그램(숫자 맞추기 게임)을 만들어봅시다.
# 차후에 배우겠지... |
"""
Nested dictionaries
"""
cars = {'bmw':{'model':'550i', 'year':2016}, 'benz':{'model':'E350', 'year':2015}}
bmw_year = cars['bmw']['year']
print(bmw_year)
print(cars['benz']['model']) |
"""
Creating your own modules
"""
# Import the module... it is inefficient to import the whole module if not needed
import math
# Importing only what you need
from math import sqrt
## Importing my own module
# import module_external.car as car
## Better way of importing whole module
# from module_external import car
... |
"""
Working with more methods
Adding documentation
"""
def sum_nums(n1, n2):
"""
Get the sum of 2 numbers
:param n1: first number
:param n2: second number
:return: sum of n1 and n2
"""
return n1 + n2
sum1 = sum_nums(1, 2)
print(sum1)
print(sum_nums(5, 7))
string_add = sum_nums("one", "two... |
"""
Object-Oriented Programming
"""
class Car(object):
# This is required for classes, initializes all objects from this class, basically a constructor
def __init__(self, make, model='550i'):
self.make = make
self.model = model
# Create instance of class
c1 = Car('BMW')
c2 = Car('Mazda')
prin... |
"""
Handling exceptions with finally and else
"""
def exceptionHandling():
try:
a = 10
b = 20
c = 0
# c = 10
d = (a + b) / c
print(d)
except:
print("Exception found!")
# raise is used to tell caller that an exception was thrown
raise Exce... |
con=1
numero_positivo=0
while con<=6:
numero=float(input())
if numero>0:
numero_positivo=numero_positivo+1
con=con+1
print("%d valores positivos" %(numero_positivo)) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.