text stringlengths 37 1.41M |
|---|
from PIL import Image
fg = Image.open('logo-1.png') # IMAGE NAME TO BE ANALIZED, PLEASE STORE IT IN THE SAME FOLDER THAN THE SCRIPT
dimensions = fg.size # TUPLE WITH (width, height) OF THE IMAGE
newIm = Image.new("RGB", dimensions,"white") # NEW IMAGE ALL WHITE WITH RGB PROPERTIES AND DIMENSIONS OF THE ANALYZED IMAG... |
# CSCI 1913, Spring 2020, Lab 3
# Student Names:
# Omar Masri!
# Brandon Weinstein!
# MASRI013@umn.edu
# WEINS127@umn.edu
#gets rid of punctuation
def clean_word(text):
contin = True
while contin:
for i in range(len(text)):
if text[i] in ["!", ",", "?", "."]:
... |
# list of items
items_list = [
{
'item_code': '84500',
'item_description': 'CHOCOLATE SHORTCAKE',
'customer_name': 'FROSTY TREATS',
'gross_weight': 15.95,
'units':10
},
{
'item_code':'84400',
'item_description':'STRAWBERRY SHORTCAKE',
'cu... |
# define list of valid facility IDs
facility_ids = ["78401", "MO-SKSTN"]
# get user input of facility ID
facility_input = input("Enter a facility ID: ")
# set up criteria for while loop
num_entries = 0
max_entries = 4
if facility_input in facility_ids:
# if facility is valid --> print welcome to facility messag... |
user_input_name = input("Enter a name: ")
user_input_place = input("Enter a place: ")
if user_input_name == "":
message = "No name entered - cannot print welcome :("
else:
# welcome message with multiple values passed to string interpolation
message = "Hello, %s! Welcome to %s!" % (user_input_name, user_in... |
import pandas as pd
import numpy as np
# read in sample data files from csv
df_items = pd.read_csv("items_sample.csv")
df_inventory_activity = pd.read_csv("inventory_activity_sample.csv")
# create a user defined function which rounds the pallet picks of each activity record
def get_num_pallets(activity):
# set t... |
import pandas as pd
# read in the sample items csv as dataframe
items_df = pd.read_csv("items_sample.csv")
# user defined function to determine an item's category
def get_volume_category(item):
# multiply width x height x depth to calculate volume
volume = item["unit_width"]*item["unit_depth"]*item["unit_hei... |
# create item dictionaries
item_1 = {
"item_code": "84500",
"item_description": "CHOCOLATE SHORTCAKE",
"customer_name": "FROSTY TREATS",
"gross_weight": 15.95
}
item_2 = {
"item_code": "84400",
"item_description": "STRAWBERRY SHORTCAKE",
"customer_name": "FROSTY TREATS",
"gross_weight":... |
def printboard(dict1):
print("|",dict1[7],"|",dict1[8],"|",dict1[9],"|")
print("------------")
print("|",dict1[4],"|",dict1[5],"|",dict1[6],"|")
print("------------")
print("|",dict1[1],"|",dict1[2],"|",dict1[3],"|")
print("THE TIC TAC TOE")
print("Hi, Welcome to the game , the game rul... |
"""
msg = input("What's The Secret Password? ")
while msg != "bananas":
print("WRONG!")
msg = input("What's The Secret Password? ")
print("Correct!")
"""
smiley = "\U0001f600"
times = 10
for num in range(1,11):
print(smiley * num)
while times > 0:
print(smiley * times)
times-=1 |
# Add
# Adds an element to a set
# If element already in set, set doesn't change
s = set([1,2,3])
print(f"\nOriginal Set: {s}")
s.add(4)
print(f"'4' Added To Set: {s}")
# Remove
# Removes value from set
# KeyError if value not found
# Use 'discard()' to remove without KeyError
s.remove(4)
print(f"'4' Removed From Set... |
# def square(num): return num * num
# print(square(9))
square2 = lambda num: num * num
print(square2(7))
#
# add = lambda a,b: a + b
# print(add(3,10))
#
# Lambda's haven't any name:
# print(square.__name__)
# print(square2.__name__)
# Most commonly used
# when you need to pass a function into a function as a param... |
# Argument Unpacking Using ** As An Argument
# We can use ** as an argument to a function to "unpack" values
#
# See 038_UnpackingTuples.py for further reference
def display_names(first, second):
print(f"{first} says hello to {second}")
names = {"first": "Colt", "second":"Rusty"}
display_names(**names)
# Without *... |
import random
rand_num = random.randint(1,10)
while True:
guess = int(input("\nPick A Number From 1 To 10: "))
if guess < rand_num:
print("Too Low!")
elif guess > rand_num:
print("Too High!")
else:
print("YOU GOT IT!")
play_again = input("\nDo You Want To Play Again? (y/n) ")
if play_again == "y":
... |
import os
import cv2
from PIL import Image
'''
This class is used to seperate single symbol with equation according to its file name length
'''
# This class is used to seperate single and equation from the annotated data
class TestEqual:
def getEqual(self):
dataroot = os.getcwd() + "/data/annotated_train/"... |
from string import punctuation, whitespace
class DateSniffer:
SNIPPET_BEFORE = 40
SNIPPET_AFTER = 40
MONTH = [
'january', 'february', 'march', 'april',
'may', 'june', 'july', 'august',
'september', 'october', 'november', 'december'
]
MONTH_ABBR = [
'jan', 'feb', 'm... |
# befor
# class NewsPerson:
# """This is a high-level module"""
# @staticmethod
# def publish(news: str) -> None:
# """
# :param news:
# :return:
# """
# print(NewsPaper().publish(news=news))
# class NewsPaper:
# """This is a low-level module"""
# @staticmeth... |
import re
import the_minion_game_data as data
TC3 = """BANANANAAAS"""
# See discussion below
HUNDRED = data.TC5[:100]
TWOK = data.TC5[:2000]
THREEK = data.TC5[:3000]
FOURK = data.TC5[:4000]
DODGY = data.TC5[:4250]
# ABBREV5 = data.TC5[:5000] between 4k and 5k causes problems.
# Setting ulimit -v 2000000 is too small f... |
import requests
import time
status_url = 'http://www.proofofexistence.com/api/v1/status'
register_url = 'http://www.proofofexistence.com/api/v1/register'
class TimestampFile:
def __init__(self, file_hash):
self.file_hash = file_hash
@property
def request_timestamp(self):
"""
... |
import numpy as np
import cv2
#image read
img = cv2.imread('Screenshot_2.png', cv2.IMREAD_COLOR)
#to draw circle on the imgae
cv2.circle(img,(200,200),70,(0,0,255),3)
# (img,centre ,radius ,color,thickness=None,lineType=None) if thickness=-1 then circle get filled otherwise empty
cv2.imshow('draw'... |
#Introduction to Python
for i in range(5):
print('I am a ghost')
print('Will this give me an error?')
|
def repeat_times(n):
s = 0
n_str = str(n)
while (n > 0):
n -= sum([int(i) for i in list(n_str)])
n_str = list(str(n))
s += 1
return s
print(repeat_times(9))
print(repeat_times(21)) |
import calendar
y = int (input ("Introduzca el año: "))
m = int (input ("introduzca el mes: "))
print(calendar.month(y,m))
|
def agregaString(str):
if len(str) >= 2 and str [:2] == "Is":
return str
return "Is" + str
print(agregaString("Blue"))
print(agregaString("Isgreen")) |
num = int(input("Please input the number: ")) #Taking input from user
if (num % 2 == 0):
print(num, "is Even")
else:
print(num, "is Odd")
|
from wordcloud import WordCloud, STOPWORDS
txt = "Many times you might have seen a cloud filled with lots of words in different sizes, which represent the frequency or the importance of each word. This is called Tag Cloud or WordCloud. For this tutorial, you will learn how to create a WordCloud of your own in Python a... |
import math
n = int(input())
def palindrome(a):
if a < n:
return False
else:
list_num = str(a)
for i in range(0, len(list_num)//2):
if list_num[i] == list_num[len(list_num) - 1 - i]:
continue
else:
return False
r... |
'''
Basic Python Data Types
Examples and Playground
'''
print("----------------")
# int
x = 3
print(x)
print(type(x))
print("----------------")
# float
x = 3.0
print(x)
print(type(x))
print("----------------")
# float
x = 3e10
print(x)
print(type(x))
print("----------------")
# string
x = "3"
print(x)
print(t... |
'''
Arguments to Functions
Examples and Playground
'''
print("----------------")
# Default Arguments
def log(message = None):
"logs a message, if passed"
if message:
print("LOG: {0}".format(message))
print(log)
log("Hello there!")
print("----------------")
# Default Arguments
def greet(nam... |
#!/usr/bin/env python3
import re
def integers_in_brackets(s):
# result = re.findall(r"\[\s*([+-]?\d+)\s*\]", s)
items = re.findall(r"[\[\{\(][^a-zA-Z\]]+[\}\]\)]", s)
print(items)
L = []
for item in items:
if '+-' not in item and '+]' not in item:
num = re.findall(r"-?\d+", ite... |
#!/usr/bin/env python3
def merge(L1, L2):
L3 = L1 + L2
L = []
while len(L3) > 0:
min = L3[0]
for num in L3:
if num < min:
min = num
L.append(min)
L3.remove(min)
return L
def main():
a = [5, 6, 8]
b = [2, 4, 6]
print(merge(a , b))
... |
#!/usr/bin/env python3
import pandas as pd
def powers_of_series(s, k):
a = []
for i in range(1, k+1):
#df.append(s.values**i)
df = pd.DataFrame(s**i, index=s.index, columns=[i])
a.append(df)
return pd.concat(a, axis=1)
def main():
s = pd.Series([1, 2, 3, 4], index=list("a... |
print(2 - 1)
# print('2' - '1')
first_name = 'Smit'
last_name = 'Patel'
name = first_name + '' + last_name
print(name)
print('Naah, na na nanana naah, nanana naah, hey Jude. \n' *10)
print(f'Hello, {name}!')
actor = 'Joaquin Phoenix'
year = 2020
movie = 'Joker'
print(f'{actor} wins Best Actor for {movie}')
pi = 3.1... |
def main():
print("Mad libs generator!\n")
line1 = "While {} the other day, you noticed a {} {} whizzing by your lawn at a speed of {} km per hour."
wordlist1 = ["(a noun)", "(an adjective)", "(a verb)", "(a number)"]
print(line1.format(wordlist1[2], wordlist1[0], wordlist1[1], wordlist1[3]))
wor... |
def calculate_experince(experinces):
years, months = 0, 0
for exp in experinces:
years += exp['years']
months += exp['months']
years += months / 12
months = months % 12
print 'You have %s years and %s months experience'
with open('test_file.txt') as test_file:
exp = {}
years, months = 0, 0
for line in ... |
def detect_age(age):
if age >= 0 and age <=2:
return "Still in Mama's arms"
elif age >= 3 and age <=4:
return "Preschool Maniac"
elif age >= 5 and age <=11:
return "Elementary school"
elif age >= 12 and age <=14:
return "Middle school"
elif age >= 15 and age <=18:
return "High school"
elif age >= 19 and... |
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# author:艾强云
# Email:1154282938@qq.com
# datetime:2019/7/5 16:08
# software: PyCharm
import math
#log a(di) B(zhen) = c(zhi) a ** c = b
while True:
a = input("请输入底数")
b = input("请输入真数")
c = input("请输入指数")
if a == '':
#利用pow(a, b)函数即可。需要开a的r次方则pow(... |
#num = int(input("Enter number > 5 to print Heart :"))
num = 6
for row in range(num):
for col in range(num+1):
if (row==0 and col%3 !=0) or (row == 1 and col % 3 ==0) or ((row-col)==2) or (row+col==8):
print("* ", end="")
else:
print(" ", end="")
else:
print()... |
class Deque(object):
def __init__(self):
self.items = []
def isempty(self):
return self.items == []
def add_front(self, item):
self.items.append(item)
def add_rear(self, item):
self.items.insert(0, item)
def remove_front(self):
return self.items.pop... |
class BalancedParenthesisCheck(object):
def is_balanced(self, str):
stack = []
opening_parenthesis = ['(', '{', '[']
matches = set(( ('(', ')'), ('{', '}'), ('[',']') ))
for s in str:
if s in opening_parenthesis:
stack.append(s)
el... |
class ReverseWordOrder(object):
@staticmethod
def reverse1(str):
return " ".join(reversed(str.split()))
@staticmethod
def reverse2(str):
return " ".join(str.split()[::-1])
print(ReverseWordOrder.reverse1("best answer"))
print(ReverseWordOrder.reverse2("best answer"))
# ---------... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# 標準ライブラリ
import math
# 3次元座標の変換用クラス
# 高速化のためfor文を使わずベタ書き
# 平行移動
# | 1 0 0 Tx | | x |
# | 0 1 0 Ty | \/ | y |
# | 0 0 1 Tz | /\ | z |
# | 0 0 0 1 | | 1 |
#
# X軸回転
# | 1 0 0 0 | | x |
# ... |
import random
ROCK = "rock"
PAPER = "paper"
SCISSORS = "scissors"
computer_input_list = [ROCK, PAPER, SCISSORS]
computer_input = random.choice(computer_input_list)
#print(computer_input)
comp = ""
if(computer_input == ROCK):
comp = 1;
elif(computer_input == SCISSORS):
comp = 2
else:
comp = 3
user_input = input("E... |
'''
print "Hello"
Mylist = []
for i in range(1,301):
Mylist.append(i)
print(Mylist)
Mylist = []
for x in Mylist:
if (x % 26 == 0):
print(x)
for i in range(1,301):
if(i % 26 == 0):
print(i)
'''
Mylist = []
A=0
for i in range(1,201):
Mylist.append(i)
if(i % 17 == 0):
A=A+i
print("Sum ... |
import requests
def main():
currency = get_target_currency()
bitcoin = get_number_of_bitcoins()
converted = convert_bitcoin_to_target(bitcoin, currency)
display_result(bitcoin, currency, converted)
def get_target_currency():
# Get target currency
currencySymbol = ""
currencyInitials = inpu... |
# -*- coding: cp1252 -*-
import csv
InputFile_name = "Day2Part1Data.csv"
InputFile_h = open(InputFile_name,'r')
CSVInput = csv.reader(InputFile_h)
next(CSVInput) #HEADER
valid_pw = 0
for record in CSVInput:
min_occ = int(record[0].strip())
max_occ = int(record[1].strip())
letter = reco... |
def cargar_archivo(lab):
return open(lab)
## Mat es la copia de la matriz que se carga en el archivo,fil (fila inicial), col (Columna inicial) , aux ( Ayuda a controlar el tamao de la matriz
## para no salirse del limite), tam (es el tamao del lado de la matriz cargada nxn)
def Derecha(mat,fil,col,aux,tam... |
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
# 1
''' load the dataset'''
museum_data = pd.read_csv('museum.csv',index_col=0,parse_dates=True)
# 2
'''print last five rows of dataset'''
print(museum_data.tail())
''' Fill in the line below: How many visitors did the Chinese Amer... |
# 1
def select_second(L):
"""Return the second element of the given list. If the list has no second
element, return None.
"""
if len(L)<2:
return None
else:
return L[1]
# 2
def losing_team_captain(teams):
"""Given a list of teams, where each team is a list of names, ... |
#영단어 맞추기 게임
import random
words_dict = {
"사자" : "lion",
"호랑이" : "tiger",
"사과" : "apple",
"비행기" : "airplane",
}
words = []
for word in words_dict:
words.append(word)
random.shuffle(words)
chance = 3
for i in range(0, len(words)): #문제 개수 (4개)
q = words[i]
for j in range(0, chance): #총 기회... |
# Simulation of Proof Of Work Protocol
from block import Block
import hashlib
# Function to solve math puzzle; find a SHA256 hash key depending on the difficulty set
def pow(key, difficulty):
dif_list = [0] * difficulty
dif_str = "".join(str(x) for x in dif_list)
nonceValue = 0
hash_value = hashlib.s... |
# https://leetcode.com/problems/validate-binary-search-tree/
# Given the root of a binary tree, determine if it is a valid binary search tree (BST).
# A valid BST is defined as follows:
# The left subtree of a node contains only nodes with keys less than the node's key.
# The right subtree of a node contains only nodes... |
# https://leetcode.com/problems/number-of-1-bits/
# Write a function that takes an unsigned integer
# and returns the number of '1' bits it has (also known as the Hamming weight).
# O(number of 1 bits in n) time complexity, O(1) space complexity
def hamming_weight(n):
"""
:type n: int
:rtype: int
"""
... |
# https://leetcode.com/problems/best-time-to-buy-and-sell-stock/
# You are given an array prices where prices[i] is the price of a given stock on the ith day.
# You want to maximize your profit by choosing a single day to buy one stock
# and choosing a different day in the future to sell that stock.
# Return the maximu... |
# https://leetcode.com/problems/merge-sorted-array/
# Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as one sorted array.
# The number of elements initialized in nums1 and nums2 are m and n respectively.
# You may assume that nums1 has a size equal to m + n
# such that it has enough space to ho... |
# Bubble sort O(n^2) - super inefficient, space complexity O(1)
def bubble_sort(num_list):
"""Bubble sort. Sorts the list of integers passed to it as an argument."""
for _ in num_list:
for i in range(len(num_list) - 1):
if num_list[i] > num_list[i + 1]:
# Swap the two number... |
# https://leetcode.com/problems/excel-sheet-column-number/
# Given a string columnTitle that represents the column title as appear in an Excel sheet,
# return its corresponding column number.
def title_to_number(column_title):
"""
:type column_title: str
:rtype: int
"""
title = column_title.lower()
... |
# Merge sorted arrays O(a+b)
def merge_sorted_arrays(array1, array2):
merged_array = []
i = 0
j = 0
while i < len(array1) or j < len(array2):
if i < len(array1) and j < len(array2):
# Append the smaller item to the merge_array
if array1[i] < array2[j]:
m... |
# https://leetcode.com/problems/longest-substring-without-repeating-characters/
# Given a string s, find the length of the longest substring without repeating characters.
# Solution 1 - moving window
# O(n) time complexity, O(n) space complexity
def length_of_longest_substring(s):
"""
:type s: str
:rtype: ... |
# Hackerrank problem
# Determine the maximum positive spread for a stock given its price history
# If the stock remains flat or declines for the full period, return -1
# Complete the 'maxDifference' function below.
#
# The function is expected to return an INTEGER.
# The function accepts INTEGER_ARRAY px as parameter... |
# https://leetcode.com/problems/count-and-say/
# The count-and-say sequence is a sequence of digit strings defined by the recursive formula:
# countAndSay(1) = "1"
# countAndSay(n) is the way you would "say" the digit string from countAndSay(n-1),
# which is then converted into a different digit string.
# To determine ... |
# https://leetcode.com/problems/maximum-number-of-balloons/
# Given a string text,
# you want to use the characters of text to form as many instances of the word "balloon" as possible.
# You can use each character in text at most once. Return the maximum number of instances that can be formed.
# Solution 1 - two dicti... |
from collections import deque
class Graph:
def __init__(self, adjacency_list):
self.adjacency_list = adjacency_list
# O(v + e) time complexity (every node and every edge is visited)
# O(n) space complexity
def bfs_traversal(self, start):
if len(self.adjacency_list) > 0:
qu... |
# https://leetcode.com/problems/binary-tree-right-side-view/
# Given the root of a binary tree, imagine yourself standing on the right side of it,
# return the values of the nodes you can see ordered from top to bottom.
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, val=0, left... |
__author__ = 'Ciaran'
import random
def generateWord():
list_of_words = ["python", "jumble", "easy", "difficult", "answer", "xylophone"]
randomWord = random.choice(list_of_words)
#print(word)
return randomWord
def showBlank(randomWord):
blankWord = len(randomWord) * "*"
print(blankWord)
# d... |
a = float(input('Podaj liczbę:'))
wynik = a == 7 or (
a % 2 == 0 and
a % 3 == 0 and
a > 10
)
print(f"Liczba jest podzielna przez 2 i 3, większa od 10 lub równa 7: {wynik}")
|
napis = input("Podaj napis z jednym nawiasem <>: ")
for litera in napis:
if litera == "<":
# print(napis.index(litera))
x = napis.index(litera)
elif litera == ">":
y = napis.index(litera)
print(f" Ilość znaków w nawiasie wynosi: {y - x - 1}")
# inne rozwiazanie
licznik = 0
czy_zliczac... |
class Vector:
def __init__(self, x=0, y=0):
self.x = x
self.y = y
def __str__(self):
return f"Wektor: {self.x}, {self.y}"
def __add__(self, other):
nowy_x = self.x + other.x
nowy_y = self.y + other.y
return Vector(nowy_x, nowy_y)
v1 = Vector(1,3)
v2 = Vect... |
#program do liczenia objętości pudła i sprawdzić czy jest większa od 1 litra
a = float(input('Podaj wymiar podstawy a w cm'))
b = float(input('Podaj wymiar podstawy b w cm'))
h = float(input('Podaj wymiar wysokości h w cm'))
V = a * b * h
print(f"Objęstość pudła jest: {V} cm3 i jest większa od 1 litra: {V>1000}")
if... |
# while inicializado en True y se sale con break
while True:
n=int(input("Ingrese numero entre 100 y 200: "))
if 100<=n<=200: # if n>=100 and n<=200
break
else:
print("Fuera de Rango!!!")
if n%2==0:
print(f"{n} es par")
else:
print(f"{n} es impar") |
'''
Calcular la potencia de un numero usando ciclos (no podra usar el operador aritmetico **), para ellos, el sistema solicitará por pantalla el valor de la base y el valor del exponente (ejemplo, base=4, exponente=2, entonces el resultado será 16), una vez realizado el calculo se mostrara el resultado por una salida p... |
# Enunciado 5
# Diego Sobarzo Licandeo
# PGY1121_004V
def funcion():
primerNumero = float(input("Introduce un primer número: "))
segundoNumero = float(input("Introduce un segundo número: "))
if primerNumero > segundoNumero:
return 1
elif primerNumero < segundoNumero:
return -1
else:... |
import pygame
from Hero import HERO
pygame.init()
# ----- these varaibles will be used to create the menu as well as the light version of the game ------ #
WHITE = (255,255,255)
GREY = (70,70,70)
LRED = (189,147,216)
RED = (180,122,234)
LGREEN = (49,203,0)
GREEN = (17,152,34)
LBLUE = (123,205,186)
BLUE = (113,169,24... |
import json
import math
input_x = int(input("Enter origin X coordinate: "))
input_y = int(input("Enter origin Y coordinate: "))
def sortfunction(c):
x = int(c["value"].split(",")[0])
y = int(c["value"].split(",")[1])
return math.sqrt(math.pow(x-input_x, 2) + math.pow(y-input_y, 2))
def getClosestCoordina... |
def is_prime(x):
hits=0
for i in range(1,x+1):
if x % i == 0:
hits += 1
if hits == 2:
return True
else:
return False |
from random import randrange
random_number = randrange(1, 10)
count = 0
# Start your game!
while (count<3):
guess = int(raw_input("Enter Guess:"))
count += 1
if (guess == random_number):
print "You win!"
break
else:
print "You lose"
|
# -*- coding: utf-8 -*-
"""
Problem 6 - Sum square difference
Created on Thu Jan 15 00:16:07 2015
@author: Richard Decal, decal@uw.edu
"""
x = sum(range(1,101)) ** 2 - sum([x**2 for x in range(1,101)])
print x
|
for i in range(1, 5):
for j in range(1, 5):
for n in range(1, 5):
if i != j != n:
print(i, j, n) |
a = 'hello,world'
b = 1.414
c = (1 != 2)
d = (True and False)
e = (True or False)
print("a:%s;b:%.2f;c:%s;d:%s;e:%s" %(a, b, c, d, e))
print("\\\"hello,world\"") |
coins = [1, 2, 5]
combos = [1] + [0] * 11
for coin in coins:
print('coin ', coin)
for i in range(coin, 12):
print('coin:' , coin, ' i:', i, ' i-coin:', i-coin)
combos[i] += combos[i-coin]
print('combos ', combos)
def all_coin_change_combinations(amount_to_divide, coin_array):
... |
def percent_method(string):
print("This prints your string - %s - using the percentage method." % string)
def format_method(string):
print("This prints your string - {} - using the .format method.".format(string))
def f_method(string):
print(f"This prints your string - {string} - using the f-string meth... |
def enumerate_inputs(data):
enumerated = enumerate(data)
print('Printing enumerated items...')
for item in enumerated:
print(item)
def zip_two_inputs(iterable1, iterable2):
zipped = zip(iterable1, iterable2)
print('Printing zipped items...')
for item in zipped:
print(item)
d... |
from collections import deque
from queue import PriorityQueue
# hash map representation of a graph problem
test_graph = {
"A": {"B": 2, "C": 5},
"B": {"D": 7, "C": 5},
"C": {"D": 2, "E": 4},
"D": {"F": 1},
"E": {"D": 6, "F": 3},
"F": {}
}
costs = {
"A": 0,
"B": float("inf"),
"C": f... |
dic={ "I":1 , "V":5 , "X":10 , "L":50 , " C":100 , "D":500 , "M":1000 }
def roman2int(roman ):
inty=[dic [liczba] for liczba in list(roman )]
last = inty[0]
i=1;
while i< (len(inty)):
if last < inty[i]:
inty[i-1]=- inty[i-1]
if(i<len(inty)):
last=inty[i-1]
i = i + 1
return sum(inty)
x = raw_input(... |
class Queue:
def __init__(self):
self.items = []
def __str__(self): # podgladanie kolejki
return str(self.items)
def is_empty(self):
return not self.items
def is_full(self): # nigdy nie jest pusta
return False
def put(self, data):
if self.is_full():
raise ValueError("kolej... |
#mamy a * x + b * y + c = 0
#przedstawia ono linie prosta o parametrach a,b,c
#upraszczam problem:
#algorytm szukania miejsca zerowego prostej y = a*x + b
#gdzie mamy zadane a i b:
def solve1(a, b):
"""Rozwiazywanie rownania liniowego y = a*x + b ."""
if a==0:
if b==0:
print 'rownanie ma nieskonczenie wiele r... |
#=================================================================
class Stack:
def __init__(self, size=10):
self.items = size * [None] # utworzenie tablicy
self.n = 0 # liczba elementow na stosie
self.size = size
def is_empty(self):
return self.n == 0
def is_full(self):
return self.size == self.n
... |
#
# @lc app=leetcode.cn id=1207 lang=python3
#
# [1207] 独一无二的出现次数
#
# https://leetcode-cn.com/problems/unique-number-of-occurrences/description/
#
# algorithms
# Easy (66.73%)
# Likes: 25
# Dislikes: 0
# Total Accepted: 9.2K
# Total Submissions: 13.4K
# Testcase Example: '[1,2,2,1,1,3]'
#
# 给你一个整数数组 arr,请你帮忙统计数组... |
"""
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.
"""
# 比较蠢的方法:
import copy
def is_palindromic(num):
tmp=list(repr(num))
tmp_reverse=copy.copy(tmp... |
#
# @lc app=leetcode.cn id=69 lang=python3
#
# [69] x 的平方根
#
# https://leetcode-cn.com/problems/sqrtx/description/
#
# algorithms
# Easy (37.24%)
# Likes: 274
# Dislikes: 0
# Total Accepted: 80K
# Total Submissions: 214.7K
# Testcase Example: '4'
#
# 实现 int sqrt(int x) 函数。
#
# 计算并返回 x 的平方根,其中 x 是非负整数。
#
# 由于返回类型... |
#
# @lc app=leetcode.cn id=844 lang=python3
#
# [844] 比较含退格的字符串
#
# https://leetcode-cn.com/problems/backspace-string-compare/description/
#
# algorithms
# Easy (49.30%)
# Likes: 96
# Dislikes: 0
# Total Accepted: 16.8K
# Total Submissions: 33.5K
# Testcase Example: '"ab#c"\n"ad#c"'
#
# 给定 S 和 T 两个字符串,当它们分别被输入到空... |
#
# @lc app=leetcode.cn id=24 lang=python3
#
# [24] 两两交换链表中的节点
#
# https://leetcode-cn.com/problems/swap-nodes-in-pairs/description/
#
# algorithms
# Medium (63.21%)
# Likes: 353
# Dislikes: 0
# Total Accepted: 56.6K
# Total Submissions: 89.6K
# Testcase Example: '[1,2,3,4]'
#
# 给定一个链表,两两交换其中相邻的节点,并返回交换后的链表。
#
#... |
#
# @lc app=leetcode.cn id=25 lang=python3
#
# [25] K 个一组翻转链表
#
# https://leetcode-cn.com/problems/reverse-nodes-in-k-group/description/
#
# algorithms
# Hard (55.24%)
# Likes: 320
# Dislikes: 0
# Total Accepted: 29.9K
# Total Submissions: 54.2K
# Testcase Example: '[1,2,3,4,5]\n2'
#
# 给你一个链表,每 k 个节点一组进行翻转,请你返回翻... |
#
# @lc app=leetcode.cn id=214 lang=python3
#
# [214] 最短回文串
#
# https://leetcode-cn.com/problems/shortest-palindrome/description/
#
# algorithms
# Hard (30.91%)
# Likes: 109
# Dislikes: 0
# Total Accepted: 5.5K
# Total Submissions: 17.6K
# Testcase Example: '"aacecaaa"'
#
# 给定一个字符串 s,你可以通过在字符串前面添加字符将其转换为回文串。找到并返... |
#
# @lc app=leetcode.cn id=409 lang=python3
#
# [409] 最长回文串
#
# https://leetcode-cn.com/problems/longest-palindrome/description/
#
# algorithms
# Easy (50.96%)
# Likes: 101
# Dislikes: 0
# Total Accepted: 16.2K
# Total Submissions: 31.2K
# Testcase Example: '"abccccdd"'
#
# 给定一个包含大写字母和小写字母的字符串,找到通过这些字母构造成的最长的回文串... |
#
# @lc app=leetcode.cn id=92 lang=python3
#
# [92] 反转链表 II
#
# https://leetcode-cn.com/problems/reverse-linked-list-ii/description/
#
# algorithms
# Medium (48.10%)
# Likes: 308
# Dislikes: 0
# Total Accepted: 35.5K
# Total Submissions: 72.2K
# Testcase Example: '[1,2,3,4,5]\n2\n4'
#
# 反转从位置 m 到 n 的链表。请使用一趟扫描完成... |
#
# @lc app=leetcode.cn id=1048 lang=python3
#
# [1048] 最长字符串链
#
# https://leetcode-cn.com/problems/longest-string-chain/description/
#
# algorithms
# Medium (37.62%)
# Likes: 30
# Dislikes: 0
# Total Accepted: 3.2K
# Total Submissions: 7.9K
# Testcase Example: '["a","b","ba","bca","bda","bdca"]'
#
# 给出一个单词列表,其中... |
#
# @lc app=leetcode.cn id=559 lang=python3
#
# [559] N叉树的最大深度
#
# https://leetcode-cn.com/problems/maximum-depth-of-n-ary-tree/description/
#
# algorithms
# Easy (67.37%)
# Likes: 73
# Dislikes: 0
# Total Accepted: 16.5K
# Total Submissions: 24.3K
# Testcase Example: '[1,null,3,2,4,null,5,6]\r'
#
# 给定一个 N 叉树,找到... |
__author__ = 'yangbin1729'
class Tree:
# ------------------------------- nested Position class -------------------------------
class Position:
def element(self):
raise NotImplementedError('must be implemented by subclass')
def __eq__(self, other):
raise NotImplemente... |
a=5
b=2
if(a<b):
print (a)
else:
print (b) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.