blob_id stringlengths 40 40 | repo_name stringlengths 5 127 | path stringlengths 2 523 | length_bytes int64 22 545k | score float64 3.5 5.34 | int_score int64 4 5 | text stringlengths 22 545k |
|---|---|---|---|---|---|---|
b3e1d545b107f607cc46e42a9e281af98cf4626c | psychotechnik/esq-currencies | /money/moneyd_classes.py | 24,252 | 3.734375 | 4 | # -*- coding: utf-8 -*-
from decimal import Decimal
import locale
# NOTE: this sets the default locale to the local environment's (and
# something other than the useless 'C' locale), but possibly it should
# be set/changed depending on the Currency country. However that will
# require a lookup: given the currency code, return the locale code;
# the pycountry package may provide a way to do that. Revisit this
# later. KW 1/2011.
DEFAULT_LOCALE = (
"%s.%s"
% (locale.getdefaultlocale()[0],
locale.getdefaultlocale()[1].lower()))
locale.setlocale(locale.LC_ALL, DEFAULT_LOCALE)
class Currency(object):
"""
A Currency represents a form of money issued by governments, and
used in one or more states/countries. A Currency instance
encapsulates the related data of: the ISO currency/numeric code, a
canonical name, countries the currency is used in, and an exchange
rate - the last remains unimplemented however.
"""
code = 'XYZ'
country = ''
countries = []
name = ''
numeric = '999'
exchange_rate = Decimal('1.0')
def __init__(self, code='', numeric='999', name='', countries=[]):
self.code = code
self.countries = countries
self.name = name
self.numeric = numeric
def __repr__(self):
return self.code
def set_exchange_rate(self, rate):
# This method could later use a web-lookup of the current
# exchange rate; currently it's just a manual field
# setting. 7/2010
if not isinstance(rate, Decimal):
rate = Decimal(str(rate))
self.exchange_rate = rate
# With Currency class defined, setup some needed module globals:
CURRENCIES = {}
CURRENCIES['XYZ'] = Currency(code='XYZ', numeric='999')
DEFAULT_CURRENCY = CURRENCIES['XYZ']
def set_default_currency(code='XYZ'):
global DEFAULT_CURRENCY
DEFAULT_CURRENCY = CURRENCIES[code]
class MoneyComparisonError(TypeError):
# This exception was needed often enough to merit its own
# Exception class.
def __init__(self, other):
assert not isinstance(other, Money)
self.other = other
def __str__(self):
# Note: at least w/ Python 2.x, use __str__, not __unicode__.
return "Cannot compare instances of Money and %s" \
% self.other.__class__.__name__
class Money(object):
"""
A Money instance is a combination of data - an amount and a
currency - along with operators that handle the semantics of money
operations in a better way than just dealing with raw Decimal or
($DEITY forbid) floats.
"""
amount = Decimal('0.0')
currency = DEFAULT_CURRENCY
def __init__(self, amount=Decimal('0.0'), currency=None):
if not isinstance(amount, Decimal):
amount = Decimal(str(amount))
self.amount = amount
if not currency:
self.currency = DEFAULT_CURRENCY
else:
if not isinstance(currency, Currency):
currency = CURRENCIES[str(currency).upper()]
self.currency = currency
def __unicode__(self):
return "%s %s" % (
locale.currency(self.amount, grouping=True),
self.currency)
__repr__ = __unicode__
def __pos__(self):
return Money(
amount=self.amount,
currency=self.currency)
def __neg__(self):
return Money(
amount=-self.amount,
currency=self.currency)
def __add__(self, other):
if not isinstance(other, Money):
raise TypeError('Cannot add a Money and non-Money instance.')
if self.currency == other.currency:
return Money(
amount=self.amount + other.amount,
currency=self.currency)
else:
this = self.convert_to_default()
other = other.convert_to_default()
return Money(
amount=(this.amount + other.amount),
currency=DEFAULT_CURRENCY)
def __sub__(self, other):
return self.__add__(-other)
def __mul__(self, other):
if isinstance(other, Money):
raise TypeError('Cannot multiply two Money instances.')
else:
return Money(
amount=(self.amount * Decimal(str(other))),
currency=self.currency)
def __div__(self, other):
if isinstance(other, Money):
if self.currency != other.currency:
raise TypeError('Cannot divide two different currencies.')
return self.amount / other.amount
else:
return Money(
amount=self.amount / Decimal(str(other)),
currency=self.currency)
def __rmod__(self, other):
"""
Calculate percentage of an amount. The left-hand side of the
operator must be a numeric value.
Example:
>>> money = Money(200, 'USD')
>>> 5 % money
USD 10.00
"""
if isinstance(other, Money):
raise TypeError('Invalid __rmod__ operation')
else:
return Money(
amount=(Decimal(str(other)) * self.amount / 100),
currency=self.currency)
def convert_to_default(self):
return Money(
amount=(self.amount * self.currency.exchange_rate),
currency=DEFAULT_CURRENCY)
def convert_to(self, currency):
"""
Convert from one currency to another.
"""
return None # TODO
__radd__ = __add__
__rsub__ = __sub__
__rmul__ = __mul__
__rdiv__ = __div__
# _______________________________________
# Override comparison operators
def __eq__(self, other):
if not isinstance(other, Money):
raise MoneyComparisonError(other)
return (self.amount == other.amount) \
and (self.currency == other.currency)
def __ne__(self, other):
result = self.__eq__(other)
if result is NotImplemented:
return result
return not result
def __lt__(self, other):
if not isinstance(other, Money):
raise MoneyComparisonError(other)
if (self.currency == other.currency):
return (self.amount < other.amount)
else:
raise TypeError('Cannot compare different currencies (yet).')
def __gt__(self, other):
if not isinstance(other, Money):
raise MoneyComparisonError(other)
if (self.currency == other.currency):
return (self.amount > other.amount)
else:
raise TypeError('Cannot compare different currencies (yet).')
def __le__(self, other):
return self < other or self == other
def __ge__(self, other):
return self > other or self == other
# ____________________________________________________________________
# Definitions of ISO 4217 Currencies
# Source: http://www.iso.org/iso/support/faqs/faqs_widely_used_standards/widely_used_standards_other/currency_codes/currency_codes_list-1.htm
CURRENCIES['BZD'] = Currency(code='BZD', numeric='084', name='Belize Dollar', countries=['BELIZE'])
CURRENCIES['YER'] = Currency(code='YER', numeric='886', name='Yemeni Rial', countries=['YEMEN'])
CURRENCIES['XBA'] = Currency(code='XBA', numeric='955', name='Bond Markets Units European Composite Unit (EURCO)', countries=[])
CURRENCIES['SLL'] = Currency(code='SLL', numeric='694', name='Leone', countries=['SIERRA LEONE'])
CURRENCIES['ERN'] = Currency(code='ERN', numeric='232', name='Nakfa', countries=['ERITREA'])
CURRENCIES['NGN'] = Currency(code='NGN', numeric='566', name='Naira', countries=['NIGERIA'])
CURRENCIES['CRC'] = Currency(code='CRC', numeric='188', name='Costa Rican Colon', countries=['COSTA RICA'])
CURRENCIES['VEF'] = Currency(code='VEF', numeric='937', name='Bolivar Fuerte', countries=['VENEZUELA'])
CURRENCIES['LAK'] = Currency(code='LAK', numeric='418', name='Kip', countries=['LAO PEOPLES DEMOCRATIC REPUBLIC'])
CURRENCIES['DZD'] = Currency(code='DZD', numeric='012', name='Algerian Dinar', countries=['ALGERIA'])
CURRENCIES['SZL'] = Currency(code='SZL', numeric='748', name='Lilangeni', countries=['SWAZILAND'])
CURRENCIES['MOP'] = Currency(code='MOP', numeric='446', name='Pataca', countries=['MACAO'])
CURRENCIES['BYR'] = Currency(code='BYR', numeric='974', name='Belarussian Ruble', countries=['BELARUS'])
CURRENCIES['MUR'] = Currency(code='MUR', numeric='480', name='Mauritius Rupee', countries=['MAURITIUS'])
CURRENCIES['WST'] = Currency(code='WST', numeric='882', name='Tala', countries=['SAMOA'])
CURRENCIES['LRD'] = Currency(code='LRD', numeric='430', name='Liberian Dollar', countries=['LIBERIA'])
CURRENCIES['MMK'] = Currency(code='MMK', numeric='104', name='Kyat', countries=['MYANMAR'])
CURRENCIES['KGS'] = Currency(code='KGS', numeric='417', name='Som', countries=['KYRGYZSTAN'])
CURRENCIES['PYG'] = Currency(code='PYG', numeric='600', name='Guarani', countries=['PARAGUAY'])
CURRENCIES['IDR'] = Currency(code='IDR', numeric='360', name='Rupiah', countries=['INDONESIA'])
CURRENCIES['XBD'] = Currency(code='XBD', numeric='958', name='European Unit of Account 17(E.U.A.-17)', countries=[])
CURRENCIES['GTQ'] = Currency(code='GTQ', numeric='320', name='Quetzal', countries=['GUATEMALA'])
CURRENCIES['CAD'] = Currency(code='CAD', numeric='124', name='Canadian Dollar', countries=['CANADA'])
CURRENCIES['AWG'] = Currency(code='AWG', numeric='533', name='Aruban Guilder', countries=['ARUBA'])
CURRENCIES['TTD'] = Currency(code='TTD', numeric='780', name='Trinidad and Tobago Dollar', countries=['TRINIDAD AND TOBAGO'])
CURRENCIES['PKR'] = Currency(code='PKR', numeric='586', name='Pakistan Rupee', countries=['PAKISTAN'])
CURRENCIES['XBC'] = Currency(code='XBC', numeric='957', name='European Unit of Account 9(E.U.A.-9)', countries=[])
CURRENCIES['UZS'] = Currency(code='UZS', numeric='860', name='Uzbekistan Sum', countries=['UZBEKISTAN'])
CURRENCIES['XCD'] = Currency(code='XCD', numeric='951', name='East Caribbean Dollar', countries=['ANGUILLA', 'ANTIGUA AND BARBUDA', 'DOMINICA', 'GRENADA', 'MONTSERRAT', 'SAINT KITTS AND NEVIS', 'SAINT LUCIA', 'SAINT VINCENT AND THE GRENADINES'])
CURRENCIES['VUV'] = Currency(code='VUV', numeric='548', name='Vatu', countries=['VANUATU'])
CURRENCIES['KMF'] = Currency(code='KMF', numeric='174', name='Comoro Franc', countries=['COMOROS'])
CURRENCIES['AZN'] = Currency(code='AZN', numeric='944', name='Azerbaijanian Manat', countries=['AZERBAIJAN'])
CURRENCIES['XPD'] = Currency(code='XPD', numeric='964', name='Palladium', countries=[])
CURRENCIES['MNT'] = Currency(code='MNT', numeric='496', name='Tugrik', countries=['MONGOLIA'])
CURRENCIES['ANG'] = Currency(code='ANG', numeric='532', name='Netherlands Antillian Guilder', countries=['NETHERLANDS ANTILLES'])
CURRENCIES['LBP'] = Currency(code='LBP', numeric='422', name='Lebanese Pound', countries=['LEBANON'])
CURRENCIES['KES'] = Currency(code='KES', numeric='404', name='Kenyan Shilling', countries=['KENYA'])
CURRENCIES['GBP'] = Currency(code='GBP', numeric='826', name='Pound Sterling', countries=['UNITED KINGDOM'])
CURRENCIES['SEK'] = Currency(code='SEK', numeric='752', name='Swedish Krona', countries=['SWEDEN'])
CURRENCIES['AFN'] = Currency(code='AFN', numeric='971', name='Afghani', countries=['AFGHANISTAN'])
CURRENCIES['KZT'] = Currency(code='KZT', numeric='398', name='Tenge', countries=['KAZAKHSTAN'])
CURRENCIES['ZMK'] = Currency(code='ZMK', numeric='894', name='Kwacha', countries=['ZAMBIA'])
CURRENCIES['SKK'] = Currency(code='SKK', numeric='703', name='Slovak Koruna', countries=['SLOVAKIA'])
CURRENCIES['DKK'] = Currency(code='DKK', numeric='208', name='Danish Krone', countries=['DENMARK', 'FAROE ISLANDS', 'GREENLAND'])
CURRENCIES['TMM'] = Currency(code='TMM', numeric='795', name='Manat', countries=['TURKMENISTAN'])
CURRENCIES['AMD'] = Currency(code='AMD', numeric='051', name='Armenian Dram', countries=['ARMENIA'])
CURRENCIES['SCR'] = Currency(code='SCR', numeric='690', name='Seychelles Rupee', countries=['SEYCHELLES'])
CURRENCIES['FJD'] = Currency(code='FJD', numeric='242', name='Fiji Dollar', countries=['FIJI'])
CURRENCIES['SHP'] = Currency(code='SHP', numeric='654', name='Saint Helena Pound', countries=['SAINT HELENA'])
CURRENCIES['ALL'] = Currency(code='ALL', numeric='008', name='Lek', countries=['ALBANIA'])
CURRENCIES['TOP'] = Currency(code='TOP', numeric='776', name='Paanga', countries=['TONGA'])
CURRENCIES['UGX'] = Currency(code='UGX', numeric='800', name='Uganda Shilling', countries=['UGANDA'])
CURRENCIES['OMR'] = Currency(code='OMR', numeric='512', name='Rial Omani', countries=['OMAN'])
CURRENCIES['DJF'] = Currency(code='DJF', numeric='262', name='Djibouti Franc', countries=['DJIBOUTI'])
CURRENCIES['BND'] = Currency(code='BND', numeric='096', name='Brunei Dollar', countries=['BRUNEI DARUSSALAM'])
CURRENCIES['TND'] = Currency(code='TND', numeric='788', name='Tunisian Dinar', countries=['TUNISIA'])
CURRENCIES['SBD'] = Currency(code='SBD', numeric='090', name='Solomon Islands Dollar', countries=['SOLOMON ISLANDS'])
CURRENCIES['GHS'] = Currency(code='GHS', numeric='936', name='Ghana Cedi', countries=['GHANA'])
CURRENCIES['GNF'] = Currency(code='GNF', numeric='324', name='Guinea Franc', countries=['GUINEA'])
CURRENCIES['CVE'] = Currency(code='CVE', numeric='132', name='Cape Verde Escudo', countries=['CAPE VERDE'])
CURRENCIES['ARS'] = Currency(code='ARS', numeric='032', name='Argentine Peso', countries=['ARGENTINA'])
CURRENCIES['GMD'] = Currency(code='GMD', numeric='270', name='Dalasi', countries=['GAMBIA'])
CURRENCIES['ZWD'] = Currency(code='ZWD', numeric='716', name='Zimbabwe Dollar', countries=['ZIMBABWE'])
CURRENCIES['MWK'] = Currency(code='MWK', numeric='454', name='Kwacha', countries=['MALAWI'])
CURRENCIES['BDT'] = Currency(code='BDT', numeric='050', name='Taka', countries=['BANGLADESH'])
CURRENCIES['KWD'] = Currency(code='KWD', numeric='414', name='Kuwaiti Dinar', countries=['KUWAIT'])
CURRENCIES['EUR'] = Currency(code='EUR', numeric='978', name='Euro', countries=['ANDORRA', 'AUSTRIA', 'BELGIUM', 'FINLAND', 'FRANCE', 'FRENCH GUIANA', 'FRENCH SOUTHERN TERRITORIES', 'GERMANY', 'GREECE', 'GUADELOUPE', 'IRELAND', 'ITALY', 'LUXEMBOURG', 'MARTINIQUE', 'MAYOTTE', 'MONACO', 'MONTENEGRO', 'NETHERLANDS', 'PORTUGAL', 'R.UNION', 'SAINT PIERRE AND MIQUELON', 'SAN MARINO', 'SLOVENIA', 'SPAIN'])
CURRENCIES['CHF'] = Currency(code='CHF', numeric='756', name='Swiss Franc', countries=['LIECHTENSTEIN'])
CURRENCIES['XAG'] = Currency(code='XAG', numeric='961', name='Silver', countries=[])
CURRENCIES['SRD'] = Currency(code='SRD', numeric='968', name='Surinam Dollar', countries=['SURINAME'])
CURRENCIES['DOP'] = Currency(code='DOP', numeric='214', name='Dominican Peso', countries=['DOMINICAN REPUBLIC'])
CURRENCIES['PEN'] = Currency(code='PEN', numeric='604', name='Nuevo Sol', countries=['PERU'])
CURRENCIES['KPW'] = Currency(code='KPW', numeric='408', name='North Korean Won', countries=['KOREA'])
CURRENCIES['SGD'] = Currency(code='SGD', numeric='702', name='Singapore Dollar', countries=['SINGAPORE'])
CURRENCIES['TWD'] = Currency(code='TWD', numeric='901', name='New Taiwan Dollar', countries=['TAIWAN'])
CURRENCIES['USD'] = Currency(code='USD', numeric='840', name='US Dollar', countries=['AMERICAN SAMOA', 'BRITISH INDIAN OCEAN TERRITORY', 'ECUADOR', 'GUAM', 'MARSHALL ISLANDS', 'MICRONESIA', 'NORTHERN MARIANA ISLANDS', 'PALAU', 'PUERTO RICO', 'TIMOR-LESTE', 'TURKS AND CAICOS ISLANDS', 'UNITED STATES MINOR OUTLYING ISLANDS', 'VIRGIN ISLANDS (BRITISH)', 'VIRGIN ISLANDS (U.S.)'])
CURRENCIES['BGN'] = Currency(code='BGN', numeric='975', name='Bulgarian Lev', countries=['BULGARIA'])
CURRENCIES['MAD'] = Currency(code='MAD', numeric='504', name='Moroccan Dirham', countries=['MOROCCO', 'WESTERN SAHARA'])
CURRENCIES['XYZ'] = Currency(code='XYZ', numeric='999', name='The codes assigned for transactions where no currency is involved are:', countries=[])
CURRENCIES['SAR'] = Currency(code='SAR', numeric='682', name='Saudi Riyal', countries=['SAUDI ARABIA'])
CURRENCIES['AUD'] = Currency(code='AUD', numeric='036', name='Australian Dollar', countries=['AUSTRALIA', 'CHRISTMAS ISLAND', 'COCOS (KEELING) ISLANDS', 'HEARD ISLAND AND MCDONALD ISLANDS', 'KIRIBATI', 'NAURU', 'NORFOLK ISLAND', 'TUVALU'])
CURRENCIES['KYD'] = Currency(code='KYD', numeric='136', name='Cayman Islands Dollar', countries=['CAYMAN ISLANDS'])
CURRENCIES['KRW'] = Currency(code='KRW', numeric='410', name='Won', countries=['KOREA'])
CURRENCIES['GIP'] = Currency(code='GIP', numeric='292', name='Gibraltar Pound', countries=['GIBRALTAR'])
CURRENCIES['TRY'] = Currency(code='TRY', numeric='949', name='New Turkish Lira', countries=['TURKEY'])
CURRENCIES['XAU'] = Currency(code='XAU', numeric='959', name='Gold', countries=[])
CURRENCIES['CZK'] = Currency(code='CZK', numeric='203', name='Czech Koruna', countries=['CZECH REPUBLIC'])
CURRENCIES['JMD'] = Currency(code='JMD', numeric='388', name='Jamaican Dollar', countries=['JAMAICA'])
CURRENCIES['BSD'] = Currency(code='BSD', numeric='044', name='Bahamian Dollar', countries=['BAHAMAS'])
CURRENCIES['BWP'] = Currency(code='BWP', numeric='072', name='Pula', countries=['BOTSWANA'])
CURRENCIES['GYD'] = Currency(code='GYD', numeric='328', name='Guyana Dollar', countries=['GUYANA'])
CURRENCIES['XTS'] = Currency(code='XTS', numeric='963', name='Codes specifically reserved for testing purposes', countries=[])
CURRENCIES['LYD'] = Currency(code='LYD', numeric='434', name='Libyan Dinar', countries=['LIBYAN ARAB JAMAHIRIYA'])
CURRENCIES['EGP'] = Currency(code='EGP', numeric='818', name='Egyptian Pound', countries=['EGYPT'])
CURRENCIES['THB'] = Currency(code='THB', numeric='764', name='Baht', countries=['THAILAND'])
CURRENCIES['MKD'] = Currency(code='MKD', numeric='807', name='Denar', countries=['MACEDONIA'])
CURRENCIES['SDG'] = Currency(code='SDG', numeric='938', name='Sudanese Pound', countries=['SUDAN'])
CURRENCIES['AED'] = Currency(code='AED', numeric='784', name='UAE Dirham', countries=['UNITED ARAB EMIRATES'])
CURRENCIES['JOD'] = Currency(code='JOD', numeric='400', name='Jordanian Dinar', countries=['JORDAN'])
CURRENCIES['JPY'] = Currency(code='JPY', numeric='392', name='Yen', countries=['JAPAN'])
CURRENCIES['ZAR'] = Currency(code='ZAR', numeric='710', name='Rand', countries=['SOUTH AFRICA'])
CURRENCIES['HRK'] = Currency(code='HRK', numeric='191', name='Croatian Kuna', countries=['CROATIA'])
CURRENCIES['AOA'] = Currency(code='AOA', numeric='973', name='Kwanza', countries=['ANGOLA'])
CURRENCIES['RWF'] = Currency(code='RWF', numeric='646', name='Rwanda Franc', countries=['RWANDA'])
CURRENCIES['CUP'] = Currency(code='CUP', numeric='192', name='Cuban Peso', countries=['CUBA'])
CURRENCIES['XFO'] = Currency(code='XFO', numeric='Nil', name='Gold-Franc', countries=[])
CURRENCIES['BBD'] = Currency(code='BBD', numeric='052', name='Barbados Dollar', countries=['BARBADOS'])
CURRENCIES['PGK'] = Currency(code='PGK', numeric='598', name='Kina', countries=['PAPUA NEW GUINEA'])
CURRENCIES['LKR'] = Currency(code='LKR', numeric='144', name='Sri Lanka Rupee', countries=['SRI LANKA'])
CURRENCIES['RON'] = Currency(code='RON', numeric='946', name='New Leu', countries=['ROMANIA'])
CURRENCIES['PLN'] = Currency(code='PLN', numeric='985', name='Zloty', countries=['POLAND'])
CURRENCIES['IQD'] = Currency(code='IQD', numeric='368', name='Iraqi Dinar', countries=['IRAQ'])
CURRENCIES['TJS'] = Currency(code='TJS', numeric='972', name='Somoni', countries=['TAJIKISTAN'])
CURRENCIES['MDL'] = Currency(code='MDL', numeric='498', name='Moldovan Leu', countries=['MOLDOVA'])
CURRENCIES['MYR'] = Currency(code='MYR', numeric='458', name='Malaysian Ringgit', countries=['MALAYSIA'])
CURRENCIES['CNY'] = Currency(code='CNY', numeric='156', name='Yuan Renminbi', countries=['CHINA'])
CURRENCIES['LVL'] = Currency(code='LVL', numeric='428', name='Latvian Lats', countries=['LATVIA'])
CURRENCIES['INR'] = Currency(code='INR', numeric='356', name='Indian Rupee', countries=['INDIA'])
CURRENCIES['FKP'] = Currency(code='FKP', numeric='238', name='Falkland Islands Pound', countries=['FALKLAND ISLANDS (MALVINAS)'])
CURRENCIES['NIO'] = Currency(code='NIO', numeric='558', name='Cordoba Oro', countries=['NICARAGUA'])
CURRENCIES['PHP'] = Currency(code='PHP', numeric='608', name='Philippine Peso', countries=['PHILIPPINES'])
CURRENCIES['HNL'] = Currency(code='HNL', numeric='340', name='Lempira', countries=['HONDURAS'])
CURRENCIES['HKD'] = Currency(code='HKD', numeric='344', name='Hong Kong Dollar', countries=['HONG KONG'])
CURRENCIES['NZD'] = Currency(code='NZD', numeric='554', name='New Zealand Dollar', countries=['COOK ISLANDS', 'NEW ZEALAND', 'NIUE', 'PITCAIRN', 'TOKELAU'])
CURRENCIES['BRL'] = Currency(code='BRL', numeric='986', name='Brazilian Real', countries=['BRAZIL'])
CURRENCIES['RSD'] = Currency(code='RSD', numeric='941', name='Serbian Dinar', countries=['SERBIA'])
CURRENCIES['XBB'] = Currency(code='XBB', numeric='956', name='European Monetary Unit (E.M.U.-6)', countries=[])
CURRENCIES['EEK'] = Currency(code='EEK', numeric='233', name='Kroon', countries=['ESTONIA'])
CURRENCIES['SOS'] = Currency(code='SOS', numeric='706', name='Somali Shilling', countries=['SOMALIA'])
CURRENCIES['MZN'] = Currency(code='MZN', numeric='943', name='Metical', countries=['MOZAMBIQUE'])
CURRENCIES['XFU'] = Currency(code='XFU', numeric='Nil', name='UIC-Franc', countries=[])
CURRENCIES['NOK'] = Currency(code='NOK', numeric='578', name='Norwegian Krone', countries=['BOUVET ISLAND', 'NORWAY', 'SVALBARD AND JAN MAYEN'])
CURRENCIES['ISK'] = Currency(code='ISK', numeric='352', name='Iceland Krona', countries=['ICELAND'])
CURRENCIES['GEL'] = Currency(code='GEL', numeric='981', name='Lari', countries=['GEORGIA'])
CURRENCIES['ILS'] = Currency(code='ILS', numeric='376', name='New Israeli Sheqel', countries=['ISRAEL'])
CURRENCIES['HUF'] = Currency(code='HUF', numeric='348', name='Forint', countries=['HUNGARY'])
CURRENCIES['UAH'] = Currency(code='UAH', numeric='980', name='Hryvnia', countries=['UKRAINE'])
CURRENCIES['RUB'] = Currency(code='RUB', numeric='643', name='Russian Ruble', countries=['RUSSIAN FEDERATION'])
CURRENCIES['IRR'] = Currency(code='IRR', numeric='364', name='Iranian Rial', countries=['IRAN'])
CURRENCIES['BMD'] = Currency(code='BMD', numeric='060', name='Bermudian Dollar (customarily known as Bermuda Dollar)', countries=['BERMUDA'])
CURRENCIES['MGA'] = Currency(code='MGA', numeric='969', name='Malagasy Ariary', countries=['MADAGASCAR'])
CURRENCIES['MVR'] = Currency(code='MVR', numeric='462', name='Rufiyaa', countries=['MALDIVES'])
CURRENCIES['QAR'] = Currency(code='QAR', numeric='634', name='Qatari Rial', countries=['QATAR'])
CURRENCIES['VND'] = Currency(code='VND', numeric='704', name='Dong', countries=['VIET NAM'])
CURRENCIES['MRO'] = Currency(code='MRO', numeric='478', name='Ouguiya', countries=['MAURITANIA'])
CURRENCIES['NPR'] = Currency(code='NPR', numeric='524', name='Nepalese Rupee', countries=['NEPAL'])
CURRENCIES['TZS'] = Currency(code='TZS', numeric='834', name='Tanzanian Shilling', countries=['TANZANIA'])
CURRENCIES['BIF'] = Currency(code='BIF', numeric='108', name='Burundi Franc', countries=['BURUNDI'])
CURRENCIES['XPT'] = Currency(code='XPT', numeric='962', name='Platinum', countries=[])
CURRENCIES['KHR'] = Currency(code='KHR', numeric='116', name='Riel', countries=['CAMBODIA'])
CURRENCIES['SYP'] = Currency(code='SYP', numeric='760', name='Syrian Pound', countries=['SYRIAN ARAB REPUBLIC'])
CURRENCIES['BHD'] = Currency(code='BHD', numeric='048', name='Bahraini Dinar', countries=['BAHRAIN'])
CURRENCIES['XDR'] = Currency(code='XDR', numeric='960', name='SDR', countries=['INTERNATIONAL MONETARY FUND (I.M.F)'])
CURRENCIES['STD'] = Currency(code='STD', numeric='678', name='Dobra', countries=['SAO TOME AND PRINCIPE'])
CURRENCIES['BAM'] = Currency(code='BAM', numeric='977', name='Convertible Marks', countries=['BOSNIA AND HERZEGOVINA'])
CURRENCIES['LTL'] = Currency(code='LTL', numeric='440', name='Lithuanian Litas', countries=['LITHUANIA'])
CURRENCIES['ETB'] = Currency(code='ETB', numeric='230', name='Ethiopian Birr', countries=['ETHIOPIA'])
CURRENCIES['XPF'] = Currency(code='XPF', numeric='953', name='CFP Franc', countries=['FRENCH POLYNESIA', 'NEW CALEDONIA', 'WALLIS AND FUTUNA'])
|
44afcb87371f25b5edc54fbf47a794d9287f6fd5 | huynhminhtruong/py | /utils/python_games.py | 1,630 | 3.875 | 4 | import turtle
# Setup Screen
screen = turtle.Screen()
screen.title("Game 1")
screen.bgcolor("black")
screen.setup(width=800, height=600)
screen.tracer(0)
# Setup Paddle A
player_a = turtle.Turtle()
player_a.speed(0)
player_a.shape("square")
player_a.color("white")
player_a.penup()
player_a.goto(-350, 0)
# Setup Paddle B
player_b = turtle.Turtle()
player_b.speed(0)
player_b.shape("square")
player_b.color("white")
player_b.penup()
player_b.goto(350, 0)
# Setup Ball
ball = turtle.Turtle()
ball.speed(10)
ball.shape("square")
ball.color("white")
ball.penup()
ball.goto(0, 0)
ball.dx = 2
ball.dy = 2
# Moving
def player_a_moving_up():
y = player_a.ycor()
y += 20
player_a.sety(y)
def player_a_moving_down():
y = player_a.ycor()
y -= 20
player_a.sety(y)
def player_b_moving_up():
y = player_b.ycor()
y += 20
player_b.sety(y)
def player_b_moving_down():
y = player_b.ycor()
y -= 20
player_b.sety(y)
# Handle keyboard input
screen.listen()
screen.onkeypress(player_a_moving_up, "w")
screen.onkeypress(player_a_moving_down, "s")
screen.onkeypress(player_b_moving_up, "Up")
screen.onkeypress(player_b_moving_down, "Down")
# Main game loop
while True:
screen.update()
# Moving ball
ball.setx(ball.xcor() + ball.dx)
ball.sety(ball.ycor() + ball.dy)
# Border checking
if ball.ycor() > 290:
ball.sety(290)
ball.dy *= -1
if ball.xcor() > 390:
ball.setx(390)
ball.dx *= -1
if ball.ycor() < -290:
ball.sety(-290)
ball.dy *= -1
if ball.xcor() < -390:
ball.setx(-390)
ball.dx *= -1 |
cb67a222b923e0b9810f2867ce8ca87aef4cbeb7 | huynhminhtruong/py | /interview/closure_decorator.py | 1,565 | 3.90625 | 4 | # First class function
# Properties of first class functions:
# - A function is an instance of the Object type.
# - You can store the function in a variable.
# - You can pass the function as a parameter to another function.
# - You can return the function from a function.
# - You can store them in data structures such as hash tables, lists
import logging
import functools as ft
logging.basicConfig(filename="output.log", level=logging.INFO)
def square(n):
return n * n
def mapping(func, a):
n = len(a)
for i in range(n):
a[i] = func(a[i])
return a
def sum_numbers(*args):
a = args # receive params as a tuples
print(a)
def add(*args):
return sum(args)
def product(*args) -> int:
return ft.reduce(lambda x, y: x * y, args)
def sub(*args) -> int:
return ft.reduce(lambda x, y: x - y, args)
def div(*args) -> int:
return ft.reduce(lambda x, y: x // y, args)
def logger(func):
def wrapper(*args):
logging.info("Running function {0} with args: {1}".format(func.__name__, args))
print(func(*args))
return wrapper
@logger
def factor(*args) -> int:
return ft.reduce(lambda x, y: x * y, args, 1)
if __name__ == "__main__":
# n = int(input())
# a = mapping(square, [int(i) for i in input().split()]) # custom mapping
# sum_numbers(*a) # pass params as a tuples
add_n = logger(add)
product_n = logger(product)
sub_n = logger(sub)
div_n = logger(div)
add_n(1, 2)
product_n(1, 2)
sub_n(1, 2)
div_n(10, 2)
factor(1, 2, 3) |
b13834533bd1aa99aa659f69cfa1e591e4177572 | tzontzy13/IN3063-TASK1 | /task1.py | 18,935 | 3.71875 | 4 | import numpy as np
import matplotlib.pyplot as plt
import math
# import datetime to check time spent running script
# makes script as efficent as possible
import datetime
class Game:
# GAMEMODE IS NUMBER ON THE CELL IS COST
def __init__(self, height, width):
# initialize the width and height of the grid
self.height = height
self.width = width
def generateGrid(self):
# generates a Height x Width 2d array with random elements from 0 - 9
grid = np.random.randint(low=0, high=9, size=(self.height, self.width))
# returns the generated grid
return grid
# Wikipedia. 2020.
# Dijkstra's algorithm - Wikipedia.
# [ONLINE] Available at: https://en.wikipedia.org/wiki/Dijkstra%27s_algorithm#Algorithm
# [Accessed 19 December 2020].
# Vaidehi Joshi. 2017.
# Finding The Shortest Path, With A Little Help From Dijkstra | by Vaidehi Joshi | basecs | Medium.
# [ONLINE] Available at: https://medium.com/basecs/finding-the-shortest-path-with-a-little-help-from-dijkstra-613149fbdc8e
# [Accessed 19 December 2020].
def dijkstra(self, grid, start):
# row and col are the lengths of our 2d array (grid is the 2d array)
row = len(grid)
col = len(grid[0])
# cost to each "node" FROM STARTING NODE!. updates as we go through "nodes"
# 2d array mirroring our grid
# at first, the cost to get to each node is 99999999 (a lot)
distance = np.full((row, col), 99999999)
# the cost to our start node is 0
distance[start] = 0
# visited and unvisited nodes
# 2d array mirroring our grid
# visited node is a 1
# unvisited node is a 0
# at first, all nodes are unvisited, so 0
visited = np.zeros((row, col), dtype=int)
# set for holding nodes to check in smallestUnvisited function, so we dont check all nodes every time
# if we had a M x N grid, we would check M x N values for the smallest unvisited one
# with this, we improve the total time of running this script by only checking neightbours of visited nodes
nodesToCheck = set()
nodesToCheck.add((0, 0))
# function to find the smallest distance node, from the unvisited nodes
def smallestUnvisited(distance, nodesToCheck):
# smallest distance node i coordinate
sm_i = -1
# smallest distance node j coordinate
sm_j = -1
# smallest distance node value (initial)
sm = 99999999
# we check every node for the smallest value
for node in nodesToCheck:
i, j = node
if (distance[i][j] < sm):
sm = distance[i][j]
sm_i = i
sm_j = j
# we return the coordinates of our smallest distance unvisited node
return (sm_i, sm_j)
# start going through all nodes in our grid and updating distances
# while there exists nodes to go through (see function declaration above)
while(len(nodesToCheck) != 0):
# get the i and j of smallest distance unvisited node
i, j = smallestUnvisited(distance, nodesToCheck)
# for south, east, norths, west we check if there exists an unvisited node
# we then compare the current distance for that node with
# the distance of the current node plus the cost
# (cost is the number of the next node)
# if the current distance is greater, i change it to the lower value i just computed
# south
# if there exists a node to the south that is UNVISITED
if i+1 < len(distance) and visited[i+1][j] == 0:
# add node to set, to be checked later when we compute the smallest value form unvisited nodes
nodesToCheck.add((i+1, j))
# compute distance
if distance[i+1][j] > grid[i+1][j] + distance[i][j]:
distance[i+1][j] = grid[i+1][j] + distance[i][j]
# east
# if there exists a node to the east that is UNVISITED
if j+1 < len(distance[0]) and visited[i][j+1] == 0:
# add node to set, to be checked later when we compute the smallest value form unvisited nodes
nodesToCheck.add((i, j+1))
# compute distance
if distance[i][j+1] > grid[i][j+1] + distance[i][j]:
distance[i][j+1] = grid[i][j+1] + distance[i][j]
# north
if i-1 >= 0 and visited[i-1][j] == 0:
# add node to set, to be checked later when we compute the smallest value form unvisited nodes
nodesToCheck.add((i-1, j))
# compute distance
if distance[i-1][j] > grid[i-1][j] + distance[i][j]:
distance[i-1][j] = grid[i-1][j] + distance[i][j]
# west
if j-1 >= 0 and visited[i][j-1] == 0:
# add node to set, to be checked later when we compute the smallest value form unvisited nodes
nodesToCheck.add((i, j-1))
# compute distance
if distance[i][j-1] > grid[i][j-1] + distance[i][j]:
distance[i][j-1] = grid[i][j-1] + distance[i][j]
# mark node as visited
visited[i][j] = 1
# remove current node from nodesToCheck, so we dont check it again, causing errors in the flow
nodesToCheck.remove((i, j))
# returning distance to bottom right cornet of 2d array
return distance[row-1][col-1]
# Wikipedia. 2020.
# Breadth-first search - Wikipedia.
# [ONLINE] Available at: https://en.wikipedia.org/wiki/Breadth-first_search
# [Accessed 19 December 2020].
def BFS(self, grid, start):
# BFS is similar to dijskras except it only checks south and east and
# doesnt have a way of picking which node to visit next
# it always picks the first node in the queue
# row and col are the lengths of our 2d array (grid is the 2d array)
row = len(grid)
col = len(grid[0])
# cost to each "node" FROM STARTING NODE!!!!!!!!!!. updates as we go through "nodes"
# 2d array mirroring our grid
# at first, the cost to get to each node is 99999999 (a lot)
distance = np.full((row, col), 99999999)
# the cost to our start node is 0
distance[start] = 0
# data structure for keeping visited nodes, so we dont visit more than once and go into an infinite loop
visited = np.zeros((row, col))
# queue for checking nodes
queue = []
# we add first node to queue
queue.append((0, 0))
# while queue is not empty
while(len(queue) != 0):
# get coordinates of first node in queue
i, j = queue[0]
# remove first node from queue
queue.pop(0)
# mark it as visited
visited[i][j] = 1
# if South node exists, is not visited and not already in the queue
if(i+1 < row and visited[i+1][j] == 0 and (i+1,j) not in queue):
# add node to queue
queue.append((i+1, j))
# compute distance
if distance[i+1][j] > grid[i+1][j] + distance[i][j]:
distance[i+1][j] = grid[i+1][j] + distance[i][j]
# if East node exists
if(j+1 < col and visited[i][j+1] == 0 and (i,j+1) not in queue):
# add node to queue
queue.append((i, j+1))
# compute distance
if distance[i][j+1] > grid[i][j+1] + distance[i][j]:
distance[i][j+1] = grid[i][j+1] + distance[i][j]
# return distance to bottom right corner (calculated only with right and down movements)
return distance[row-1][col-1]
# Ali Mirjalili. 2018.
# Inspiration of Ant Colony Optimization - YouTube.
# [ONLINE] Available at: https://www.youtube.com/watch?v=1qpvpOHGRqA&ab_channel=AliMirjalili
# [Accessed 19 December 2020].
# Ali Mirjalili. 2018.
# How the Ant Colony Optimization algorithm works - YouTube.
# [ONLINE] Available at: https://www.youtube.com/watch?v=783ZtAF4j5g&t=235s&ab_channel=AliMirjalili
# [Accessed 19 December 2020].
# Wikipedia. 2020.
# Ant colony optimization algorithms - Wikipedia.
# [ONLINE] Available at: https://en.wikipedia.org/wiki/Ant_colony_optimization_algorithms#Algorithm_and_formulae
# [Accessed 19 December 2020].
# Wikipedia. 2020.
# Fitness proportionate selection - Wikipedia.
# [ONLINE] Available at: https://en.wikipedia.org/wiki/Fitness_proportionate_selection
# [Accessed 19 December 2020].
def ant_colony(self, grid, start):
# row and col are the lengths of our 2d array (grid is the 2d array)
row = len(grid)
col = len(grid[0])
# end node
end = (row - 1, col - 1)
# initialize pheromones (similar to weights from neural networks)
pheromones = np.ones(shape=(row, col))
# constant that gets divided by a distance when updating pheromones
# used for updateing pheromones
q_constant = 1.1
# constant that "fades out" the pheromones
evaporation_rate = 0.55
# set number of generations (epochs) and ants
ants = 256*3+32+8+16+32+128+32
gens = 32+16+8+4+8
# initial shortest path
shortest_path = 99999999
# helper functions
# selects a node for the ant to visit
def roulette_select(current_node, nodes_to_check):
# nodes to check contains the neighbours of current node that meet a specific criteria (exist, not in current path)
# n = probability
n = np.random.uniform(0, 1)
# sum of all activations (a)
s = 0
# list for nodes and probability of nodes
prob = []
nodes = []
# for each node
for node in nodes_to_check:
# add it to nodes
nodes.append(node)
# create activation (a) based on distance and pheromones
# if the pheromones are low, the activation will be low
# if the distance is low, the activation will be high
if(distance(current_node, node) != 0):
a = (1 / distance(current_node, node)) * \
pheromone(current_node, node)
else:
a = pheromone(current_node, node)
# add activation to sum
s += a
# add activation to probability list
prob.append(a)
prob = np.array(prob, dtype='float64')
# divide the probability list by the sum
# prob now contains the probability of each node to be picked
# sum of probability list is now 1
prob = prob / s
# choose a node based on the probability list generated above and n
cumulative_sum = 0
chosen = 0
# developed this code using the pseudocode from Wikipedia and a YouTube video
# Wikipedia. 2020.
# Fitness proportionate selection - Wikipedia.
# [ONLINE] Available at: https://en.wikipedia.org/wiki/Fitness_proportionate_selection
# [Accessed 19 December 2020].
# Ali Mirjalili. 2018.
# How the Ant Colony Optimization algorithm works - YouTube.
# [ONLINE] Available at: https://www.youtube.com/watch?v=783ZtAF4j5g&t=235s&ab_channel=AliMirjalili
# [Accessed 19 December 2020].
# adapted pseudocode for my project
for i in range(len(prob)):
if cumulative_sum < n:
chosen = i
cumulative_sum += prob[i]
return nodes[chosen]
# returns the pheromone levels between 2 points
def pheromone(p1, p2):
pher = pheromones[p2[0]][p2[1]]
return pher
# distance between 2 points using "The time spent on a cell is the number on this cell"
def distance(p1, p2):
dist = grid[p2[0]][p2[1]]
return dist
# update pheromones after each generation
def update_pheromones(paths):
# apply evaporation rate
# the pheromones "lose" power after each generation
new_pheromones = (1 - evaporation_rate) * pheromones
# update each pheromone manually
# formula found in Wikipedia
for hist, dist in paths:
for node in hist:
i = node[0]
j = node[1]
# i changed this because I cant divide by 0
if (dist == 0):
dist = 0.75
# update pheromones at a specific node
# pheromone after evaporation + a constant divided by distance traveled by the ant
new_node_pher = new_pheromones[i][j] + (q_constant / dist)
new_pheromones[i][j] = new_node_pher
# return pheromones
return new_pheromones
# starting from node, return a set of new nodes for the the ant to choose from
def update_nodes_to_check(node, path):
i = node[0]
j = node[1]
new_nodes_to_check = set()
# if node exists
# if node not already visited
if((i+1 < row) and ((i+1, j) not in path)):
new_nodes_to_check.add((i+1, j))
if((i-1 >= 0) and ((i-1, j) not in path)):
new_nodes_to_check.add((i-1, j))
if((j+1 < col) and ((i, j+1) not in path)):
new_nodes_to_check.add((i, j+1))
if((j-1 >= 0) and ((i, j-1) not in path)):
new_nodes_to_check.add((i, j-1))
# return the new set of nodes for roulette selection
return new_nodes_to_check
# if a shorter path exists, update the distance of the shortest path
def update_shortest_path(paths):
current_shortest = shortest_path
# check each valid path
# i say valid because sometimes the ant doesnt reach the end node
# that path is not added in the paths list
for hist, dist in paths:
if dist < current_shortest:
# update shortest distance
current_shortest = dist
return current_shortest
# for each generation
for g in range(gens):
# list for storing paths of that generation
paths = []
# for each ant
for a in range(ants):
# start point
current_node = (0, 0)
current_distance = 0
# path of ant
path = set()
path.add(current_node)
# path of ant, in the order of nodes
path_in_order = []
path_in_order.append(current_node)
# nodes to check with roulette selection
nodes_to_check = set()
nodes_to_check.add((1, 0))
nodes_to_check.add((0, 1))
# if there are nodes to check and the current node is not the end node
while (len(nodes_to_check) != 0) and (current_node != end):
# select next node
next_node = roulette_select(current_node, nodes_to_check)
# compute distance to next node from START of path to next node
current_distance += distance(current_node, next_node)
# create a new set of nodes to check in the next while loop
nodes_to_check = update_nodes_to_check(next_node, path)
# set current node to next node
current_node = next_node
# add node to path
path.add(next_node)
path_in_order.append(next_node)
# the ant doesnt always reach the end node (gets lost or trapped), so we check if it found a viable path before adding to paths list
if(end in path):
paths.append([path_in_order, current_distance])
# update pheromones and shortest path for next generation
pheromones = update_pheromones(paths)
shortest_path = update_shortest_path(paths)
# returns the shortest path to end node
return shortest_path
# testing starts here
grid2 = [[1, 9, 9, 9],
[1, 9, 9, 9],
[1, 9, 9, 9],
[1, 1, 1, 1]]
grid6 = [[1, 9, 9],
[1, 9, 9],
[1, 1, 1]]
grid3 = [[1, 4, 1],
[1, 2, 1]]
grid4 = [[0, 9, 9, 9, 9],
[0, 9, 0, 0, 0],
[0, 9, 0, 9, 0],
[0, 9, 0, 9, 0],
[0, 0, 0, 9, 0]]
grid5 = [[0, 9, 0, 0, 0, 0],
[0, 9, 0, 9, 9, 0],
[0, 9, 0, 0, 9, 0],
[0, 9, 9, 0, 9, 0],
[0, 0, 0, 0, 9, 0]]
grid7 = [[0, 6, 4, 5, 1, 4, 3, 5, 6, 8, 7],
[1, 3, 3, 9, 1, 4, 3, 5, 6, 2, 1],
[4, 1, 9, 1, 1, 4, 3, 5, 6, 5, 3],
[9, 6, 1, 2, 1, 4, 3, 5, 6, 2, 1],
[1, 3, 5, 4, 1, 4, 3, 5, 6, 8, 4],
[8, 7, 2, 9, 1, 4, 3, 5, 6, 7, 5],
[1, 6, 3, 5, 1, 4, 3, 5, 6, 2, 2],
[8, 7, 2, 9, 1, 4, 3, 5, 6, 7, 5],
[1, 6, 3, 5, 1, 4, 3, 5, 6, 2, 2],
[8, 7, 2, 9, 1, 4, 3, 5, 6, 7, 5],
[1, 6, 3, 5, 1, 4, 3, 5, 6, 2, 2]]
grid8 = [[1, 9, 9, 9, 9, 9],
[1, 1, 9, 1, 1, 1],
[9, 1, 9, 1, 9, 1],
[9, 1, 9, 1, 9, 1],
[9, 1, 9, 1, 9, 1],
[9, 1, 9, 1, 9, 1],
[9, 1, 1, 1, 9, 1]]
grid9 = [[0, 6, 4, 5],
[1, 3, 3, 9],
[4, 9, 2, 1],
[9, 6, 1, 2],
[2, 3, 4, 5]]
game = Game(14, 14)
grid_genrated = game.generateGrid()
grid = grid_genrated
print('\n')
# compute distance with Dijkstra
begin_time = datetime.datetime.now()
distance = game.dijkstra(grid, (0, 0))
print("time - Dijkstra ", datetime.datetime.now() - begin_time)
print("distance - Dijkstra ", distance)
print('\n')
print("ACO started")
# compute distance with ant colony
begin_time = datetime.datetime.now()
distance3 = game.ant_colony(grid, (0, 0))
print("time - ant_colony ", datetime.datetime.now() - begin_time)
print("distance - ant_colony ", distance3)
print('\n')
# compute distance with BFS
begin_time = datetime.datetime.now()
distance2 = game.BFS(grid, (0, 0))
print("time - BFS ", datetime.datetime.now() - begin_time)
print("distance - BFS ", distance2) |
360d9c21dbf5a48dcc918e4a37edccb36e754e84 | kolbychien/Big_Fish_HW | /text_to_html/file_reader.py | 229 | 3.6875 | 4 |
class FileReader:
def read_file(self, file):
try:
data = open(file, "r")
return data
except FileNotFoundError:
print('{} File Not Found'.format(file))
return '' |
37bcd2c5af0266085fd1f92a598a7c938b7459b9 | sjandro/Python_Projects | /worms.py | 988 | 3.71875 | 4 | # The numbers 1 to 9999 (decimal base) were written on a paper.
# Then the paper was partially eaten by worms. It happened that just those parts of paper
# with digit "0" were eaten.
# Consequently the numbers 1200 and 3450 appear as 12 and 345 respectively,
# whilst the number 6078 appears as two separate numbers 6 and 78.
# What is the sum of the numbers appearing on the worm-eaten paper?
###### WHAT ARE WE LOOKING FOR
# to see your ability to :
# 1) write readable clean code
# 2) problem solving using (if/else/loops/etc ... )
# 3) use parsing, string/numbers dancing
# the "main" function is provided to get you started.
def worms(param):
total = 0
for num in param:
str_num = str(num)
if "0" in str_num:
parts = [int(i) for i in str_num.split("0") if i != ""]
total += sum(parts)
else:
total += num
return total
def main():
print(worms(range(1, 1001)))
if __name__ == '__main__':
main()
|
67b18f00fa58479afbadc342c857a9dcf3dca4f6 | sjandro/Python_Projects | /spiralMatrix.py | 2,990 | 3.828125 | 4 | # n = int(raw_input().split(',')[0])
# matrix = ""
# for i in xrange(1, n + 1):
# if matrix == "":
# matrix = raw_input()
# elif i % 2 == 0:
# row = raw_input().split(',')
# row.reverse()
# #print row
# matrix = matrix + "," + ",".join(row)
# else:
# matrix = matrix + "," + raw_input()
# print matrix
import itertools
arr = [['0','1','2','3'],
['4','5','6','7'],
['8','9','10','11'],
['12','13','14','15']]
def shift(seq, n):
n = n % len(seq)
return seq[n:] + seq[:n]
def buildMatrix(matrix, lst, x, y, start, end):
for num in lst:
print "x: " + str(x) + " y: " + str(y)
matrix[x][y] = num
if x == start and y < end:
y += 1
elif y == end and x < end:
x += 1
elif x == end and y > start:
y -= 1
elif x > start and y == start:
x -= 1
return matrix
def buildSquence(matrix, x, y, start, end, parameter):
l = []
for i in range(parameter):
print "x: " + str(x) + " y: " + str(y)
l.append(matrix[x][y])
if x == start and y < end:
y += 1
elif y == end and x < end:
x += 1
elif x == end and y > start:
y -= 1
elif x > start and y == start:
x -= 1
return l
def transpose_and_yield_top(arr):
# count = 0
while arr:
# if(count == 4):
# break
yield arr[0]
#print arr[0]
#count += 1
l = list(zip(*arr[1:]))
print l
arr = list(reversed(l))
# def outerLayerSize(n):
# if n == 1:
# return 1
# else:
# return n * 4 - 4
# test = ",".join(list(itertools.chain(*transpose_and_yield_top(arr))))
# mlist = [list(i) for i in list(transpose_and_yield_top(arr))]
# final_sque = []
# for i in range(len(mlist)):
# for j in range(len(mlist[i])):
# final_sque.append(mlist[i][j])
# print final_sque
#spiral_matrix = list(itertools.chain(*transpose_and_yield_top(arr)))
#spiral_matrix = final_sque
matrix = [[0 for i in range(len(arr))] for i in range(len(arr))]
#layers = []
params_length = len(arr)
#index = 0
x = 0
y = 0
start = 0
end = len(arr) - 1
while params_length > 0:
#size = outerLayerSize(params_length)
size = 1 if params_length == 1 else params_length * 4 - 4
params_length -= 2
print size
#layers.append(spiral_matrix[index:size+index])
layers = buildSquence(arr, x, y, start, end, size)
print buildMatrix(matrix,shift(layers, -2),x,y,start,end)
#index = size
x += 1
y += 1
start += 1
end -= 1
#print layers
# l = shift(test.split(","), -2)
# print l
# matrix = [[0 for i in range(len(arr))] for i in range(len(arr))]
# print matrix
# x = 0
# y = 0
# start = 0
# end = len(arr) - 1
# for i in range(len(layers)):
# print buildMatrix(matrix,shift(layers[i], -2),x,y,start,end)
# x += 1
# y += 1
# start += 1
# end -= 1
|
6c6b663994ce1242ed06b87b9ed761dcc7952a5a | anitha-mahalingappa/myprograms | /add_sub.py | 340 | 3.796875 | 4 |
def my_add(arg1,arg2):
add = arg1+arg2
print(add)
return add
def my_sub(arg3,arg4):
sub = arg3-arg4
print(sub)
return sub
#main prog
my_num1 = int(input(" enter the number : "))
my_num2 = int(input(" enter the number : "))
var1 = my_add(my_num1,my_num2)
var2 = my_sub(my_num1,my_num2)
print(var1,var2) |
140f58ab33359d4f2fee71db14309ea689af34a1 | luandadantas/100diasdecodigo | /Dia62-laços_while/ingressos_para_o_cinema.py | 240 | 4 | 4 |
while True:
idade = int(input("Qual a sua idade: "))
if idade < 3:
print("Entrada gratuita.")
elif 3 <= idade <= 12:
print("O ingresso é 10 reais.")
elif idade > 12:
print("O ingresso é 15 reais.") |
c8d57ee25e8e01dff8ba1513e2da416a8b9d32e5 | luandadantas/100diasdecodigo | /Dia3-Trabalhando_com_listas/trabalhando_com_listas.py | 655 | 3.578125 | 4 | magicians = ["alice", "david", "carolina"]
for magician in magicians:
print(magician.title() + ", that was a great trick")
print("I can't wait to see yout next trick, " + magician.title() + ".\n")
print("Thank you, everyone. That was a great magic show!\n\n")
# Pizzas
sabores_pizzas = ["Marguerita", "Quatro queijos", "Brócolis"]
for pizza in sabores_pizzas:
print("Gosto de Pizza de " + pizza + ".")
print("\n")
# Animais
animais = ["papagaio", "cachorro", "gato"]
for animal in animais:
print("O " + animal + " é um ótimo animal de estimação")
print("Qualquer um desses animais seria um ótimo animal de estimação.\n") |
900339c6573b404e2d1a9baab95ebab83ff0d77f | luandadantas/100diasdecodigo | /Dia5-Tuplas/tuplas.py | 424 | 3.546875 | 4 | #Buffet
pratos = ("file com fritas", "Macarrão a bolonhesa", "Feijoada", "Batata frita", "Arroz de Leite")
for prato in pratos:
print(prato)
print("\n")
#Certificando de que python rejeita a mudança de uma tupla
#pratos[0] = "Salada"
#print(pratos)
#Sobrescrevendo uma tupla
pratos = ("salada", "Torta de Limão", "Feijoada", "Batata Frita", "Arroz de Leite")
for novos_pratos in pratos:
print(novos_pratos) |
f7b899552df22c76e14b57078c14f7b79db9a93d | luandadantas/100diasdecodigo | /Dia25-Sintaxe_if-elif-else/alien_color.py | 235 | 3.59375 | 4 | alien_color = "vermelho"
if alien_color == verde:
print("O jogador acabou de ganhar 5 pontos")
elif alien_color == amarelo
print("O jogador acabou de ganhar 10 pontos")
else:
print("O jogador acabou de ganhar 15 pontos")
|
c9e94907bcc0cd80b129b6af08d2ada91f73a757 | luandadantas/100diasdecodigo | /Dia51-URI/1070_seis_numeros_impares.py | 122 | 3.65625 | 4 | X = int(input())
cont = 0
while (cont < 6):
if X % 2 != 0:
print(X)
cont = cont + 1
X = X + 1 |
99f8af2cfad89ccad08ff5d2add5f27608d13241 | luandadantas/100diasdecodigo | /Dia6-URI/1019_conversao_de_tempo.py | 550 | 3.890625 | 4 |
'''
Leia um valor inteiro, que é o tempo de duração em segundos de um determinado evento em uma fábrica,
e informe-o expresso no formato horas:minutos:segundos.
Entrada: O arquivo de entrada contém um valor inteiro N.
Saída: Imprima o tempo lido no arquivo de entrada (segundos), convertido para horas:minutos:segundos.
Exemplo de entrada: 556
Exemplo de Saída: 0:9:16
'''
tempo = int(input())
hora = tempo//3600
resto_hora = tempo%3600
minuto = resto_hora//60
segundo = tempo%60
print(str(hora) + ":" + str(minuto) + ":" + str(segundo)) |
18fb3450295c77c92240542858e9f6ac1eda0aff | luandadantas/100diasdecodigo | /Dia17-URI/1013_O_Maior.py | 166 | 3.609375 | 4 | A, B, C = input().split(" ")
A = int(A)
B= int(B)
C = int(C)
AB = (A+B+abs(A-B))/2
maior = (AB+C+abs(AB-C))/2
maior = int(maior)
print(str(maior) + " eh o maior") |
276d376cb90bd570b184389be4b53942cc1349a8 | luandadantas/100diasdecodigo | /Dia27-Finalizando_capitulo5/ingredientes_varias_listas.py | 464 | 3.65625 | 4 | ingredientes_disponíveis = ['tomate', 'brócolis', 'queijo', 'cebola', 'molho']
ingredientes_solicitados = ['tomate', 'batata frita', 'queijo']
for ingrediente_solicitados in ingredientes_solicitados:
if ingrediente_solicitados in ingredientes_disponíveis:
print("Adicionando " + ingrediente_solicitados + ".")
else:
print("Desculpa, nós não temos o ingrediente " + ingrediente_solicitados + ".")
print("\nA pizza está finalizada.")
|
89922c88bab0ebb36e7662ac8af16c974b5ff543 | a-lexgon-z/Alexander_Gonzalez_TE19D | /variabler/variabler.py | 356 | 3.8125 | 4 | name = "Alexander" # har skapat variablen name och tilldelat det värdet "Alexander"
age = 17 # skapat variabeln age och tilldelat det värdet 17
print(f"Hej {name} du är {age} år gammal")
side = float(input("Ange kvadratens sida: "))
area = side**2
omkrets = 4*side
print(f"Kvadratens area är {area} a.e. och lvadratens omkrets är {omkrets} l.e.") |
2690d3485c14aa778f7385128237aabfa345556d | apr-fue/python | /Term 1/hagnman.py | 2,055 | 4.09375 | 4 | #hangman game
#april fuentes
#10/19
#just a game of hangman
#computer picks a word
#player guesses it one letter at a time
#cant guess the word in time
#the stick figure dies
#imports
import random
#constants
HANGMAN = ['''
+---+
| |
|
|
|
|
=========''', '''
+---+
| |
O |
|
|
|
=========''', '''
+---+
| |
O |
| |
|
|
=========''', '''
+---+
| |
O |
/| |
|
|
=========''', '''
+---+
| |
O |
/|\\ |
|
|
=========''', '''
+---+
| |
O |
/|\\ |
/ |
|
=========''', '''
+---+
| |
O |
/|\\ |
/ \ |
|
=========''']
MAX_WRONG = len(HANGMAN) - 1
WORDS = ("BRUH", "YEET", "JELLYFISH", "JOE")
#initialize variables
word = random.choice(WORDS)
so_far = "-" * len(word)
wrong = 0
used = []
print("Welcome to Hangman.")
while wrong < MAX_WRONG and so_far != word:
print(HANGMAN[wrong])
print("\nYou've used the following letters:\n", used)
print("\nSo far, the word is:\n", so_far)
guess = input("\nEnter your guess: ")
guess = guess.upper()
while guess in used:
print("You've already guessed the letter", guess)
guess = input("\nEnter your guess: ")
guess = guess.upper()
used.append(guess)
if guess in word:
print("\nYes!", guess, "is in the word!")
new = " "
for i in range(len(word)):
if guess == word[i]:
new += guess
else:
new += so_far[1]
so_far = new
else:
print("\nSorry,",guess, "isn't in the word")
wrong +=1
if wrong == MAX_WRONG:
print(HANGMAN[wrong])
print("\You've been hanged!")
else:
print("nYou guessed it!")
print("\nThe word was", word)
input("\n\nPress the enter key to exit")
|
5f433c76732e66e4e4ca6677488e717baaf4656f | rjayswal-pythonista/OOP_Python | /Library.py | 2,747 | 4.09375 | 4 | class Library:
def __init__(self, availableBooks):
self.availableBooks = availableBooks
def displaybook(self):
print('List of Available Books in Library are:')
for books in self.availableBooks:
print(books)
def lendbook(self, requestedbook):
if requestedbook in self.availableBooks:
print()
print(f"You have now borrowed book name {requestedbook} from Library")
self.availableBooks.remove(requestedbook)
else:
print(f"Sorry, {requestedBook} is not available in Library now")
def addbook(self, returnedbook):
self.availableBooks.append(returnedbook)
print()
print(f"Thank you for returning book name {returnedbook} to Library")
print()
class Customer:
def requestbook(self):
print('Enter the name of book which you want to borrow from Library: ')
self.book = str(input())
return self.book
def returnbook(self):
print('Enter the name of book which you want to return to Library: ')
self.book = str(input())
return self.book
if __name__ == "__main__":
availableBooks = ['The Lord of the Rings', 'Harry Potter series', 'The Little Prince', 'Think and Grow Rich']
library = Library(availableBooks)
customer = Customer()
print('##########################################################################################################')
print(" Welcome to Roshan Jayswal Library ")
print('##########################################################################################################')
print()
print('Enter your choice: ')
while True:
print()
print('Enter 1 to display available books in Library')
print('Enter 2 to borrow book from Library')
print('Enter 3 to return book to Library')
print('Enter 4 to quit')
userchoice = int(input())
if userchoice == 1:
library.displaybook()
elif userchoice == 2:
requestedBook = customer.requestbook()
library.lendbook(requestedBook)
elif userchoice == 3:
returnedBook = customer.returnbook()
library.addbook(returnedBook)
elif userchoice == 4:
print('#########################################################################################################')
print(' Thank you for visiting Roshan Jayswal Library. See you soon... ')
print('#########################################################################################################')
quit()
|
db4896b8597a48ba911b60c418a20ef74a87648d | Juanmarin444/python_practice | /hello_world.py | 514 | 3.75 | 4 | words = "It's thanksgiving day. It's my birthday, too!"
print words
print words.find('day')
print words.replace("day", "month")
print words
x = [2,54,-2,7,12,98]
print min(x)
print max(x)
y = ["hello",2,54,-2,7,12,98,"world"]
print y[0]
print y[len(y)-1]
new_y = [y[0], y[len(y) - 1]]
print new_y
list_2 = [19,2,54,-2,7,12,98,32,10,-3,6]
print list_2
list_2.sort()
print list_2
half_length = len(list_2)/2
lst = []
for ele in list_2 [:5]:
lst.append(int(ele))
list_2.insert(5, lst)
print list_2[5:]
|
e84ea0ce2afb28b4bb2c13a0f8b44fbbb08788bc | aayanqazi/python-preparation | /A List in a Dictionary.py | 633 | 4.25 | 4 | from collections import OrderedDict
#List Of Dictionary
pizza = {
'crust':'thick',
'toppings': ['mashrooms', 'extra cheese']
}
print("You ordered a " + pizza['crust'] + "-crust pizza " +
"with the following toppings:")
for toppings in pizza['toppings']:
print ("\t"+toppings)
#Examples 2
favourite_languages= {
'jen': ['python', 'ruby'],
'sarah': ['c'],
' edward': ['ruby', 'go'],
'phil': ['python', 'haskell'],
}
for name,languages in favourite_languages.items():
print("\n"+name.title()+"'s favourite languages are :")
for language in languages:
print ("\t"+language.title()) |
2a5a3c3379ac23b7f50123e6e537dea5119119b0 | routedo/cisco-template-example | /configgen.py | 863 | 3.578125 | 4 | """
Generates a configuration file using jinja2 templates
"""
from jinja2 import Environment, FileSystemLoader
import yaml
def template_loader(yml_file, template_file, conf_file):
"""
This function generates a configuration file using jinja2 templates.
yml_file = Location of the file containing variables to use with the jinja2 template
template_file = Location of jinja2 template file
conf_file = Location to place generated config file.
"""
env = Environment(loader=FileSystemLoader('./'))
# Load variables from yml_file
with open(yml_file) as yfile:
yml_var = yaml.load(yfile)
template = env.get_template(template_file)
# Render template
out_text = template.render(config=yml_var)
# Write results of out_text to file
file = open(conf_file, 'w')
file.write(out_text)
file.close()
|
5a8e4bc36057b004f79a5172b0d7de1754fb3fa5 | BaburinAnton/GeekBrains-Python-homeworks | /Lesson 6/hw 3.py | 831 | 3.59375 | 4 | class Worker:
name = None
surname = None
position = None
profit = None
bonus = None
def __init__(self, name, surname, position, profit, bonus):
self.name = name
self.surname = surname
self.position = position
self.profit = profit
self.bonus = bonus
class Position(Worker):
def __init__(self, name, surname, position, profit, bonus):
super().__init__(name, surname, position, profit, bonus)
def get_full_name(self):
return self.name + self.surname
def get_full_profit(self):
self.__income = {'profit': self.profit, 'bonus': self.bonus}
return self.__income
technician = Position('Anton', 'Baburin', 'technician', 28000, 4000)
print(technician.get_full_name(), technician.get_full_profit()) |
194f4c01744ab1d09ed9ca3329624b6768e83b60 | BaburinAnton/GeekBrains-Python-homeworks | /Lesson 4/hw 4.py | 129 | 3.515625 | 4 | numbers = [14, 42, 1, 7, 13, 99, 16, 1, 70, 55, 14, 13, 1, 7]
list = [el for el in numbers if numbers.count(el)==1]
print(list) |
a322c9f894dc53a7e56f5f9bca0ee15d4e666209 | Glitchier/Python-Programs-Beginner | /Day 5/sum_of_even.py | 185 | 3.96875 | 4 | sum=0
for i in range(2,101,2):
sum+=i
print(f"Sum of even numbers: {sum}")
sum=0
for i in range(1,101):
if(i%2==0):
sum+=i
print(f"Sum of even numbers: {sum}") |
05a1e4c378524ef50215bd2bd4065b9ab696b80d | Glitchier/Python-Programs-Beginner | /Day 2/tip_cal.py | 397 | 4.15625 | 4 | print("Welcome to tip calculator!")
total=float(input("Enter the total bill amount : $"))
per=int(input("How much percentage of bill you want to give ? (5%, 10%, 12%, 15%) : "))
people=int(input("How many people to split the bill : "))
bill_tip=total*(per/100)
split_amount=float((bill_tip+total)/people)
final_bill=round(split_amount,2)
print(f"Each person should pay : ${final_bill}") |
f54e2970cd64a45890d02ba9b969257a46642e6f | Glitchier/Python-Programs-Beginner | /Day 9/auction.py | 799 | 3.765625 | 4 | from art import logo
from replit import clear
print(logo)
bid_dic={}
run_again=True
def high_bid(bid_dic_record):
high_amount=0
winner=""
for bidder in bid_dic_record:
bid_amount=bid_dic_record[bidder]
if(bid_amount>high_amount):
high_amount=bid_amount
winner=bidder
print(f"The winner is {winner} with a bid of ${high_amount}")
print("The auction start's here .....")
while(run_again):
key_name=input("Enter your name : ")
key_value=float(input("Enter your bid : $"))
bid_dic[key_name]=key_value
run_again_ch=input("Is there any another bidder? Type Yes or No\n").lower()
if(run_again_ch=="no"):
run_again=False
high_bid(bid_dic)
elif(run_again_ch=="yes"):
clear() |
e88c319709f2822abaea0703fdb94685f3c0de91 | litewhat/internal-linking | /Multiprocessing/m_threading.py | 885 | 3.578125 | 4 | import time
import threading
import multiprocessing
def calc_square(numbers):
print("Calculating square numbers")
for n in numbers:
time.sleep(0.2)
print(f"Square: {n*n}")
def calc_cube(numbers):
print("Calculating cube numbers")
for n in numbers:
time.sleep(0.2)
print(f"Square: {n*n*n}")
if __name__ == "__main__":
arr = [2, 3, 8, 9]
t = time.time()
# calc_square(arr)
# calc_cube(arr)
# t1 = threading.Thread(target=calc_square, args=(arr,))
# t2 = threading.Thread(target=calc_cube, args=(arr,))
p1 = multiprocessing.Process(target=calc_square, args=(arr,))
p2 = multiprocessing.Process(target=calc_cube, args=(arr,))
# t1.start()
# t2.start()
#
# t1.join()
# t2.join()
p1.start()
p2.start()
p1.join()
p2.join()
print(f"Done in: {time.time() - t}")
|
e6cad988204f288958eeb15f365d991b490f6a51 | SharonT2/Practica1IPC2 | /lista.py | 1,696 | 3.875 | 4 | from nodo import Nodo
class Lista():
def __init__(self):#métoedo constructor
#dos referencias
self.primero = None #un nodo primero que inserte el usuario
self.ultimo = None #un nodo que apunta al ultimo nodo
#Creando el primer nodo self, id, nombre, m, n, primero, fin
def insertar(self, ingrediente):
pizza="Pizza de "+ingrediente
nuevo = Nodo(pizza)
if self.primero is None: #si el primero está vacío
self.primero = nuevo #entonces el primero será igual al objeto que mandó el usuario
else: #si el primero no está vacío
tem = self.primero #temporal, para una referencia
while tem.siguiente is not None:#se ejecutará mientras el siguiente sea no sea nulo, cuando encuentre
tem = tem.siguiente #el siguiente que sea nulo
tem.siguiente=nuevo#ahora el siguiente del último nodo ya no será nulo, sino será el nuevo nodo
def eliminar(self):
try:
retorno = self.primero.ingrediente
if self.primero is not None:
if self.primero.siguiente is not None:
self.primero = self.primero.siguiente
else:
self.primero = None
print("Se ha entregado la pizza", retorno)
except:
print("Cola vacía, totalidad de ordenes entregadas")
def mostrar(self):
tem = self.primero#empezando por el principio
i=1
while tem is not None:
print(" |"+str(i)+")",tem.ingrediente+"| ", end=" ")
i+=1
#Listasube.mostrar()
tem = tem.siguiente
|
ad19b0f9e3453d3148f84f0545159d96b90055a1 | HarkTu/Coding-Education | /SoftUni.bg/Python Oop/03-ENCAPSULATION-exercise/01. Wild Cat Zoo.py | 6,196 | 3.546875 | 4 | class Lion:
def __init__(self, name, gender, age):
self.age = age
self.gender = gender
self.name = name
def get_needs(self):
return 50
def __repr__(self):
return f"Name: {self.name}, Age: {self.age}, Gender: {self.gender}"
class Tiger:
def __init__(self, name, gender, age):
self.age = age
self.gender = gender
self.name = name
def get_needs(self):
return 45
def __repr__(self):
return f"Name: {self.name}, Age: {self.age}, Gender: {self.gender}"
class Cheetah:
def __init__(self, name, gender, age):
self.age = age
self.gender = gender
self.name = name
def get_needs(self):
return 60
def __repr__(self):
return f"Name: {self.name}, Age: {self.age}, Gender: {self.gender}"
class Keeper:
def __init__(self, name, age, salary):
self.age = age
self.salary = salary
self.name = name
def __repr__(self):
return f"Name: {self.name}, Age: {self.age}, Salary: {self.salary}"
class Caretaker:
def __init__(self, name, age, salary):
self.age = age
self.salary = salary
self.name = name
def __repr__(self):
return f"Name: {self.name}, Age: {self.age}, Salary: {self.salary}"
class Vet:
def __init__(self, name, age, salary):
self.age = age
self.salary = salary
self.name = name
def __repr__(self):
return f"Name: {self.name}, Age: {self.age}, Salary: {self.salary}"
class Zoo:
def __init__(self, name, budget, animal_capacity,
workers_capacity): # in document says 'animlal_capacity'. 1 test fails without correction
self.animals = []
self.workers = []
self.name = name
self.__workers_capacity = workers_capacity
self.__animal_capacity = animal_capacity
self.__budget = budget
def add_animal(self, animal, price):
if len(self.animals) == self.__animal_capacity:
return "Not enough space for animal"
if price > self.__budget:
return "Not enough budget"
self.animals.append(animal)
self.__budget -= price
return f"{animal.name} the {type(animal).__name__} added to the zoo"
def hire_worker(self, worker):
if len(self.workers) < self.__workers_capacity:
self.workers.append(worker)
return f"{worker.name} the {type(worker).__name__} hired successfully"
return "Not enough space for worker"
def fire_worker(self, worker_name):
for worker_x in self.workers:
if worker_x.name == worker_name:
self.workers.remove(worker_x)
return f"{worker_name} fired successfully"
return f"There is no {worker_name} in the zoo" # on document there was mistaken double space on this line. 1 test fails without correction
def pay_workers(self):
sum_salary = sum([x.salary for x in self.workers])
if sum_salary > self.__budget:
return "You have no budget to pay your workers. They are unhappy"
self.__budget -= sum_salary
return f"You payed your workers. They are happy. Budget left: {self.__budget}"
def tend_animals(self):
sum_tend = sum([x.get_needs() for x in self.animals])
if sum_tend > self.__budget:
return "You have no budget to tend the animals. They are unhappy."
self.__budget -= sum_tend
return f"You tended all the animals. They are happy. Budget left: {self.__budget}"
def profit(self, amount):
self.__budget += amount
def animals_status(self):
result = ''
result += f"You have {len(self.animals)} animals\n"
result += f"----- {sum([1 for x in self.animals if type(x) == Lion])} Lions:\n"
result += '\n'.join([str(x) for x in self.animals if isinstance(x, Lion)])
result += f"\n----- {sum([1 for x in self.animals if isinstance(x, Tiger)])} Tigers:\n"
result += '\n'.join([x.__repr__() for x in self.animals if isinstance(x, Tiger)])
result += f"\n----- {sum(isinstance(x, Cheetah) for x in self.animals)} Cheetahs:\n"
result += '\n'.join([x.__repr__() for x in self.animals if isinstance(x, Cheetah)])
return result + '\n'
def workers_status(self):
result = ''
result += f"You have {len(self.workers)} workers\n"
result += f"----- {sum([1 for x in self.workers if type(x) == Keeper])} Keepers:\n"
result += '\n'.join([x.__repr__() for x in self.workers if isinstance(x, Keeper)])
result += f"\n----- {sum([1 for x in self.workers if isinstance(x, Caretaker)])} Caretakers:\n"
result += '\n'.join([x.__repr__() for x in self.workers if isinstance(x, Caretaker)])
result += f"\n----- {sum(isinstance(x, Vet) for x in self.workers)} Vets:\n"
result += '\n'.join([x.__repr__() for x in self.workers if isinstance(x, Vet)])
return result + '\n' # there is no new line in example solution. 1 test fails without correction
zoo = Zoo("Zootopia", 3000, 5, 8)
# Animals creation
animals = [Cheetah("Cheeto", "Male", 2), Cheetah("Cheetia", "Female", 1), Lion("Simba", "Male", 4),
Tiger("Zuba", "Male", 3), Tiger("Tigeria", "Female", 1), Lion("Nala", "Female", 4)]
# Animal prices
prices = [200, 190, 204, 156, 211, 140]
# Workers creation
workers = [Keeper("John", 26, 100), Keeper("Adam", 29, 80), Keeper("Anna", 31, 95), Caretaker("Bill", 21, 68),
Caretaker("Marie", 32, 105), Caretaker("Stacy", 35, 140), Vet("Peter", 40, 300), Vet("Kasey", 37, 280),
Vet("Sam", 29, 220)]
# Adding all animals
for i in range(len(animals)):
animal = animals[i]
price = prices[i]
print(zoo.add_animal(animal, price))
# Adding all workers
for worker in workers:
print(zoo.hire_worker(worker))
# Tending animals
print(zoo.tend_animals())
# Paying keepers
print(zoo.pay_workers())
# Fireing worker
print(zoo.fire_worker("Adam"))
# Printing statuses
print(zoo.animals_status())
print(zoo.workers_status())
|
32a6b5e833eb5d3a78e8f4b03444da335fe910cb | HarkTu/Coding-Education | /SoftUni.bg/Python Advanced/December 2020/GameOfWords.py | 1,068 | 3.59375 | 4 | initial = input()
size = int(input())
matrix = []
p_row = 0
p_column = 0
for row in range(size):
temp = input()
add_row = []
for column in range(len(temp)):
if temp[column] == 'P':
p_row = row
p_column = column
add_row.append('-')
continue
add_row.append(temp[column])
matrix.append(add_row)
directions = {'up': [-1, 0],
'down': [1, 0],
'left': [0, -1],
'right': [0, 1]
}
commands_count = int(input())
for _ in range(commands_count):
command = input()
next_row = p_row + directions[command][0]
next_column = p_column + directions[command][1]
if 0 <= next_row < size and 0 <= next_column < size:
p_row, p_column = next_row, next_column
if not matrix[next_row][next_column] == '-':
initial += matrix[p_row][p_column]
matrix[p_row][p_column] = '-'
else:
initial = initial[:-1]
matrix[p_row][p_column] = 'P'
print(initial)
for row in matrix:
print(*row, sep='')
|
c2853ed178330ec79e5ed687780430139a103c48 | HarkTu/Coding-Education | /SoftUni.bg/Python Advanced/August 2020/TaxiExpress.py | 504 | 3.75 | 4 | customers = [int(x) for x in input().split(', ')]
taxis = [int(x) for x in input().split(', ')]
time = sum(customers)
while customers and taxis:
customer = customers[0]
taxi = taxis.pop()
if taxi >= customer:
customers.remove(customers[0])
if customers:
print(
f"Not all customers were driven to their destinations\nCustomers left: {', '.join([str(x) for x in customers])}")
else:
print(f"All customers were driven to their destinations\nTotal time: {time} minutes")
|
14a7f65f931c18bf4e7fa39e421d1a688e47356c | rg3915/Python-Learning | /your_age2.py | 757 | 4.3125 | 4 | from datetime import datetime
def age(birthday):
'''
Retorna a idade em anos
'''
today = datetime.today()
if not birthday:
return None
age = today.year - birthday.year
# Valida a data de nascimento
if birthday.year > today.year:
print('Data inválida!')
return None
# Verifica se o dia e o mês já passaram;
# se não, tira 1 ano de 'age'.
if today.month < birthday.month or (today.month == birthday.month and today.day < birthday.day):
age -= 1
return age
if __name__ == '__main__':
birthday = input('Digite sua data de nascimento no formato dd/mm/yyyy: ')
birthday = datetime.strptime(birthday, '%d/%m/%Y')
if age(birthday):
print(age(birthday))
|
3ef31c99b25fbb7b23b367ef87e312753a13a3ab | Jiang-Xiaocha/Lcode | /searchMatrix.py | 1,226 | 3.8125 | 4 | '''
Description:
38. 搜索二维矩阵 II
写出一个高效的算法来搜索m×n矩阵中的值,返回这个值出现的次数。
这个矩阵具有以下特性:
每行中的整数从左到右是排序的。
每一列的整数从上到下是排序的。
在每一行或每一列中没有重复的整数。
样例
考虑下列矩阵:
[
[1, 3, 5, 7],
[2, 4, 7, 8],
[3, 5, 9, 10]
]
给出target = 3,返回 2
挑战
要求O(m+n) 时间复杂度和O(1) 额外空间
'''
class Solution:
"""
@param matrix: A list of lists of integers
@param target: An integer you want to search in matrix
@return: An integer indicate the total occurrence of target in the given matrix
"""
def searchMatrix(self, matrix, target):
# write your code here
if (len(matrix) == 0):
return 0
row = 0
col = len(matrix[0]) - 1
res = 0
while (col>=0 and row <=len(matrix)-1):
if matrix[row][col] == target:
res += 1
col = col - 1
if matrix[row][col] > target:
col = col - 1
if matrix[row][col] < target:
row = row + 1
return res |
a858c6ebc8e7f19176cdd4a2c880ff14e7f14011 | challengeryang/webservicefib | /client_sim/httpclientthread.py | 1,955 | 3.5 | 4 | #!/usr/bin/python
#
# author: Bo Yang
#
"""
thread to send requests to server
it picks up request from job queue, and then picks
up one available connection to send this request
"""
import threading
import Queue
class HttpClientThread(threading.Thread):
"""
Thread to send request to server. it's just a work thread,
and doesn't maintain any state
it picks up job from job queue, and get an available connection
from connection queue, finally send the request through this
connection
"""
def __init__(self, job_queue, connection_queue):
threading.Thread.__init__(self)
self.job_queue = job_queue
self.connection_queue = connection_queue
def run(self):
print '%s: starting' % self.getName()
num_request = 0
while True:
job = None
try:
# get job from job queue
job = self.job_queue.get(True, 3)
except Queue.Empty:
print '%s: no more jobs(sent %d requests), existing' \
% (self.getName(), num_request)
break
num_request += 1
# pick up a conenction from connection queue
conn = self.connection_queue.get(True)
#try:
msg = ""
if job['op'] == 'HEAD':
conn.HEAD(job['val'])
msg = job['op'] + " " + str(job['val'])
elif job['op'] == 'GET':
conn.GET(job['val'])
msg = job['op'] + " " + str(job['val'])
elif job['op'] == 'POST':
conn.POST(job['val'])
msg = job['op'] + " " + str(job['val'])
else:
msg = '%s unsupported operation' % job['op']
print "## " + msg
# put back the connection so other threads can
# use this connection as well
self.connection_queue.put(conn, True)
|
0b6c0ac5676c1071e9728bb00e8bd258ee40339d | yevheniir/python_course_2020 | /.history/1/test_20200606182729.py | 266 | 3.96875 | 4 | people = []
while True:
name = input()
if name == "stop":
break
if name == "show all":
print(people)
pe
print("STOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOP")
# for name in people:
# if name != "JoJo":
# print(name) |
8ca513cdf45e5f286a6fb29abbebdf69e1e84b44 | yevheniir/python_course_2020 | /l5/untitled-master/HW01_star_novela.py | 2,464 | 3.890625 | 4 | import random
print("Вітаю, Ви Колобок і Вас поставили на вікні простигати. Ваші дії:")
print("1 - втекти")
print("2 - залишитися")
a = input("Виберіть дію: ")
if a == "1":
print("Ви зустріли зайця. Ваші дії:")
print("1 - заспівати пісню і втекти")
print("2 - прикинутися пітоном")
print("3 - прикинутися мухомором")
elif a == "2" :
print("Вас з'їли дід та баба. Гра закінчена.")
quit()
else:
print("Виберіть 1 або 2. Гра закінчена.")
quit()
b = input("Виберіть дію: ")
if b == "1":
print("Ви втекли від зайця. Ви зустріли лисицю. Ваші дії")
print("1 - заспівати пісню і втекти.")
print("3 - сказати 'Я хворий на коронавірус'")
print("4 - сказати 'Я зроблений з ГМО зерна'")
elif b == "2" or b == "3":
y = random.choice([True, False])
if y == True:
print("Ви втекли від зайця. Ви зустріли лисицю. Ваші дії")
print("1 - заспівати пісню і втекти.")
print("3 - сказати 'Я хворий на коронавірус'")
print("4 - сказати 'Я зроблений з ГМО зерна'")
else:
print("Заєць Вам не повірив і Вас з'їв. Гра закінчена. ")
quit()
else:
print("Виберіть 1, 2 або 3. Гра закінчена.")
quit()
s = input("Виберіть дію: ")
if s == "1":
y = random.choice([True, False])
if y == True:
print("Ви втекли від лисиці. Гра закінчена.")
quit()
else:
print("Ви не втекли3"
" від лисиці і вона Вас з'їла. Гра закінчена.")
quit()
elif s == "2" or "3" or "4":
y = random.choice([True, False])
if y == True:
print("Лисиця Вам повірила і Ви втекли. Гра закінчена.")
quit()
else:
print("Лисиця Вам не повірила і з'їла. Гра закінчена. ")
quit()
else:
print("Виберіть 1, 2, 3, 4. Гра закінчена.")
quit() |
6c12b0a15ff48d7b1707f162d2f7c7c30a28ea02 | yevheniir/python_course_2020 | /.history/1/dz/1st_game_20200613180427.py | 1,110 | 3.75 | 4 | import time
import random
while True:
print("Вітаю у грі камінь, ножиці, бумага!")
time.sleep(2)
відповідь_до_початку_гри=input("Хочете зіграти?(Відповідати Так або Ні)")
if відповідь_до_початку_гри=="Так":
print("Чудово")
else:
print("Шкода")
time.sleep(9999999999999999999999999999999999999999999999999999999999999999999999999999999)
time.sleep(2)
input("Обирайте предмет.(Камінь-1st-1, Ножиці-2nd-2, чи Бумага-3d-3)")
first=Камінь=1
second=Ножиці=2
third=Бумага=3
ваша_відповідь = 1 or 2 or 3
1 < 3
2 > 1
3 < 2
відповідь_бота=(random.randint(1,3))
if ваша_відповідь<відповідь_бота:
print("Упс. Ви програли")
print(відповідь_бота)
else:
print("Ура ви виграли!")
print(відповідь_бота)
|
32bc00c8b8700da494e559fcd8e2558a43b93e03 | suminov/lesson2 | /lessonfor.py | 564 | 3.96875 | 4 | for x in range(10):
print(x+1)
print(
)
word = input('Введите любое слово: ')
for letter in word:
print(letter)
print(
)
rating = [{'shool_class': '4a', 'scores': [2, 3, 3, 5, 4]},
{'shool_class': '4b', 'scores': [2, 4, 5, 5, 4]},
{'shool_class': '4v', 'scores': [2, 2, 3, 5, 3]}]
a = 0
for result in rating:
print('Средний балл {} класса: {}'
.format(result['shool_class'], sum(result['scores'])/len(result['scores'])))
sum_scores += sum(result['scores'])/len(result['scores'])
print(sum_scores/len(rating)) |
edc0c851a098ede4bb3e4e026e4d0bb6f35451d9 | MDaalder/MIT6.00.1x_Intro_CompSci | /W06_AlgoComplexity_BigO/Sort variants bubble, selection, merge.py | 3,349 | 4.03125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Fri Mar 15 16:21:21 2019
@author: md131
Comparison of sorting methods and their complexities in Big Oh notation.
"""
""" Bubble sort compares consecutive pairs of elements. Overall complexity is O(n^2) where n is len(L)
Swaps elements in the pair such that smaller is first.
When reach the end of the list, start the sort again.
Stop when no more sorts have to be made. """
def bubbleSort(L):
swap = False
while not swap:
swap = True
for j in range(1, len(L)):
if L[j-1] > L[j]: # if L[j-1] is larger than L[j], put element L[j] to the left of L[j-1] by swapping their index values
swap = False
temp = L[j]
L[j] = L[j-1]
L[j-1] = temp
""" Selection sort. Overall complexity is O(n^2) where n is len(L)
1st step: extract the minimum element from the suffix, swap it with index 0 [0] and put into the prefix.
2nd step: extract the minimum element from the remainin sublist (suffix), swap it with index 1 [1], becomes the last element of the prefix.
prefix: L[0:i]
suffix: L[i+1, len(L)]
Always iterating up i. Prefix is always sorted, where no element is larger than in the suffix. """
def selectionSort(L):
suffixSt = 0
while suffixSt != len(L):
for i in range(suffixSt, len(L)):
if L[i] < L[suffixSt]:
L[suffixSt], L[i] = L[i], L[suffixSt] # L[suffixSt] is larger than L[i], swap the two. Put the lower value on the left of the list
suffixSt += 1
""" Merge Sort: overall complexity is O(n log n) where n is len(L)
Successively divide a large list into two halves until you have lists of length < 2. These are considered sorted.
Then compare the smallest value of two lists one at a time, and add the smallest value to the end of a new sublist. This is the merging part.
If a sublist is empty while comparing, add the remaining values from the other sublist to the result.
Then merge your new, but longer, sublists in the same way as above.
Repeat until you have a final sorted list. This essentially contains all of the merged, sorted sublists."""
# complexity O(log n), n is len(L)
def mergeSort(L):
if len(L) < 2: # base case, list of length < 2 is considered sorted
return L[:]
else:
middle = len(L)//2 # integer divide by two
left = mergeSort(L[:middle]) # divide the list and mergeSort again, until len(L) < 2
right = mergeSort(L[middle:]) # divide the list "
return merge(left, right) # requires the next function 'merge, conquer with the merge step
# complexity O(n), n is len(L)
def merge(left, right):
result = []
i, j = 0,0
while i < len(left) and j < len(right): # assumes right and left sublists are already ordered
if left[i] < right[i]:
result.append(left[i])
i += 1 # move indices for sublists depending on which sublist holds the next smallest element
else:
result.append(right[j])
j += 1
while (i < len(left)): # when the right sublist is empty, append the left one to it
result.append(left[i])
i += 1
while (j < len(right[j])):
result.append(right[j]) # when the left sublist is empty, append the right one to it
j += 1
return result |
00a3af0ce1ebf2608eddbc9264cedf965c1d27b7 | MDaalder/MIT6.00.1x_Intro_CompSci | /W07_Plotting/primes_list.py | 881 | 4.03125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sun Mar 24 16:48:04 2019
@author: Matt
"""
""" returns a list of prime numbers between 2 and N
inclusive, sorter in increasing order"""
def primes_list(N):
'''
N: an integer
'''
primes = []
rangeNums = []
if N == 2:
primes.append(N)
return primes[:]
for i in range(N-1):
rangeNums.append(i+2)
for num in rangeNums:
for j in range(2,N):
prime = True
# print(num, j)
if num == j:
break
if num%j == 0:
prime = False
break
if prime == True:
primes.append(num)
# print(rangeNums[:])
# print(primes[:])
return primes[:]
print(primes_list(2)) |
77f89966c4fdf45f1d47c2165f85644ceb9f20fa | MDaalder/MIT6.00.1x_Intro_CompSci | /W02_Simple_Programs/Converting int to binary.py | 888 | 4.03125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Feb 5 20:59:49 2019
@author: Matt
"""
# this program converts an integer number into a binary
# if binary 101 = 1*2**2 + 0*2**1 + 1*2**0 = 5
# then, if we take the remainder relative to 2 (x%2) of this number
# that gives us the last binary bit
# if we then divide 5 by 2 (5//2) all the bits get shifted right
# 5//2 = 1*2**1 + 0*2**0 = 10
# keep doing successive divisions; now remainder gets next bit, and so on
# we've converted to binary.
inNum = int(input('Enter an integer to convert to binary: '))
num = inNum
if num < 0:
isNeg = True
num = abs(num)
else:
isNeg = False
result = ''
if num == 0:
result = '0'
while num > 0:
result = str(num%2) + result
num = num//2
if isNeg:
result = '-' + result
print('The binary of your integer ' + str(inNum) + ' is ' + str(result))
|
5e0d0132cee8a9b3aa8f9a417eb8638d3f73ec82 | MDaalder/MIT6.00.1x_Intro_CompSci | /W02_Simple_Programs/polysum.py | 468 | 3.75 | 4 |
"""
@author: Matt
Function calculates the sum of the area and perimeter^2 of a regular polygon to 4 decimal points
A regular polygon has n sides, each with length s
n number of sides
s length of each side
"""
def polysum(n, s):
import math
area = (0.25*n*s**2)/(math.tan(math.pi/n)) # area of the polygon
perim = s*n # perimeter of the polygon
return round((float(area + perim**2)), 4) # returns the answer, to 4 decimal points |
e3b9c70022e232ae228e23a4ff155ae4da19cf69 | MDaalder/MIT6.00.1x_Intro_CompSci | /W04_GoodPractices/8 video example of raise.py | 678 | 3.546875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sat Mar 2 20:37:50 2019
@author: Matt
"""
def get_ratios(L1, L2):
""" assumes L1 and L2 are lists of equal length of numbers
returns a list containing L1[i]/L2[i]"""
ratios = []
for index in range(len(L1)):
try:
ratios.append(L1[index]/float(L2[index]))
except ZeroDivisionError:
ratios.append(float('NaN')) # NaN = not a number
except:
raise ValueError('get_ratios called with bad arg')
return ratios
L1 = [1, 2, 3, 4]
L2 = [5, 6, 7, 8]
#L2 = [5, 6, 7, 0] #test case for div 0
#L2 = [5, 6, 7] # test case for bad argument len L1 != len L2
|
423a48d5272b44e2156d1f0966c70757007233aa | MDaalder/MIT6.00.1x_Intro_CompSci | /Midterm Problem 5.py | 1,991 | 3.75 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sun Feb 24 16:38:25 2019
@author: Matt
"""
def uniqueValues(aDict):
'''
aDict: a dictionary
This function takes in a a dictionary, and returns a list
Keys in aDict map to integer values that are unique (values appear only once in aDict)
List of keys returned should be in increasing order.
If there are no unique values in aDict, the function should return an empy list
. '''
dummyList = []
dummyDict = {}
result = []
intValues = aDict.values() # gets values of dictionary
# keyValues = aDict.keys() # gets keys of dictionary
# print('Values in aDict', intValues)
# print('Keys in aDict', keyValues)
for t in intValues: # this will iterate through values of dictionary, and create key entries of int value k to keep a count of how many times that int comes up
if t in dummyDict: # if the value is already in the dictionary, add 1 to entry count
dummyDict[t] += 1
if t not in dummyDict: # if the value is not already in dict, create an entry
dummyDict[t] = 1
for k in dummyDict: # itereates through all int keys in the new dictionary (which are values in original dictionary)
if dummyDict[k] == 1: # if the value of that key is 1, that int is unique in the dictionary
dummyList.append(k) # add that int value to the list of unique dictionary values
for w in aDict: # iterates through keys in aDict
if aDict[w] in dummyList: # if the value of aDict[key] is in the dummyList of unique dictionary values
result.append(w) # record that aDict key to a list to be sorted and printed
result.sort()
return result
#aDict = {'a':1, 'b': 2, 'c': 4, 'd': 0, 'e': 3, 'f': 2}
# answer [0, 1, 3, 4]
#aDict = {1:1, 2: 2, 8: 4, 0: 0, 5: 3, 3: 2}
# answer [4, 5, 8]
aDict = {2: 0, 3: 3, 6: 1}
#answer [2, 3, 6]
print(uniqueValues(aDict))
|
81a509d34b1289560e111cfaf2103fe29f327009 | AlymbaevaBegimai/TEST | /2.py | 401 | 4 | 4 |
class Phone:
username = "Kate"
__how_many_times_turned_on = 0
def call(self):
print( "Ring-ring!" )
def __turn_on(self):
self.__how_many_times_turned_on += 1
print( "Times was turned on: ", self.__how_many_times_turned_on )
my_phone = Phone()
my_phone.call()
print( "The username is ", my_phone.username ) |
f8b1dd75c2283fec69c9236c52814a3c7ae31396 | romanzdk/books-recommender | /processing.py | 987 | 3.671875 | 4 | import pandas as pd
df = pd.read_csv('data/out.csv', sep=';')
def get_similar(book_name):
author_books = []
year_books = []
# get all books with the corresponding name
books = (
df[df['title'].str.contains(book_name.lower())]
.sort_values('rating_cnt', ascending = False)
)
if books.shape[0] > 0:
# get books of the same author
author = books.iloc[0,0]
author_books = (
df[df['author'] == author]
.sort_values('rating_avg', ascending = False)[:5]['title']
.to_list()
)
# get books within the year range
year = books.iloc[0,2]
year_range = 5
year_books = (
df[(df['year'] <= (year + year_range)) & (df['year'] >= (year - year_range))]
.sort_values('rating_avg', ascending = False)[:5]['title']
.to_list()
)
return {
'Author books':author_books,
'Year books':year_books
} |
7486bead68a7bf0c2e7d2a4ed289203a278be6b7 | bb-bb/KwantumNum | /task1.py | 1,557 | 3.5 | 4 | """
author: Geert Schulpen
Task 1; random disorder
"""
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.widgets import Slider, Button
import random as random
g_AxColor = "lightgoldenrodyellow"
random.seed(1248)
def disorder(size,scale):
"""
A function that generates a disorder-potential
:param size: how big the matrix has to be
:param scale: how big the disorder has to be
:return: A square array of size size, which contains random entries on the main diagonal
"""
deltaHhatDiagonaal=[]
deltaHhatDiagonaal.append([random.random() for i in range(size)])*scale
deltaHhat=np.diagflat(deltaHhatDiagonaal) #aanmaken extra matrix
return(deltaHhat)
def task1():
gridSize = 400
t=1
box=1
big=1
medium=0.075
small=0.00125
standardHamilton=getHamiltonMatrix(gridSize,t)
deltaHamiltonSmall=disorder(gridSize,small)
deltaHamiltonMedium=disorder(gridSize,medium)
deltaHamiltonBig=disorder(gridSize,big)
valuesSmall,vectorsSmall=calculateEigenstate(standardHamilton+deltaHamiltonSmall, box)
valuesMedium,vectorsMedium=calculateEigenstate(standardHamilton+deltaHamiltonMedium, box)
valuesBig,vectorsBig=calculateEigenstate(standardHamilton+deltaHamiltonBig, box)
plotEigenstate(valuesSmall,vectorsSmall,box,'Task1, small disorder')
plotEigenstate(valuesMedium,vectorsMedium,box,'Task1, medium disorder')
plotEigenstate(valuesBig,vectorsBig,box,'Task1, big disorder')
task1()
|
18e1e68ed464494e6547e83b3c827fb322ddfa89 | Yrshyx/C | /python/第一题.py | 237 | 3.734375 | 4 | counter=0
for i in range(1,5):
for j in range(1,5):
for k in range(1,5):
if i!=j and j!=k and i!=k:
print("{} {} {}".format(i,j,k))
counter +=1
print("共有{}种".format(counter))
|
507fdcb28060f2b139b07853c170974939267b63 | Abhinav-Rajput/CodeWars__KataSolutions | /Python Solutions/Write_ Number_in_Expanded_Form.py | 611 | 4.34375 | 4 | # Write Number in Expanded Form
# You will be given a number and you will need to return it as a string in Expanded Form. For example:
# expanded_form(12) # Should return '10 + 2'
# expanded_form(42) # Should return '40 + 2'
# expanded_form(70304) # Should return '70000 + 300 + 4'
def expanded_form(num):
strNum = str(num)
line = ''
for i in range(0,len(strNum)):
if strNum[i]=='0':
continue
line += strNum[i] + ''
for j in range(0,(len(strNum)-(i+1))):
line += '0'
line += ' + '
line = line[0:len(line)-3]
return line |
41159eb6bd04eeaf5593014c6820fcf7e30b5832 | Abhinav-Rajput/CodeWars__KataSolutions | /Python Solutions/spyGames.py | 437 | 3.5625 | 4 | def decrypt(code):
z = {0: ' '}
sum = 0
res = ''
arr = []
for i in range(1, 27):
z[i] = chr(i + 96)
codes = code.split()
for c in codes:
for a in c:
if a.isdigit():
sum += int(a)
if sum > 26:
sum = sum % 27
arr.append(sum)
sum = 0
for r in arr:
res += z[r]
return res
h = decrypt('x20*6<xY y875_r97L')
print(h)
|
8d6538986282bfbe541fe6e1d4a0b36920072f78 | jgarciagarrido/tuenti_challenge_7 | /challenge_4/solve.py | 758 | 3.84375 | 4 | def is_triangle(a, b, c):
return (a + b > c) and (b + c > a) and (a + c > b)
def perimeter(triangle):
return triangle[0] + triangle[1] + triangle[2]
def min_perimeter_triangle(n, sides):
sides.sort()
triangle = None
for i in xrange(1, n-1):
b = sides[i]
c = sides[i+1]
for j in xrange(0, i):
a = sides[j]
if is_triangle(a, b, c):
return perimeter((a, b, c))
return "IMPOSSIBLE"
if __name__ == '__main__':
t = int(raw_input())
for i in xrange(1, t + 1):
sides_line = [int(s) for s in raw_input().split(" ")]
n_sides = sides_line[0]
sides = sides_line[1:]
print "Case #{}: {}".format(i, min_perimeter_triangle(n_sides, sides))
|
6e71a0d9e1518351d493c96315b76817a7d0e214 | RickLee910/Leetcode_easy | /Array_easy/offer_16.py | 322 | 3.75 | 4 | class Solution:
#动态规划
def maxSubArray1(self, nums):
if nums == []:
return 0
else:
for i in range(1, len(nums)):
nums[i] = max(nums[i] + nums[i - 1], nums[i])
return max(nums)
sol = Solution()
a = [1,-1,-2,3]
print(sol.maxSubArray(a))
|
c6fe56f2f56e95e1c34fb75e533abc0917d46512 | RickLee910/Leetcode_easy | /Hash_easy/leetcode_349.py | 276 | 3.515625 | 4 | from collections import Counter
class Solution:
def intersection(self, nums1, nums2):
temp1 = Counter(nums1)
temp2 = Counter(nums2)
ans = []
for i in temp1.keys():
if temp2[i] >0:
ans.append(i)
return ans |
c8ad40f63b827bb6102c20bb82a510f35cd8a6bc | RickLee910/Leetcode_easy | /Array_easy/leetcode_88.py | 896 | 3.59375 | 4 | class Solution:
def merge(self, nums1, m, nums2, n):
for i in range(len(nums1)-m):
nums1.pop()
for j in range(len(nums2)-n):
nums2.pop()
nums1.extend(nums2)
nums1.sort()
def merge1(self, nums1, m, nums2, n):
temp = {}
temp1 = []
for i,x in enumerate(nums1):
if m == 0:
break
temp[x] = temp.get(x, 0) + 1
if i == m - 1:
break
for j, x in enumerate(nums2):
if n == 0:
break
temp[x] = temp.get(x, 0) + 1
if j == n - 1:
break
nums1.clear()
temp1 = list(temp.keys())
temp1.sort()
for j in temp1:
nums1.extend([j] * temp[j])
nums1 = [3,0,0]
m = 1
nums2 = [2,5,6,0,0]
n = 3
s = Solution()
s.merge(nums1,m,nums2,n)
print(nums1) |
3b2c8b6e23b557a1f8013f8ed9750ea72b72e3f7 | RickLee910/Leetcode_easy | /String_easy/inter_01.09.py | 650 | 3.8125 | 4 | class Solution:
#切片比较
def isFlipedString(self, s1: str, s2: str) -> bool:
if len(s1) != len(s2):
return False
return s1 in (s2 + s2)
#循环判断
def isFlipedString1(self, s1: str, s2: str) -> bool:
if len(s1) != len(s2):
return False
if s1 == '' and s2 == '':
return True
S2 = list(s2)
S1= list(s1)
for i in range(len(s2)):
if S2 == S1:
return True
else:
S2.append(S2.pop(0))
return False
s = Solution()
a = "waterbottl1"
b = "erbottlewat"
print(s.isFlipedString(a,b)) |
2eaa46e63db5e0cdec6028abf86595d8ebf0504d | RickLee910/Leetcode_easy | /Array_easy/inter_17.04.py | 261 | 3.53125 | 4 | import collections
class Solution:
def missingNumber(self, nums):
temp = collections.Counter(nums)
for i in range(len(nums) + 1):
if i not in temp:
return i
s = Solution()
a = [1,2,3,4,5]
print(s.missingNumber(a)) |
c58e8f35f2412cd9caf48ddb1330bf23bd631ee1 | RickLee910/Leetcode_easy | /Array_easy/leetcode_35.py | 626 | 3.703125 | 4 | class Solution:
#二分法
def searchInsert1(self, nums, target):
first, end = 0, len(nums)
while first < end:
mid = (first + end) // 2
if nums[mid] == target:
return mid
elif nums[mid] < target:
first = mid + 1
else:
end = mid
return first
#利用list特性,巧妙计算
def searchInsert(self, nums, target):
for i in nums:
if i >= target:
return nums.index(i)
return len(nums)
a = [1,3,5,6]
sol = Solution()
print(sol.searchInsert(a, 4))
|
b68eff085bc7ac20fa2fb7b462af20e511fdcf29 | satishky18/VM-reservation-system | /28sept2021542PM-vm-inventory.py | 3,796 | 3.78125 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[1]:
class Machine:
"""A sample Employee class"""
def __init__(self, ip, username, password, avalible, owner):
self.ip = ip
self.username = username
self.password = password
self.avalible = avalible
self.owner = owner
# In[13]:
import sqlite3
#from employee import Employee
conn = sqlite3.connect('server.db')
c = conn.cursor()
c.execute("""CREATE TABLE IF NOT EXISTS machine (
ip varchar,
username text,
password text,
avalible boolean,
owner null
)""")
def insert_emp(emp):
with conn:
c.execute("INSERT INTO machine VALUES (:ip, :username, :password, :avalible, :owner)", {'ip': emp.ip, 'username': emp.username, 'password': emp.password, 'avalible': emp.avalible, 'owner': emp.owner})
def get_emps_by_avalible(avalible):
c.execute("SELECT * FROM machine WHERE avalible=:avalible", {'avalible': avalible})
return c.fetchall()
def get_emps_by_ip(ip):
c.execute("SELECT * FROM machine WHERE ip=:ip", {'ip': ip})
return c.fetchall()
def update_pay(ip, avalible, owner):
with conn:
c.execute("""UPDATE machine SET avalible = :avalible, owner = :owner
WHERE ip = :ip""",
{'ip': ip, 'avalible': avalible, 'owner': owner})
#def remove_emp(emp):
# with conn:
# c.execute("DELETE from employees WHERE first = :first AND last = :last",
# {'first': emp.first, 'last': emp.last})
emp_1 = Machine('192.168.1.2', 'satish', 'satish-password', 1, '' )
emp_2 = Machine('192.168.1.3', 'tim', 'tim-password', 1, '' )
emp_3 = Machine('192.168.1.4', 'sera', 'sera-password', 1, '' )
emp_4 = Machine('192.168.1.5', 'dan', 'dan-password', 1, '' )
emp_5 = Machine('192.168.1.6', 'scot', 'scot-password', 1, '' )
if c.execute("SELECT * FROM machine").fetchone():
print("data alrady exixt")
else:
insert_emp(emp_1)
insert_emp(emp_2)
insert_emp(emp_3)
insert_emp(emp_4)
insert_emp(emp_5)
#emps = get_emps_by_avalible('0')
#print(get_emps_by_avalible('0'))
#print(get_emps_by_ip('192.168.1.2'))
#update_pay('192.168.1.2', 0, 'sky')
#remove_emp(emp_1)
emps = get_emps_by_avalible(1)
print(emps)
#conn.close()
# In[12]:
import paramiko
while True:
x = input('''please write "new" for request for new machine or write "return" to return the machine
''')
if x == "new":
emps = get_emps_by_avalible('1')
if len(emps) == 0:
print ("no vm left try after some time.")
else:
i = input('enter your name: ')
j = list(emps[0])
#print(get_emps_by_avalible('0'))
k=emps[0]
print(i + " " + "your machine ip is"+"=" + j[0] + " " + "username is" + "=" + j[1] + " " + "password is" + "=" + j[2] )
update_pay(k[0], 0, i)
elif x == "return":
retip = input('please enter machine ip: ')
try:
emps = get_emps_by_ip(retip)
#emps = list(emps[0])
#print(emps)
except:
print("enter valid ip")
continue
k=emps[0]
update_pay(k[0], 1, '')
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
try:
ssh.connect(emps[0], 22, emps[1], emps[2])
stdin, stdout, stderr = ssh.exec_command('rm -rf /tmp')
lines = stdout.readlines()
print(lines)
except:
print ("Unabele to conenct to the server")
else:
print("plesae provide valid response")
# In[ ]:
i=('192.168.1.2', 'satish', 'satish-password', 1, '')
print(i[0])
# In[ ]:
|
33f746a4c39d26398bed011515bcd32aef4630ab | ottohahn/OHNLP | /splitter/splitter.py | 1,365 | 3.84375 | 4 | #!/usr/bin/env python3
"""
A basic sentence splitter, it takes a text as input and returns an array of
sentences
"""
import re
INITIALS_RE = re.compile(r'([A-z])\.')
def splitter(text):
"""
Basic sentence splitting routine
It doesn't take into account dialog or quoted sentences inside a sentence.
"""
sentences = []
# First step remove newlines
text = text.replace('\n', ' ')
# we remove tabs
text = text.replace('\t', ' ')
# then we replace abbreviations
text = text.replace('Ph.D.', "Ph<prd>D<prd>")
text = text.replace('Mr.', 'Mr<prd>')
text = text.replace('St.', 'Mr<prd>')
text = text.replace('Mrs.', 'Mrs<prd>')
text = text.replace('Ms.', 'Ms<prd>')
text = text.replace('Dr.', 'Dr<prd>')
text = text.replace('Drs.', 'Drs<prd>')
text = text.replace('vs.', 'vs<prd>')
text = text.replace('etc.', 'etc<prd>')
text = text.replace('Inc.', 'Inc<prd>')
text = text.replace('Ltd.', 'Ltd<prd>')
text = text.replace('Jr.', 'Jr<prd>')
text = text.replace('Sr.', 'Sr<prd>')
text = text.replace('Co.', 'Co<prd>')
text = INITIALS_RE.sub('\1<prd>', text)
text = text.replace('.', '.<stop>')
text = text.replace('?', '?<stop>')
text = text.replace('!', '!<stop>')
text = text.replace('<prd>', '.')
sentences = text.split('<stop>')
return sentences
|
a597c668dda0375e97dbe33b4dce6d1cc42a8a69 | kernel-memory-dump/UNDP-AWS-2021 | /16-ec2/test-program.py | 1,984 | 3.6875 | 4 | import program
failed_tests = []
pass_tests = []
def test_max1_handles_same_number_ok():
a = 2
result = program.max1(a, a)
if result == a:
pass_tests.append('test_max1_handles_same_number_ok PASSED')
else:
failed_tests.append(f'test_max1_handles_same_number_ok FAILED: the returned value was not as expected, test expected: {a} but instead got {result}')
def test_max1_handles_different_number_ok():
a = 2
b = 3
result = program.max1(a, b)
if result == b:
pass_tests.append('test_max1_handles_different_number_ok PASSED')
else:
failed_tests.append(f'test_max1_handles_different_number_ok FAILED: the returned value was not as expected, test expected: {b} but instead got {result}')
def test_max1_handles_different_number_first_arg_ok():
a = 0
b = 3
expected = -1
result = program.max1(a, b)
if result == expected:
pass_tests.append('test_max1_handles_different_number_first_arg_ok PASSED')
else:
failed_tests.append(f'test_max1_handles_different_number_first_arg_ok FAILED: the returned value was not as expected, test expected: {expected} but instead got {result}')
def test_max1_handles_different_number_second_arg_ok():
a = 3
b = 0
expected = -1
result = program.max1(a, b)
if result == expected:
pass_tests.append('test_max1_handles_different_number_second_arg_ok PASSED')
else:
failed_tests.append(f'test_max1_handles_different_number_second_arg_ok FAILED: the returned value was not as expected, test expected: {expected} but instead got {result}')
test_max1_handles_same_number_ok()
test_max1_handles_different_number_ok()
test_max1_handles_different_number_first_arg_ok()
test_max1_handles_different_number_second_arg_ok()
# for each
# int i = 0; i < pass_tests.length; i++
# passed_test = pass_tests[i]
#
#
for passed_test in pass_tests:
print(passed_test)
for failed_test in failed_tests:
print(failed_test) |
b8ca7993c15513e13817fa65f892ebd014ca5743 | Satona75/Python_Exercises | /Guessing_Game.py | 816 | 4.40625 | 4 | # Computer generates a random number and the user has to guess it.
# With each wrong guess the computer lets the user know if they are too low or too high
# Once the user guesses the number they win and they have the opportunity to play again
# Random Number generation
from random import randint
carry_on = "y"
while carry_on == "y":
rand_number = randint(1,10)
guess = int(input("Try and guess the number generated between 1 and 10 "))
while guess != rand_number:
if guess < rand_number:
guess = int(input("Sorry too low! Try again.. "))
else:
guess = int(input("Sorry too high! Try again.. "))
print("Congratulations!! You have guessed correctly!")
carry_on = input("Do you want to play again? (y/n).. ")
print("Thanks for playing!") |
12c145181efc2ff5fba7113ad3be5dd4f8941369 | Satona75/Python_Exercises | /multiply_even_numbers.py | 210 | 3.96875 | 4 | def multiply_even_numbers(list):
evens = [num for num in list if num%2 == 0]
holder = 1
for x in evens:
holder = holder * x
return holder
print(multiply_even_numbers([1,2,3,4,5,6,7,8])) |
c069374b1d2c822c9a71b4c7c95ac5e7e3ca945f | Satona75/Python_Exercises | /RPS-AI.py | 1,177 | 4.3125 | 4 | #This game plays Rock, Paper, Scissors against the computer.
print("Rock...")
print("Paper...")
print("Scissors...\n")
#Player is invited to choose first
player=input("Make your move: ").lower()
#Number is randomly generated between 0 and 2
import random
comp_int=random.randint(0, 2)
if comp_int == 0:
computer = "rock"
elif comp_int == 1:
computer = "paper"
else:
computer = "scissors"
print("Computer has chosen: " + computer)
if player == "rock" or player == "paper" or player == "scissors":
if computer == player:
print("It's a tie!")
elif computer == "rock":
if player == "paper":
print("You Win!")
elif player == "scissors":
print("Computer Wins!")
elif computer == "paper":
if player == "scissors":
print("You Win!")
elif player == "rock":
print("Computer Wins!")
elif computer == "scissors":
if player == "rock":
print("You Win!")
elif player == "paper":
print("Computer Wins!")
else:
print("Something has gone wrong!")
else:
print("Please enter either rock, paper or scissors")
|
474ae873c18391c8b7872994da02592b59be369c | Satona75/Python_Exercises | /RPS-AI-refined.py | 1,977 | 4.5 | 4 | #This game plays Rock, Paper, Scissors against the computer
computer_score = 0
player_score = 0
win_score = 2
print("Rock...")
print("Paper...")
print("Scissors...\n")
while computer_score < win_score and player_score < win_score:
print(f"Computer Score: {computer_score}, Your Score: {player_score}")
#Player is invited to choose first
player=input("Make your move: ").lower()
if player == "quit" or player == "q":
break
#Number is randomly generated between 0 and 2
import random
comp_int=random.randint(0, 2)
if comp_int == 0:
computer = "rock"
elif comp_int == 1:
computer = "paper"
else:
computer = "scissors"
print("Computer has chosen: " + computer)
if player == "rock" or player == "paper" or player == "scissors":
if computer == player:
print("It's a tie!")
elif computer == "rock":
if player == "paper":
print("You Win!")
player_score += 1
elif player == "scissors":
print("Computer Wins!")
computer_score += 1
elif computer == "paper":
if player == "scissors":
print("You Win!")
player_score += 1
elif player == "rock":
print("Computer Wins!")
computer_score += 1
elif computer == "scissors":
if player == "rock":
print("You Win!")
player_score += 1
elif player == "paper":
print("Computer Wins!")
computer_score += 1
else:
print("Something has gone wrong!")
else:
print("Please enter either rock, paper or scissors")
if computer_score > player_score:
print("Oh no! The Computer won overall!!")
elif player_score > computer_score:
print("Congratulations!! You won overall")
else:
print("It's a tie overall")
|
44cbdbc57f54a30a0c711991f5d57e93c369acb3 | moon0331/baekjoon_solution | /others/10809.py | 232 | 3.84375 | 4 | import string
word = input()
result = []
for c in string.ascii_lowercase:
result.append(word.find(c))
print(*result)
print(*[input().find(c) for c in string.ascii_lowercase])
# print(*map(input().find,map(chr,range(97,123)))) |
7c2e2524d3de22c2feb4f5551ced1318ca102f87 | moon0331/baekjoon_solution | /programmers/Level 1/약수의 합.py | 120 | 3.53125 | 4 | def solution(n):
return sum(x for x in range(1, n+1) if n%x == 0)
print(solution(12) == 28)
print(solution(5) == 6) |
c2464adf389dca62e0d39b969f16c6c4197f6f20 | moon0331/baekjoon_solution | /programmers/Level 2/[1차] 프렌즈4블록.py | 1,712 | 3.59375 | 4 | def reverse_board(board): # (m,n)
new_board = [line[::-1] for line in list(map(list, zip(*board)))]
return new_board # (n,m)
def search_pop_blocks(m, n, board): # board (m,n) 들어올때 지워야 할 인덱스와 지워지는 블록 수 반환 (reverse될때 확인 필요)
erase_idx = [set() for _ in range(n)]
pop_idx = set()
for i in range(m-1):
for j in range(n-1):
if is_same(board, i, j):
erase_idx[i] |= {j, j+1}
erase_idx[i+1] |= {j, j+1}
pop_idx |= {(i, j), (i, j+1), (i+1, j), (i+1, j+1)}
n_pop_block = len(pop_idx)
return erase_idx, n_pop_block
def is_same(b, i, j):
four_blocks = {b[i][j], b[i+1][j], b[i][j+1], b[i+1][j+1]}
return not 0 in four_blocks and len(four_blocks) == 1
def pop_block(board, erase_idx_by_row, m):
for i, erase_idx in enumerate(erase_idx_by_row):
if not erase_idx:
continue
minval, maxval = min(erase_idx), max(erase_idx)
board[i][minval:maxval+1] = []
board[i] += [0 for _ in range(m-len(board[i]))]
def solution(m, n, board):
answer = 0
board = reverse_board(board)
while True:
erase_idx_by_row, n_pop_block = search_pop_blocks(n, m, board)
if n_pop_block:
answer += n_pop_block
pop_block(board, erase_idx_by_row, m)
continue
break
return answer
ms = [4, 6]
ns = [5, 6]
boards = [
["CCBDE", "AAADE", "AAABF", "CCBBF"],
["TTTANT", "RRFACC", "RRRFCC", "TRRRAA", "TTMMMF", "TMMTTJ"]
]
answers = [14, 15]
for m, n, board, answer in zip(ms, ns, boards, answers):
print(solution(m, n, board) == answer)
# 7번 10번 체크 필요 |
19830dddda2ffb1971d0360f0634d69e1d05754d | moon0331/baekjoon_solution | /programmers/Level 2/문자열 압축.py | 1,281 | 3.5625 | 4 | def get_new_subword_info(word=None):
return {'word':word, 'n_freq':1, 'init':False}
def subword_info_to_string(subword_info):
if subword_info['n_freq'] >= 2:
return str(subword_info['n_freq']) + subword_info['word']
else:
return subword_info['word']
def solution(s):
if len(s) == 1:
return 1
elif len(s)==2 or (len(s) == 3 and len(set(s)) == 1):
return 2
answer = float('inf')
for unit in range(1, len(s)//2+1):
words = [s[i:i+unit] for i in range(0, len(s), unit)]
result_word = ''
subword_info = get_new_subword_info(words[0])
for w in words[1:]:
if subword_info['word'] != w: # new word
result_word += subword_info_to_string(subword_info)
subword_info = get_new_subword_info(w)
else:
subword_info['n_freq'] += 1
result_word += subword_info_to_string(subword_info)
answer = min(answer, len(result_word))
return answer
answer_sheet = [
("aabbaccc", 7),
("ababcdcdababcdcd", 9),
("abcabcdede", 8),
("abcabcabcabcdededededede", 14),
("xababcdcdababcdcd", 17)
]
print(solution('a') == 1)
for x, y in answer_sheet:
print(solution(x) == y) |
83ec2cd0ebe74f598b82553c40dfaa4c3c041a87 | moon0331/baekjoon_solution | /others/8958.py | 149 | 3.5625 | 4 | def nth(x):
x = len(x)
return int(x*(x+1)/2)
N = int(input())
for _ in range(N):
txt = input().split('X')
print(sum(map(nth, txt))) |
95a921ad3f8564b509fdbed54dabeab02b55eaea | moon0331/baekjoon_solution | /programmers/Level 1/정수 제곱근 판별.py | 145 | 3.5 | 4 | def solution(n):
sqrt = n**0.5
return int((sqrt+1)**2) if sqrt == int(sqrt) else -1
print(solution(121) == 144)
print(solution(3) == -1) |
f648b2f6240acb7757aaa42fa3a3adebb3edd9c0 | moon0331/baekjoon_solution | /level2/1259.py | 144 | 3.625 | 4 | while True:
num = input()
if num == '0':
break
print('yes' if all(map(lambda x: x[0]==x[1], zip(num, num[::-1]))) else 'no') |
f566d4798eb7ba166d80406eedbf310cca8f5350 | moon0331/baekjoon_solution | /programmers/Level 1/내적.py | 157 | 3.703125 | 4 | def solution(a, b):
return sum([x*y for x, y in zip(a,b)])
print(solution([1,2,3,4], [-3, -1, 0, 2]) == 3)
print(solution([-1, 0, 1], [1, 0, -1]) == -2) |
f61b06360de5642bc8df6c24371f0c5a2a8b58e1 | moon0331/baekjoon_solution | /programmers/고득점 Kit/전화번호 목록.py | 634 | 3.828125 | 4 | '''
가장 짧은 숫자의 자리수 : n
number[:n] 에서부터 number[:] 까지 hash값 담아버림
'''
def solution(phone_book):
phone_book.sort(key=lambda x:len(x))
print(phone_book)
for i in range(len(phone_book)-1):
subword = phone_book[i]
words_rng = phone_book[i+1:]
for word in words_rng:
if word.startswith(subword):
return False
return True
phones = [
["119", "97674223", "1195524421"],
["123","456","789"],
["12","123","1235","567","88"]
]
returns = [False, True, False]
for p, r in zip(phones, returns):
print(solution(p) == r) |
ce5f9b82b4843c790112e72e2e9555ae29ead8ed | atikus/study1 | /mystudy/generator.py | 364 | 3.796875 | 4 | # bu fonk her yeni çağrılışında baştan başlıyor.
def deneme():
for i in range(5):
yield i*i*i
for j in deneme():
print(j)
for j in deneme():
print(j)
print("= "*40)
# bu bir kere kullanılıyor. ve kendini mem den siliyor.
generator = (x*x*x for x in range(5))
for j in generator:
print(j)
for j in generator:
print(j)
|
096e3e7959be263809b5f5c809e3a2e847771c19 | dkoriadi/query-plans-visualiser | /PlansFrame.py | 3,626 | 3.8125 | 4 | """
PlansFrame.py
This script is called by app.py to display multiple QEPs in tree format.
"""
import tkinter
import tkinter.scrolledtext
import MainFrame
class PlansPage(tkinter.Frame):
"""
This is the class that displays the plans page whereto view all possible QEPs. It is displayed as a
separate frame from the landing page. The QEPs may also be viewed on the CLI for convienience.
Methods
-------
displayPlans(planStrings)
Display all possible QEPs and actual QEP on GUI and CLI
"""
def onFrameConfigure(self, event):
"""
Update the scrollregion of the canvas to allow scrolling on the scrollbar
Parameters
----------
event: Tkinter event (in this case, left-click)
"""
self.canvas.configure(scrollregion=self.canvas.bbox("all"))
def displayPlans(self, planStrings):
# Display QEPs on GUI
self.label_plans.configure(state='normal')
# Remove previous plans
self.label_plans.delete('1.0', tkinter.END)
self.label_plans.insert('end', planStrings + '\n')
self.label_plans.configure(state='disabled')
def __init__(self, tk_parent_frame, tk_root_window, objLandingPage):
"""
Constructor of the PlansPage class
Parameters
----------
tk_parent_frame: tkinter.Frame
The parent Tkinter frame that is on top of the Tkinter window. Every Tkinter window must contain
a widget (the frame in this case) to be able to display UI.
tk_root_window: tkinter.Tk
The Tkinter root window which has one or more Tkinter frames created as objects. Switching the
Tkinter frame is done via the root window.
"""
tkinter.Frame.__init__(self, tk_parent_frame, width=300, height=300)
self.controller = tk_root_window
self.canvas = tkinter.Canvas(self, width=300, height=300)
self.canvas.pack(side=tkinter.LEFT, expand=True, fill=tkinter.BOTH)
self.frame = tkinter.Frame(self.canvas)
# Get the LandingPage object to pass variables
self.objLandingPage = objLandingPage
# Vertical scrollbar
self.yscroll = tkinter.Scrollbar(
self, command=self.canvas.yview, orient=tkinter.VERTICAL)
self.yscroll.pack(side=tkinter.RIGHT, fill=tkinter.Y,
expand=tkinter.FALSE)
self.canvas.configure(yscrollcommand=self.yscroll.set)
self.canvas.create_window((0, 0), window=self.frame, anchor="nw",
tags="self.frame")
# Horizontal scrollbar
self.xscroll = tkinter.Scrollbar(
self.canvas, orient='horizontal', command=self.canvas.xview)
self.xscroll.pack(side=tkinter.BOTTOM, fill=tkinter.X)
# Callback function for scrollbar
self.frame.bind("<Configure>", self.onFrameConfigure)
# Button created to allow user to go back to LandingPage
tkinter.Button(
self.frame, text="Back",
command=lambda: self.controller.showFrame(MainFrame.LandingPage)).grid(row=0, column=0, padx=(10, 0), pady=9)
"""Plans"""
self.label_plans_header = tkinter.Label(
self.canvas, text="Plans:", anchor="w")
self.label_plans_header.config(font=(None, 14))
self.label_plans_header.pack(padx=(10, 0), pady=(15, 0))
self.label_plans = tkinter.scrolledtext.ScrolledText(
self.canvas, wrap='word', state='disabled', width=130, height=100)
self.label_plans.pack(padx=(10, 10), pady=(10, 10))
|
19dbab140d55e0b7f892d66f08b9dc26ba5f4095 | timurridjanovic/javascript_interpreter | /udacity_problems/8.subsets.py | 937 | 4.125 | 4 | # Bonus Practice: Subsets
# This assignment is not graded and we encourage you to experiment. Learning is
# fun!
# Write a procedure that accepts a list as an argument. The procedure should
# print out all of the subsets of that list.
#iterative solution
def listSubsets(list, subsets=[[]]):
if len(list) == 0:
return subsets
element = list.pop()
for i in xrange(len(subsets)):
subsets.append(subsets[i] + [element])
return listSubsets(list, subsets)
print listSubsets([1, 2, 3, 4, 5])
#recursive solution
def sublists(big_list, selected_so_far):
if big_list == []:
print selected_so_far
else:
current_element = big_list[0]
rest_of_big_list = big_list[1:]
sublists(rest_of_big_list, selected_so_far + [current_element])
sublists(rest_of_big_list, selected_so_far)
dinner_guests = ["LM", "ECS", "SBA"]
sublists(dinner_guests, [])
|
d5b4078fc05372736115f67ea8044976fe1ab994 | dundunmao/LeetCode2019 | /680. Valid Palindrome II.py | 672 | 3.765625 | 4 | # 问一个string是不是palindrome,可以最多去掉一个char
class Solution(object):
def validPalindrome(self, s):
"""
:type s: str
:rtype: bool
"""
l = 0
r = len(s)-1
while l < r:
if s[l] != s[r]:
return self.isPanlin(s,l,r-1) or self.isPanlin(s,l+1,r)
l += 1
r -= 1
def isPanlin(self,s,i,j):
while i < j:
if s[i] != s[j]:
return False
else:
i += 1
j -= 1
return True
if __name__ == '__main__':
s = Solution()
a = 'abbb'
print s.validPalindrome(a)
|
71dda13cd5f310acf20845a091a5663b7fbee6f6 | dundunmao/LeetCode2019 | /long_qomolangma.py | 708 | 3.625 | 4 | def qomolangma(array):
start = 0
res = 1
for i in range(len(array)):
if array[i] < array[start]:
res = max(res, i - start + 1)
start = i
if start == len(array) - 1:
return res
new_start = len(array) - 1
for j in range(len(array) - 1, start - 1, -1):
if array[j] < array[new_start]:
res = max(res, new_start - j + 1)
new_start = j
return res
array = [3,7,4,9,2,1,13] # 5
print(qomolangma(array))
array = [1, 99, 104, 400, 22, 15, 33]
print(qomolangma(array)) # 6
array = [1]
print(qomolangma(array)) # 1
array = [1, 2]
print(qomolangma(array)) # 2
array = [1, 2, 3, 4, 5, 6, 7]
print(qomolangma(array)) # 2
|
a0bb6c5c0a352812303e2dd732927dd21d487b6b | dundunmao/LeetCode2019 | /975. Odd Even Jump.py | 3,340 | 3.625 | 4 |
# 最后结果
import bisect
class Solution1:
def oddEvenJumps(self, A):
n = len(A)
odd_jump = [False] * n
even_jump = [False] * n
bst = SortedArray()
# base case
odd_jump[n - 1] = True
even_jump[n - 1] = True
bst.put(A[n - 1], n - 1)
# general case
for i in range(n - 2, -1, -1):
# odd跳的结果 (比它大的里面找最小的)
next_node = bst.find_next(A[i])
odd_jump[i] = next_node[0] != -1 and even_jump[next_node[1]]
# even跳的结果(比它小的里面找最大的)
pre_node = bst.find_prev(A[i])
even_jump[i] = pre_node[0] != -1 and odd_jump[pre_node[1]]
# 把cur加入当前bst
bst.put(A[i], i)
result = 0
# 看每个起点的odd跳的结果
for i in range(0, n):
if odd_jump[i]:
result += 1
return result
class SortedArray:
def __init__(self):
self.array = []
def put(self, val, index):
i = 0
while i < len(self.array):
if val <= self.array[i][0]:
break
i += 1
self.array.insert(i, [val, index])
def find_prev(self, val):
i = 0
while i < len(self.array):
if val <= self.array[i][0]:
if val == self.array[i][0]:
return self.array[i]
i -= 1
break
i += 1
if i == len(self.array):
i -= 1
if i < 0:
return [-1, -1]
while i > 0:
if self.array[i][0] != self.array[i-1][0]:
break
i -= 1
return self.array[i]
def find_next(self, val):
i = 0
while i < len(self.array):
if val <= self.array[i][0]:
if val == self.array[i][0]:
return self.array[i]
break
i += 1
if i > len(self.array) - 1:
return -1, -1
return self.array[i]
############
import bisect
class Solution0:
def oddEvenJumps(self, A):
n = len(A)
odd_jump = [False] * n
even_jump = [False] * n
bst = []
# base case
odd_jump[n - 1] = True
even_jump[n - 1] = True
bisect.insort_right(bst, A[n - 1])
# general case
for i in range(n - 2, -1, -1):
# odd跳的结果 (比它大的里面找最小的)
next_node = bisect.bisect_right(bst, A[i])
odd_jump[i] = next_node != len(bst) and even_jump[next_node]
# even跳的结果(比它小的里面找最大的)
pre_node = bisect.bisect_left(bst, A[i])
even_jump[i] = pre_node != 0 and odd_jump[pre_node]
# 把cur加入当前bst
bisect.insort_left(bst, A[i])
result = 0
# 看每个起点的odd跳的结果
for i in range(0, n):
if odd_jump[i]:
result += 1
return result
s = Solution0()
a = [2,3,1,1,4] # 3
print(s.oddEvenJumps(a))
a = [10,13,12,14,15] # 2
print(s.oddEvenJumps(a))
a = [5,1,3,4,2] # 3
print(s.oddEvenJumps(a))
a = [1,2,3,2,1,4,4,5] # 6
print(s.oddEvenJumps(a))
a = [5,1,3,4,2] #3
print(s.oddEvenJumps(a))
|
91fdacb3c856743643ffced2e2963efbb77224da | dundunmao/LeetCode2019 | /426. Convert BST to Sorted Doubly Linked List.py | 4,401 | 3.9375 | 4 | """
# Definition for a Node.
class Node(object):
def __init__(self, val, left, right):
self.val = val
self.left = left
self.right = right
"""
class Solution(object):
def treeToDoublyList(self, root):
"""
:type root: Node
:rtype: Node
"""
if not root: return None
head, tail = self.helper(root)
return head
def helper(self, root):
'''construct a doubly-linked list, return the head and tail'''
head, tail = root, root
if root.left:
left_head, left_tail = self.helper(root.left)
left_tail.right = root
root.left = left_tail
head = left_head
if root.right:
right_head, right_tail = self.helper(root.right)
right_head.left = root
root.right = right_head
tail = right_tail
head.left = tail
tail.right = head
return head, tail
###################################
class Node:
def __init__(self, val):
self.val = val
self.left = None # pre
self.right = None # next
class Solution:
def treeToDoublyList(self, root: 'Node') -> 'Node':
if not root:
return None
res = self.dfs(root)
res.head.left = res.tail
res.tail.right = res.head
return res.head
def dfs(self, root):
# base case
if not root.left and not root.right:
res = NodeWrapper(root, root)
return res
# general case
if root.left:
left_wrapper = self.dfs(root.left)
left_wrapper.tail.right = root
root.left = left_wrapper.tail
else:
left_wrapper = NodeWrapper(None, None)
if root.right:
right_wrapper = self.dfs(root.right)
right_wrapper.head.left = root
root.right = right_wrapper.head
else:
right_wrapper = NodeWrapper(None, None)
head = left_wrapper.head if left_wrapper.head else root
tail = right_wrapper.tail if right_wrapper.tail else root
return NodeWrapper(head, tail)
class NodeWrapper:
def __init__(self, head, tail):
self.head = head
self.tail = tail
######简化base case
class Solution:
def treeToDoublyList(self, root: 'Node') -> 'Node':
if not root:
return None
res = self.dfs(root)
res.head.left = res.tail
res.tail.right = res.head
return res.head
def dfs(self, root):
# base case
if not root:
return NodeWrapper(None, None)
# general case
left_wrapper = self.dfs(root.left)
right_wrapper = self.dfs(root.right)
if left_wrapper.tail:
left_wrapper.tail.right = root
root.left = left_wrapper.tail
if right_wrapper.head:
right_wrapper.head.left = root
root.right = right_wrapper.head
head = left_wrapper.head if left_wrapper.head else root
tail = right_wrapper.tail if right_wrapper.tail else root
return NodeWrapper(head, tail)
class NodeWrapper:
def __init__(self, head, tail):
self.head = head
self.tail = tail
#######
class Solution:
def treeToDoublyList(self, root):
if root is None:
return None
wrapper = NodeWrapper(None, None)
self.dfs(root, wrapper)
wrapper.head.left = wrapper.tail
wrapper.tail.right = wrapper.head
return wrapper.head
def dfs(self, node, wrapper):
if node is None:
return
self.dfs(node.left, wrapper)
if wrapper.head is None:
wrapper.head = node
else:
wrapper.tail.right = node
node.left = wrapper.tail
wrapper.tail = node
self.dfs(node.right, wrapper)
class NodeWrapper:
def __init__(self, head, tail):
self.head = head
self.tail = tail
if __name__ == '__main__':
P = Node(4)
P.left = Node(2)
P.left.left = Node(1)
P.left.right = Node(3)
# P.left.right.left = TreeNode(6)
# P.left.right.right = TreeNode(7)
# P.left.right.right.right = TreeNode(8)
P.right = Node(5)
# P.right.left = TreeNode(6)
# P.right.right = TreeNode(6)
s = Solution1()
print(s.treeToDoublyList(P))
|
25f1ecffe70394a7cbaa66761d07d4f343301ab1 | dundunmao/LeetCode2019 | /1094. Car Pooling.py | 928 | 3.546875 | 4 | class Solution:
def carPooling(self, trips: List[List[int]], capacity: int) -> bool:
capacity_array = []
for trip in trips:
capacity_array.append(SeatCapacity(trip[0], trip[1], 1))
capacity_array.append(SeatCapacity(trip[0], trip[2], -1))
capacity_array.sort()
res = 0
seat = 0
for seat_cap in capacity_array:
if seat_cap.state == -1:
seat -= seat_cap.num
elif seat_cap.state == 1:
seat += seat_cap.num
res = max(res, seat)
return res <= capacity
class SeatCapacity:
def __init__(self, num, time, state):
self.num = num
self.time = time
self.state = state
def __le__(a, b):
if a.time == b.time:
return a.state < b.state
return a.time < b.time
s = Solution()
a = [[2,1,5],[3,3,7]]
b = 4
print(s.carPooling(a, b))
|
234a66bc28e80b148b555449f8a8c581e06c9854 | dundunmao/LeetCode2019 | /139. word break.py | 8,985 | 3.5625 | 4 |
# 给出一个字符串s和一个词典,判断字符串s是否可以被空格切分成一个或多个出现在字典中的单词。
#
# 您在真实的面试中是否遇到过这个题? Yes
# 样例
# 给出
#
# s = "lintcode"
#
# dict = ["lint","code"]
#
# 返回 true 因为"lintcode"可以被空格切分成"lint code"
class Solution:
# @param s: A string s
# @param dict: A dictionary of words dict
def wordBreak(self, s, dict):
# write your code here
if len(dict) == 0 and len(s) == 0:
return True
if s is None or len(s) == 0 or len(dict) == 0:
return False
can = [False for i in range(len(s)+1)]
can[0] = True
max_len = max(dict)
for i in range(1,len(s)+1):
for j in range(1,min(i,max_len)+1):
if not can[i - j]:
continue
word = s[(i-j):i]
if word in dict:
can[i] = True
break
return can[len(s)]
# time limit exceed
class Solution1:
# @param s: A string s
# @param dict: A dictionary of words dict
def wordBreak(self, s, dict):
if len(dict) == 0 and len(s) == 0:
return True
if s is None or len(s) == 0 or len(dict) == 0 :
return False
n = len(s)
f = [False for i in range(n)]
for k in range(n):
word = s[0:k+1]
if word in dict:
f[k] = True
for i in range(1,n):
for j in range(0,i):
word = s[j+1:i+1]
if word in dict and f[j]:
f[i] = True
return f[n-1]
#尽量优化版,仍超时;第一个不超时的办法,是j从后往前遍历
class Solution3:
# @param s: A string s
# @param dict: A dictionary of words dict
def wordBreak(self, s, dict):
if len(dict) == 0 and len(s) == 0:
return True
if s is None or len(s) == 0 or len(dict) == 0:
return False
n = len(s)
max_len = max([len(word) for word in dict])
f = [False for i in range(n)]
for k in range(n):
word = s[0:k + 1]
if word in dict:
f[k] = True
for i in range(1, n):
for j in range(0, i):
if f[j]:
word = s[j + 1:i + 1]
if len(word) <= max_len:
if word in dict:
f[i] = True
break
############
class Solution(object):
def wordBreak(self, s, wordDict):
"""
:type s: str
:type wordDict: List[str]
:rtype: bool
"""
dictionary_set = set(wordDict)
res = [False for i in range(len(s))]
for i in range(len(s)):
if s[0: i + 1] in dictionary_set:
res[i] = True
continue
for j in range(0, i):
if res[j] and s[j + 1: i + 1] in dictionary_set:
res[i] = True
break
else:
res[i] = False
return res[len(s) - 1]
class Solution3:
def wordBreak(self, s: str, wordDict) -> bool:
dictionary_set = set(wordDict)
result = [None for i in range(len(s))]
return self.dfs(s, len(s) - 1, dictionary_set, result)
def dfs(self, s, i, dictionary_set, result):
if result[i] is not None:
return result[i]
if s[0: i + 1] in dictionary_set:
result[i] = True
return True
for p in range(0, i):
if self.dfs(s, p, dictionary_set, result) and s[p + 1: i + 1] in dictionary_set:
result[i] = True
return True
result[i] = False
return False
class Solution3:
def wordBreak(self, s: str, wordDict) -> bool:
dictionary_set = set(wordDict)
result = [None for i in range(len(s))]
return self.dfs(s, 0, dictionary_set, result)
def dfs(self, s, i, dictionary_set, result):
if result[i] is not None:
return result[i]
if s[i: len(s)] in dictionary_set:
result[i] = True
return True
for p in range(i + 1, len(s)):
if self.dfs(s, p, dictionary_set, result) and s[i: p] in dictionary_set:
result[i] = True
return True
result[i] = False
return False
class Solution3:
def wordBreak(self, s: str, wordDict) -> bool:
n = len(s)
dictionary_set = set(wordDict)
res = [False for i in range(n + 1)]
# base case
res[n] = True
# general case
for i in range(n - 1, -1, -1):
# a[i~n-1] 刚好在dictionary里
if s[i : n] in dictionary_set:
res[i] = True
# a[i~j-1]在dictionary里面,且a[j~n-1]可以break
for j in range(i + 1, n):
if res[j] and s[i : j] in dictionary_set:
res[i] = True
return res[0]
######trie
class Solution:
def wordBreak(self, s: str, wordDict):
n = len(s)
trie_word = Trie()
for word in wordDict:
trie_word.insert(word)
res = [False for i in range(n + 1)]
# base case
res[n] = True
# general case
for i in range(n - 1, -1, -1):
# a[i~n-1] 刚好在dictionary里
if trie_word.search(s[i: n]) == 1:
res[i] = True
continue
# a[i~j-1]在dictionary里面,且a[j~n-1]可以break
for j in range(i + 1, n):
if res[j]:
result = trie_word.search(s[i: j])
if result == False:
res[i] = False
break
elif result == True:
res[i] = True
break
return res[0]
# class Trie:
#
# def __init__(self):
# """
# Initialize your data structure here.
# """
# self.root = TrieNode()
#
# def insert(self, word: str) -> None:
# """
# Inserts a word into the trie.
# """
# cur_root = self.root
# for char in word:
# index = ord(char) - 97
# if cur_root.children[index] == None:
# cur_root.children[index] = TrieNode()
# cur_root = cur_root.children[index]
# cur_root.is_word = True
#
# def search(self, prefix: str) -> bool:
# """
# Returns if there is any word in the trie that starts with the given prefix.
# """
# cur_root = self.root
# for char in prefix:
# index = ord(char) - 97
# if cur_root.children[index] == None:
# return False
# cur_root = cur_root.children[index]
# if cur_root.is_word == True:
# return True
# return None
#
#
# class TrieNode:
# def __init__(self):
# self.children = [None] * 26
# self.is_word = False
######用trie的最优解
class Solution:
def wordBreak(self, s: str, wordDict: List[str]) -> bool:
n = len(s)
trie_word = Trie()
for word in wordDict:
trie_word.insert(word)
res = [False for i in range(len(s))]
for i in range(len(s)):
cur_root = trie_word.root
flag = True
for j in range(i, -1, -1):
index = ord(s[j]) - 97
if cur_root.children[index] is None:
flag = False
break
cur_root = cur_root.children[index]
if cur_root.is_word and res[j-1]:
res[i] = True
break
if cur_root.is_word and flag:
res[i] = True
return res[len(s) - 1]
class Trie:
def __init__(self):
"""
Initialize your data structure here.
"""
self.root = TrieNode()
def insert(self, word: str) -> None:
"""
Inserts a word into the trie.
"""
cur_root = self.root
reverse_word = list(word)[::-1]
for char in reverse_word:
index = ord(char) - 97
if cur_root.children[index] == None:
cur_root.children[index] = TrieNode()
cur_root = cur_root.children[index]
cur_root.is_word = True
class TrieNode:
def __init__(self):
self.children = [None] * 26
self.is_word = False
if __name__ == "__main__":
x = Solution10()
s = "leetcode"
dict = ["leet","code"]
print(x.wordBreak(s, dict)) #T
s = 'applepenapple'
dict = ["apple", "pen"]
print(x.wordBreak(s, dict)) #T
s = 'catsandog'
dict = ["cats", "dog", "sand", "and", "cat"]
print(x.wordBreak(s, dict)) #F
|
a935afab319838c30d5e68573bae93e95da04ae2 | dundunmao/LeetCode2019 | /587. Erect the Fence.py | 1,263 | 3.515625 | 4 | class Solution:
def outerTrees(self, points):
point_array = []
for p in points:
point = Point(p[0], p[1])
point_array.append(point)
point_array.sort()
point_stack = []
for i in range(len(point_array)):
while len(point_stack) >= 2 and self.orientation(point_stack[-2], point_stack[-1], point_array[i]) > 0:
point_stack.pop()
point_stack.append(point_array[i])
for i in range(len(point_array) - 1, -1, -1):
while len(point_stack) >= 2 and self.orientation(point_stack[-2], point_stack[-1], point_array[i]) > 0:
point_stack.pop()
point_stack.append(point_array[i])
res = set()
for ele in point_stack:
res.add((ele.x, ele.y))
return res
def orientation(self, p, q, r):
return (q.y - p.y) * (r.x - p.x) - (q.x - p.x) * (r.y - p.y)
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def __lt__(a, b): # 按x的从小到大排,如果相等,按y的从大到小
if a.x == b.x:
return b.y < a.y
return a.x < b.x
x = Solution()
p = [[1,1],[2,2],[2,0],[2,4],[3,3],[4,2]]
print(x.outerTrees(p))
|
cdfacc797df7c4d29f48907b1719e1a36522d1d9 | dundunmao/LeetCode2019 | /703. Kth Largest Element in a Stream.py | 1,008 | 3.8125 | 4 | import heapq
class KthLargest:
def __init__(self, k, nums):
self.top_k_min_heap = []
self.size = k
i = 0
while i < len(nums) and k > 0:
heapq.heappush(self.top_k_min_heap, nums[i])
i += 1
k -= 1
while i < len(nums):
if self.top_k_min_heap[0] < nums[i]:
heapq.heappop(self.top_k_min_heap)
heapq.heappush(self.top_k_min_heap, nums[i])
i += 1
def add(self, val: int) -> int:
if len(self.top_k_min_heap) < self.size:
heapq.heappush(self.top_k_min_heap, val)
elif self.top_k_min_heap[0] < val:
heapq.heappop(self.top_k_min_heap)
heapq.heappush(self.top_k_min_heap, val)
return self.top_k_min_heap[0]
# Your KthLargest object will be instantiated and called as such:
k = 3
nums = [5, -1]
obj = KthLargest(k, nums)
print(obj.add(2))
print(obj.add(1))
print(obj.add(-1))
print(obj.add(3))
print(obj.add(4))
|
dba0a491be622d41f73dd8c8b1294e2e2d0ad2fd | dundunmao/LeetCode2019 | /138 Copy List with Random Pointer .py | 4,754 | 3.625 | 4 |
class RandomListNode:
def __init__(self, x):
self.label = x
self.next = None
self.random = None
class Solution:
# @param head: A RandomListNode
# @return: A RandomListNode
def copyRandomList(self, head):
# write your code here
if head is None:
return None
dummy = RandomListNode(0)
pre = dummy
# pre = newnNode
map = {}
while head is not None:
if map.has_key(head):
newNode = map.get(head)
else:
newNode = RandomListNode(head.label)
map[head] = newNode
pre.next = newNode
if head.random is not None: #这里别忘了
if map.has_key(head.random):
newNode.random = map.get(head.random)
else:
newNode.random = RandomListNode(head.random.label)
map[head.random] = newNode.random
pre = pre.next #这里别忘了.
head = head.next
return dummy.next
# 方法二,基本同上,但是先循环得到next,再循环一边得到random
class Solution(object):
def copyRandomList(self, head):
"""
:type head: RandomListNode
:rtype: RandomListNode
"""
if head is None:
return head
nHead = RandomListNode(head.label)
old = head
new = nHead
hash = {}
hash[head] = nHead
while old.next != None:
old = old.next
new.next = RandomListNode(old.label)
new = new.next
hash[old] = new
old = head
new = nHead
while old != None:
if old.random != None:
new.random = hash[old.random]
old = old.next
new = new.next
return nHead
# 方法3: 先loop一遍,在每一个点后都复制一边这个node 1->1'->2->2'->3->3'->N这时候random都带上
# 再loop一遍,提取每一个新点和起箭头.
class Solution2:
# @param head: A RandomListNode
# @return: A RandomListNode
def copyRandomList(self, head):
# write your code here
if head is None:
return None
self.copyNext(head)
self.copyRandom(head)
return self.splitList(head)
def splitList(self, head):
newHead = head.next
while head is not None:
temp = head.next
head.next = temp.next
head = head.next
if temp.next is not None:
temp.next = temp.next.next
return newHead
def copyRandom(self, head):
while head is not None:
if head.next.random is not None:
head.next.random = head.random.next
head = head.next.next
def copyNext(self, head):
while head is not None:
newNode = RandomListNode(head.label)
newNode.random = head.random
newNode.next = head.next
head.next = newNode
head = head.next.next
class Node:
def __init__(self, x, next, random):
self.val = x
self.next = next
self.random = random
class Solution:
def copyRandomList(self, head: 'Node') -> 'Node':
if not head:
return None
self.copy_node(head)
self.copy_random(head)
res = self.split(head)
return res
def copy_node(self, head):
old = head
while old:
new = Node(old.val, None, None)
new.next = old.next
old.next = new
old = new.next
def copy_random(self, head):
cur = head
while cur and cur.next:
if cur.random:
cur.next.random = cur.random.next
cur = cur.next.next
def split(self, head):
dummy = Node(-1, None, None)
dummy.next = head
cur = dummy
while head and head.next:
cur.next = head.next
cur = cur.next
head.next = cur.next
head = head.next
return dummy.next
if __name__ == '__main__':
# P = RandomListNode(1)
# P.next = RandomListNode(2)
# P.next.next = RandomListNode(3)
# P.next.next.next = RandomListNode(4)
# P.random = P
# P.next.random = P.next.next
# P.next.next.random = P.next
# P.next.next.next.random = None
#
#
# s = Solution4()
# print(s.copyRandomList(P))
P = Node(1, None, None)
P.next = Node(2, None, None)
# P.next.next = RandomListNode(3)
# P.next.next.next = RandomListNode(4)
P.random = P.next
P.next.random = P.next
s = Solution4()
print(s.copyRandomList(P))
|
04cd7500781232849379a93fe63a29a96daaf347 | dundunmao/LeetCode2019 | /212. Word Search II.py | 5,797 | 3.984375 | 4 | # class TrieNode:
# def __init__(self):
# self.flag = False
# self.s = ''
# self.sons = []
# for i in range(26):
# self.sons.append(None)
#
#
# class Trie:
# def __init__(self):
# self.root = TrieNode()
# def insert(self, word):
# # Write your code here
# cur = self.root
# for i in range(len(word)):
# c = ord(word[i]) - ord('a')
# if cur.sons[c] is None:
# cur.sons[c] = TrieNode()
# cur = cur.sons[c]
# cur.s = word
# cur.flag = True
#
# # @param {string} word
# # @return {boolean}
# # Returns if the word is in the trie.
# def search(self, word):
# # Write your code here
# cur = self.root
# for i in range(len(word)):
# c = ord(word[i]) - ord('a')
# if cur.sons[c] is None:
# return False
# cur = cur.sons[c]
# return cur.flag
#
# class Solution:
# # @param board, a list of lists of 1 length string
# # @param words: A list of string
# # @return: A list of string
# def wordSearchII(self, board, words):
# result = []
# tree = Trie()
# for word in words:
# tree.insert(word)
# res = ''
# for i in range(len(board)):
# for j in range(len(board[i])):
# self.help(board,i,j,tree.root,result,res)
# return result
# def help(self,board,x,y,root,result,res):
# dx = [1, 0, -1, 0]
# dy = [0, 1, 0, -1]
# if root.flag is True:
# if root.s not in result:
# result.append(root.s)
# if x < 0 or x >= len(board) or y < 0 or y >= len(board[0]) or board[x][y]==0 or root is None:
# return
# if root.sons[ord(board[x][y]) - ord('a')]:
# for i in range(4):
# cur = board[x][y]
# board[x][y] = False
# self.help(board, x+dx[i], y+dy[i],root.sons[ord(cur) - ord('a')], result, res)
# board[x][y] = cur
################################
# 停在叶子
class Solution:
def findWords(self, board, words):
word_trie = Trie()
for word in words:
word_trie.insert(word)
res = set()
path = []
n = len(board)
m = len(board[0])
direction = [(-1, 0), (1, 0), (0, -1), (0, 1)]
visited = [[False for i in range(len(board[0]))] for j in range(len(board))]
for i in range(n):
for j in range(m):
cur = word_trie.root
char = board[i][j]
if cur.children[ord(char) - 97]:
self.dfs(cur, i, j, path, res, board, direction, visited)
return res
def dfs(self, node, row, col, path, res, board, direction, visited):
path.append(board[row][col])
char = board[row][col]
visited[row][col] = True
cur = node.children[ord(char) - 97]
if cur.is_word:
res.add(''.join(path))
for i, j in direction:
if 0 <= row + i < len(board) and 0 <= col + j < len(board[0]) and cur.children[ord(board[row + i][col + j]) - 97] and visited[row][col]:
self.dfs(cur, row + i, col + j, path, res, board, direction, visited)
path.pop()
visited[row][col] = False
#停在None
class Solution3:
def findWords(self, board, words):
word_trie = Trie()
for word in words:
word_trie.insert(word)
res = set()
path = []
n = len(board)
m = len(board[0])
direction = [(-1, 0), (1, 0), (0, -1), (0, 1)]
visited = [[False for i in range(len(board[0]))] for j in range(len(board))]
for i in range(n):
for j in range(m):
cur = word_trie.root
char = board[i][j]
self.dfs(cur, i, j, path, res, board, direction, visited)
return res
def dfs(self, node, row, col, path, res, board, direction, visited):
if row in [-1, len(board)] or col in [-1, len(board[0])] or node.children[ord(board[row][col]) - 97] is None or visited[row][col]:
return
path.append(board[row][col])
visited[row][col] = True
cur = node.children[ord(board[row][col]) - 97]
if cur.is_word:
res.add(''.join(path))
for i, j in direction:
self.dfs(cur, row + i, col + j, path, res, board, direction, visited)
path.pop()
visited[row][col] = False
class Trie:
def __init__(self):
self.root = TrieNode()
def insert(self, word: str) -> None:
cur_root = self.root
for char in word:
index = ord(char) - 97
if cur_root.children[index] is None:
cur_root.children[index] = TrieNode()
cur_root = cur_root.children[index]
cur_root.is_word = True
class TrieNode:
def __init__(self):
self.children = [None] * 26
self.is_word = False
if __name__ == '__main__':
s = Solution3()
board = [
['d','o','a','f'],
['a','g','a','i'],
['d','c','a','n']
]
words =["dog", "dad", "dgdg", "can", "again"]
print(s.findWords(board, words))
board = [
['o', 'a', 'a', 'n'],
['e', 't', 'a', 'e'],
['i', 'h', 'k', 'r'],
['i', 'f', 'l', 'v']
]
words = ["oath", "pea", "eat", "rain"]
print(s.findWords(board, words))
Output: ["eat", "oath"]
board = [["a","b"], ["a","b"]]
words = ["ab"]
print(s.findWords(board, words))
board = [["b"], ["a"], ["b"], ["b"], ["a"]]
words = ["baa", "abba", "baab", "aba"]
print(s.findWords(board, words))
|
d51ee8447c2680177bab81e87d626fe4bc567024 | dundunmao/LeetCode2019 | /449. Serialize and Deserialize BST.py | 1,680 | 3.734375 | 4 | # Definition for a binary tree node.
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string.
:type root: TreeNode
:rtype: str
"""
res = self.dfs_serialize(root)
return ','.join(res)
def dfs_serialize(self, root):
if not root:
return []
else:
left = self.dfs_serialize(root.left)
right = self.dfs_serialize(root.right)
return left + right + [str(root.val)]
def deserialize(self, data):
"""Decodes your encoded data to tree.
:type data: str
:rtype: TreeNode
"""
if not data:
return None
data = [int(ele) for ele in data.split(',') if ele]
res = self.dfs_deserialize(data, float('-inf'), float('inf'))
return res
def dfs_deserialize(self, data, lower, upper):
if not data or data[-1] < lower or data[-1] > upper:
return None
val = data.pop()
root = TreeNode(val)
root.right = self.dfs_deserialize(data, val, upper) #右子树值在自己和上一层node之间
root.left = self.dfs_deserialize(data, lower, val) # 左子树值在上一层的node和自己之间
return root
# Your Codec object will be instantiated and called as such:
P = TreeNode(10)
P.left = TreeNode(5)
P.left.left = TreeNode(2)
P.left.right = TreeNode(7)
P.left.right.left = TreeNode(6)
P.right = TreeNode(12)
codec = Codec()
print(codec.serialize(P))
print(codec.deserialize(codec.serialize(P)))
|
c3192e3a235a580209903a4c70ee2b3c39978bde | dundunmao/LeetCode2019 | /124. Binary Tree Maximum Path Sum.py | 9,004 | 3.90625 | 4 | # 给出一棵二叉树,寻找一条路径使其路径和最大,路径可以在任一节点中开始和结束(路径和为两个节点之间所在路径上的节点权值之和)
#
# 您在真实的面试中是否遇到过这个题? Yes
# 样例
# 给出一棵二叉树:
#
# 1
# / \
# 2 3
# 返回 6
class TreeNode:
def __init__(self, val):
self.val = val
self.left, self.right = None, None
# 用resultTyoe这个class
class ResultType(object):
def __init__(self, root2any, any2any):
self.root2any = root2any
self.any2any = any2any
class Solution1:
"""
@param root: The root of binary tree.
@return: An integer
"""
def maxPathSum(self, root):
# write your code here
result = self.helper(root)
return result.any2any
def helper(self, root):
if root is None:
return ResultType(float('-inf'), float('-inf'))
# Divide
left = self.helper(root.left)
right = self.helper(root.right)
# Conquer
root2any = max(0,max(left.root2any, right.root2any)) + root.val
any2any = max(left.any2any, right.any2any)
any2any = max(any2any,
max(0,left.root2any) +
max(0,right.root2any) +
root.val)
return ResultType(root2any, any2any)
# 不用resultTyoe这个class,这个方法最好
class Solution2(object):
def maxPathSum(self, root):
"""
:type root: TreeNode
:rtype: int
"""
any_any, root_any = self.helper(root)
return any_any
def helper(self, root):
if root is None:
return float('-inf'), float('-inf')
left_any_any, left_root_any = self.helper(root.left)
right_any_any, right_root_any = self.helper(root.right)
root_any = root.val + max(0, left_root_any, right_root_any)
any_any = max(left_any_any, right_any_any, root_any, root.val + left_root_any + right_root_any)
return any_any, root_any
class Solution:
"""
@param root: The root of binary tree.
@return: An integer
"""
def maxPathSum(self, root):
if not root:
return 0
ans = [float('-inf')] #在这里更新global的最大path-sum
self.helper(root,ans) #表现从root出发的最大path—sum(root-any)
return ans[0]
def helper(self,root,ans):
if not root:
return 0
l = max(0, self.helper(root.left, ans)) #左子树的root-any
r = max(0, self.helper(root.right, ans)) #右子树的root-any
sum = l + r + root.val #root这棵树的global的any-any
ans[0] = max(ans[0], sum) #更新
return max(l,r) + root.val #返回的是 root-any
#################################################3
# 2019 rockey
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def maxPathSum(self, root: TreeNode) -> int:
if not root:
raise ValueError('not valid input')
return self.dfs(root).max_sum
def dfs(self, root):
# base case
if not root.left and not root.right:
return Result(root.val, root.val)
# general case
res_left = Result(float('-inf'), float('-inf')) if not root.left else self.dfs(root.left)
res_right = Result(float('-inf'), float('-inf')) if not root.right else self.dfs(root.right)
max_sum = max(res_left.max_sum,
res_right.max_sum,
max(0, res_left.max_sum_to_root) + max(0, res_right.max_sum_to_root) + root.val
)
max_sum_to_root = max(root.val,
res_left.max_sum_to_root + root.val,
res_right.max_sum_to_root + root.val
)
return Result(max_sum, max_sum_to_root)
class Result:
def __init__(self, max_sum, max_sum_to_root):
self.max_sum = max_sum
self.max_sum_to_root = max_sum_to_root
#################################################3
class Solution:
def maxPathSum(self, root: TreeNode) -> int:
if not root:
raise ValueError('not valid input')
return self.dfs(root).max_sum
def dfs(self, root):
# base case
if not root:
return Result(float('-inf'), float('-inf'))
# general case
res_left = self.dfs(root.left)
res_right = self.dfs(root.right)
max_sum = max(res_left.max_sum,
res_right.max_sum,
max(0, res_left.max_sum_to_root) + max(0, res_right.max_sum_to_root) + root.val
)
max_sum_to_root = max(root.val,
res_left.max_sum_to_root + root.val,
res_right.max_sum_to_root + root.val
)
return Result(max_sum, max_sum_to_root)
class Result:
def __init__(self, max_sum, max_sum_to_root):
self.max_sum = max_sum
self.max_sum_to_root = max_sum_to_root
#################################################3
# 16 个分支
import random
class MyTreeNode:
def __init__(self, val):
self.val = val
self.children = [None] * 16
class Result:
def __init__(self, max_sum, max_sum_to_root):
self.max_sum = max_sum
self.max_sum_to_root = max_sum_to_root
class Solution:
def maxPathSum(self, root: TreeNode) -> int:
if not root:
raise ValueError('not valid input')
new_root = self.copy_tree(root)
return self.dfs(new_root).max_sum
def dfs(self, root):
# base case
if not root:
return Result(float('-inf'), float('-inf'))
# general case
max_sum_without_root = float('-inf')
biggest_sum_to_child = float('-inf')
bigger_sum_to_child = biggest_sum_to_child
for ele in root.children:
ele_res = self.dfs(ele)
max_sum_without_root = max(max_sum_without_root, ele_res.max_sum)
if ele_res.max_sum_to_root > biggest_sum_to_child:
bigger_sum_to_child = biggest_sum_to_child
biggest_sum_to_child = ele_res.max_sum_to_root
elif ele_res.max_sum_to_root > bigger_sum_to_child:
bigger_sum_to_child = ele_res.max_sum_to_root
total_max_sum = max(max_sum_without_root,
max(0, biggest_sum_to_child) + max(0, bigger_sum_to_child) + root.val
)
total_max_sum_to_root = max(root.val, biggest_sum_to_child + root.val)
return Result(total_max_sum, total_max_sum_to_root)
def copy_tree(self, root):
if not root:
return None
my_root = MyTreeNode(root.val)
my_root.children[random.randint(0, 7)] = self.copy_tree(root.left)
my_root.children[random.randint(0, 7) + 8] = self.copy_tree(root.right)
return my_root
################
# 16分支
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
import random
class MyTreeNode:
def __init__(self, val):
self.val = val
self.children = [None] * 16
class Result:
def __init__(self, max_profit, max_profit_without_root):
self.max_profit = max_profit
self.max_profit_without_root = max_profit_without_root
class Solution:
def rob(self, root: TreeNode) -> int:
if not root:
return 0
new_root = self.copy_tree(root)
return self.dfs(new_root).max_profit
def dfs(self, root):
# base case
if not root:
return Result(0, 0)
# general case
child_max_profit_without_root_sum = 0
child_max_profit_sum = 0
for child in root.children:
child_res = self.dfs(child)
child_max_profit_without_root_sum += child_res.max_profit_without_root
child_max_profit_sum += child_res.max_profit
max_profit = max(child_max_profit_sum, root.val + child_max_profit_without_root_sum)
max_profit_without_root = child_max_profit_sum
return Result(max_profit, max_profit_without_root)
def copy_tree(self, root):
if not root:
return None
my_root = MyTreeNode(root.val)
my_root.children[random.randint(0, 7)] = self.copy_tree(root.left)
my_root.children[random.randint(0, 7) + 8] = self.copy_tree(root.right)
return my_root
if __name__ == '__main__':
# TREE 1
# Construct the following tree
# 5
# / \
# 3 6
# / \
# 2 4
P = TreeNode(1)
P.left = TreeNode(2)
s = Solution()
print(s.maxPathSum(P))
|
87dd5e40f48b6154f4ad565ae45304307fb13144 | dundunmao/LeetCode2019 | /241. Different Ways to Add Parentheses.py | 1,309 | 4.0625 | 4 | # Given a string of numbers and operators, return all possible results from computing all the different
# possible ways to group numbers and operators. The valid operators are +, - and *.
#
#
# Example 1
# Input: "2-1-1".
#
# ((2-1)-1) = 0
# (2-(1-1)) = 2
# Output: [0, 2]
#
#
# Example 2
# Input: "2*3-4*5"
#
# (2*(3-(4*5))) = -34
# ((2*3)-(4*5)) = -14
# ((2*(3-4))*5) = -10
# (2*((3-4)*5)) = -10
# (((2*3)-4)*5) = 10
# Output: [-34, -14, -10, -10, 10]
#
class Solution(object):
def diffWaysToCompute(self, input):
"""
:type input: str
:rtype: List[int]
"""
return self.dfs(input)
def dfs(self, input):
ans = []
for i in range(len(input)):
if input[i] == '+' or input[i] == '-' or input[i] == '*':
left = self.dfs(input[:i])
right = self.dfs(input[i + 1:])
for ele1 in left:
for ele2 in right:
if input[i] == '+':
ans.append(ele1 + ele2)
elif input[i] == '-':
ans.append(ele1 - ele2)
elif input[i] == '*':
ans.append(ele1 * ele2)
if ans == []:
ans.append(eval(input))
return ans
|
31df3f479fd5b5552b9a1396163008dc38abd9d6 | dundunmao/LeetCode2019 | /69. Sqrt(x).py | 1,323 | 3.859375 | 4 |
class Solution:
"""
@param x: An integer
@return: The sqrt of x
"""
def sqrt(self, x):
start = 1
end = x
while start+1 < end:
mid = start+(end-start)/2
if mid*mid <= x:
start = mid
else:
end = mid
if end*end <=x:
return end
return start
def mySqrt_leet(self, x):
"""
:type x: int
:rtype: int
"""
if x <= 0:
return 0
if x == 1:
return 1
start = 1
end = x
while start + 1 < end:
mid = (start+end)/2
if mid**2 == x:
return mid
elif mid**2 < x:
start = mid
else:
end = mid
return start
class SolutionNew:
def mySqrt(self, x: int) -> int:
if x <= 1:
return x
s = 0
e = x //2
while s + 1 < e:
m = s + (e - s) // 2
if m*m == x:
return m
elif m*m < x:
s = m
else:
e = m
if e * e <= x:
return e
else:
return s
if __name__ == "__main__":
x = 10
s = Solution()
print s.sqrt(x)
|
e7ea9a45373e0021b745e8e19d441139163e36e8 | dundunmao/LeetCode2019 | /1123. Lowest Common Ancestor of Deepest Leaves.py | 1,116 | 3.765625 | 4 | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def lcaDeepestLeaves(self, root: TreeNode) -> TreeNode:
res = Result()
self.dfs(root, 0, res)
return res.lca
# 返回的是当前node的左右子树的深度
def dfs(self, node, depth, res):
# 更新此树最大深度
res.deepest = max(res.deepest, depth)
if not node:
return depth
# 左边的最大深度
left = self.dfs(node.left, depth + 1, res)
# 右边的最大深度
right = self.dfs(node.right, depth + 1, res)
# 如果左右都到了最大深度,lca更新成当前node
# 如到叶子了,左右深度都是这个叶子的深度,都是最大深度,记录这个叶子为lca
# 再上一层,
if left == res.deepest and right == res.deepest:
res.lca = node
return max(left, right)
class Result:
def __init__(self):
self.lca = None
self.deepest = 0
|
910a21d1d3d13cfbaccf71ea77218b06a375d7fb | dundunmao/LeetCode2019 | /test.py | 31,321 | 3.578125 | 4 | # def water_flower(a, capacity):
# res = 0
# left = capacity
# for i in range(len(a)):
# if a[i] > left:
# res += i * 2
# left = capacity - a[i]
# if left < 0:
# return -1
# else:
# left -= a[i]
#
# return res + len(a)
#
# def compare_string1(a, b):
# a_array = a.split(',')
# b_array = b.split(',')
# res = []
# count_b = [] #表示b里每个str的num
# for i in b_array:
# count_b.append(count_min_char(i))
# count_a = [0] * 11 #index表示num,ele表示有几个str是这个num的
# for j in a_array:
# count = count_min_char(j)
# count_a[count] += 1
# #累加,表示有几个str是最少这个num的。
# for i in range(1, len(count_a)):
# count_a[i] = count_a[i] + count_a[i - 1]
# # num表示b里每个str的num,去a里要找比num小一个的num对应多少个str
# for num in count_b:
# res.append(count_a[num - 1])
# return res
#
# def count_min_char(string):
# array = [0] * 26
# for cha in string:
# array[ord(cha) - 97] += 1
# for i in range(len(array)):
# if array[i] > 0:
# return array[i]
#
#
# # 方法2
# def compare_string2(a, b):
# a_array = a.split(',')
# b_array = b.split(',')
# res = []
# for i in b_array:
# count = 0
# for j in a_array:
# if count_char(j, min(j)) < count_char(i, min(i)):
# count += 1
# res.append(count)
# return res
# def count_char(string, char):
# res = 0
# for ele in string:
# if ele == char:
# res += 1
# return res
# a = 'abcd,aabc,bd,efcfdcc'
# b = 'aaa,aa,a'
# print(compare_string1(a,b))
#
#
#
# a = [2,4,5,1,2]
# c = 6
# print(water_flower(a, c)) # 17
# a = [2,4,5,1]
# c = 6
# print(water_flower(a, c)) # 8
# a = [2, 4, 5]
# c = 6
# print(water_flower(a, c)) # 7
# a = [2, 2, 1, 1, 2]
# c = 3
# print(water_flower(a, c)) # 13
#
# import collections
# def continous_k(a, k):
# mini = min(a[:len(a) - k + 1])
# mini_index = []
# for i in range(len(a) - k + 1):
# if a[i] == mini:
# mini_index.append(i)
# res = float('inf')
# for ele in mini_index:
# res = min(res, trans_to_num(ele, a, k))
# res_array = collections.deque()
# while res > 0:
# res_array.appendleft(res % 10)
# res = res // 10
# return res_array
# def trans_to_num(ele, a, k):
# array = a[ele: ele + k]
# res = 0
# j = 0
# for i in range(len(array) - 1, -1, -1):
# res += array[i] * 10 ** j
# j += 1
# return res
# def continous_k(a, k):
# start_index = 0
# for i in range(len(a) - k + 1):
# if a[i] > a[start_index]:
# start_index = i
# return a[start_index: start_index + k]
# a = [1, 4, 3, 2, 5] #[4, 3, 2]
# k = 3
# print(continous_k(a, k))
# a = [1, 4, 3, 2, 5] #[4, 3, 2]
# k = 4
# print(continous_k(a, k))
# a = [3, 1, 2] #[3,22]
# k = 2
# print(continous_k(a, k))
#
# a = [10, 2, 1] #[10,2]
# k = 2
# print(continous_k(a, k))
#
# def solution(A, B):
# # write your code in Python 3.6
# if len(A) == 0 or len(B) == 0:
# return -1
# res = []
# # do not rotate first one
# # A is original, A[0] is target
# base_a = helper(A[0], A, B)
# if base_a != -1:
# res.append(base_a)
# # B is original, B[0] is target
# base_b = helper(B[0], B, A)
# if base_b != -1:
# res.append(base_b)
# # rotate first one, result needs + 1
# # A is original, B[0] is target
# base_a_rotate = helper(B[0], A, B)
# if base_a_rotate != -1:
# res.append(base_a_rotate + 1)
# # B is original, A[0] is target
# base_b_rotate = helper(A[0], B, A)
# if base_b_rotate != -1:
# res.append(base_b_rotate + 1)
#
# if len(res) == 0:
# return -1
# return min(res)
#
# def helper(target, original, totated):
# res = 0
# for i in range(1, len(original)):
# if original[i] != target and totated[i] == target:
# res += 1
# elif original[i] != target and totated[i] != target:
# res = -1
# break
# return res
# a = [2, 4, 6, 5, 2]
# b = [1, 2, 2, 2, 3]
# class SpreadSheet:
# def __init__(self, num_row, num_col):
# self.num_row = num_row
# self.num_col = num_col
# self.content = [['' for i in range(self.num_col)] for j in range(self.num_row)]
# self.record_width = [0 for i in range(self.num_col)]
#
# def edit_content(self, row, col, content):
# self.content[row][col] = content
# self.record_width[col] = max(self.record_width[col], len(content))
#
# def print_spreadsheet(self):
# for i in range(self.num_row):
# print('|'.join(self.content[i]))
#
# def print_pretty(self):
#
# for i in range(self.num_row):
# res = []
# for j in range(self.num_col):
# if len(self.content[i][j]) < self.record_width[j]:
# make_up = self.record_width[j] - len(self.content[i][j])
# res.append(self.content[i][j] + ' ' * make_up)
# else:
# res.append(self.content[i][j])
# print('|'.join(res))
# # def
# spread_sheet = SpreadSheet(4, 3)
# spread_sheet.edit_content(0,0,'bob')
# spread_sheet.edit_content(0,1,'10')
# spread_sheet.edit_content(0,2,'foo')
# spread_sheet.edit_content(1,0,'alice')
# spread_sheet.edit_content(1,1,'5')
#
# spread_sheet.print_spreadsheet()
# spread_sheet.print_pretty()
# spread_sheet.edit_content(1,0,'x')
# def aaa(a):
# res = 0
# for i in range(1, a + 1):
# if i % 15 == 0:
# res += i * 10
# elif i % 5 == 0:
# res += i * 3
# elif i % 3 == 0:
# res += i * 2
# else:
# res += i
# return res
#
# a = 1000
# print(aaa(a))
# def aaaa(a):
# res = []
#
# # index = ord('N') + 17
# # while index > 90:
# # index = index - 90
# # print(chr(index + 65 - 1))
# for i in range(1, 27):
# res = []
# for cha in string:
# index = ord(cha) + i
# if index > 90:
# while index > 90:
# index = index - 90
# res.append(chr(index + 65 - 1))
# else:
# res.append((chr(index)))
# print(i, ''.join(res))
#
#
# string = 'SQZUQ'
# print(aaaa(string))
# def aaa(a):
# count = 0
# for i in range(5000, 50000):
# ord(a[i])
# return count
# print(aaa('LFIHKRVHRMWRXZGVZURHHSLIGLUDZGVI'))
# A = [(-853388, -797447), (-442839, 721091), (-406140, 987734), (-55842, -980970),(-28064, -960562)
# (240773, -871287)
# (273637, 851940)
# (320461, 997514)
# (495045, -667013)
# (757135, -861866)
# (1148386, -439206)
# (1220903, 239470)
# import collections
# def check_function(sum_up):
# res = []
# queue = collections.deque()
# for i in range(0, sum_up):
# for j in range(0, sum_up + 1):
# if i + j == sum_up + 1:
# res.append((i, j))
# if i + 1 < sum_up and j - 1 < sum_up:
# queue.append((i + 1, j - 1))
# if i - 1 < sum_up and j + 1 < sum_up:
# queue.append((i - 1, j + 1))
#
# def find_arguments(f, z):
# x = 1
# y = 2 ** 32 - 1
# res = []
# while f(x, 1) <= z:
# y = bin_search(x, y, f, z)
# if y != -1:
# res.append([x, y])
# else:
# y = 2 ** 32 - 1
# x += 1
# return res
#
# def bin_search(x, last_y, f, z):
# left, right = 1, last_y - 1
# while left <= right:
# mid = (left + right) // 2
#
# if f(x, mid) == z:
# return mid
# elif f(x, mid) < z:
# left = mid + 1
# else:
# right = mid - 1
# return -1
# def f(x,y):
# return x + y
#
# z = 5
# print(find_arguments(f,z))
# class Product:
# def __init__(self, k ):
# self.a = []
# self.product = 1
# self.index_zero = -1
# self.k = k
# def add(self, x):
# self.a.append(x)
# size = len(self.a)
# if len(self.a) <= self.k:
# if x == 0:
# self.index_zero = size - 1
# return 0
# else:
# self.product *= x
# if self.index_zero != -1:
# return 0
# return self.product
# else:
# if x == 0:
# if self.a[size - k - 1] != 0:
# self.product = self.product // self.a[size - k - 1]
# self.index_zero = size - 1
# return 0
# else:
# self.product = self.product * x // self.a[size - k - 1] if self.a[size - k - 1] != 0 else self.product * x
# if size - self.index_zero <= k:
# return 0
# else:
# return self.product
# nums = [1, 3, 3, 6, 5, 7, 0, -3, 6, -3]
# k = 3
# s = Product(k)
#
# # print(s.add(1))
# # print(s.add(3))
# # print(s.add(3))
# # print(s.add(6))
# print(s.add(5))
# print(s.add(7))
# print(s.add(0))
# print(s.add(0))
# print(s.add(6))
# print(s.add(-3))
# print(s.add(-3))
#####frog
# def frog_jump(a, k):
# f = [False for i in range(len(a))]
# f[0] = True
# for i in range(1, len(a)):
# if a[i] == 0:
# if f[i - 1] == True:
# f[i] = True
# if i - k >= 0 and f[i - k] == True:
# f[i] = True
# return f[-1]
#
# def frog_jump1(a, k1, k2):
# visited = [None for i in range(len(a))]
# return dfs(0, visited, k1, k2, a)
# def dfs(start, visited, k1, k2, a):
# if start == len(a) - 1:
# visited[start] = True
# return True
# if visited[start] is not None:
# return
# else:
# for i in range(k1, k2 + 1):
# if start + i < len(a) and a[start + i] == 0:
# if dfs(start + i, visited, k1, k2, a):
# visited[start] = True
# return True
# visited[start] = False
# return False
#
# # a = [0,0,1,1,0,0,1,1,0]
# # k = 3
# # print(frog_jump(a,k))
# a1 = [0,1,1,0,0,1,1,1,0]
# k1 = 3
# k2 = 4
# print(frog_jump1(a1,k1, k2))
# box and ball
# class BoxBall:
# def out_from(self, m, start):
# return self.helper(0, start, 'down', m)
# def helper(self, i, j, dir, m):
# if i == len(m) - 1:
# return j
# else:
# if m[i][j] == '\\':
# if dir == 'down':
# return self.helper(i, j + 1, 'right', m)
# elif dir == 'right':
# return self.helper(i + 1, j, 'down', m)
# else:
# return -1
# elif m[i][j] == '/':
# if dir == 'down':
# return self.helper(i, j - 1, 'left', m)
# elif dir == 'left':
# return self.helper(i + 1, j, 'down', m)
# else:
# return -1
# s = BoxBall()
# m = [['\\', '\\','\\','/','/'],['\\', '\\','\\','/','/'],['/','/','/','\\','\\'],['\\', '\\','\\','/','/'],['/','/','/','/','/']]
# start = 0
# print(s.out_from(m, start))
# def move_target(a, t):
# n = len(a)
# for i in range(n - 1, -1, -1):
# if a[i] == t:
# j = i - 1
# while j >= 0 and a[j] == t:
# j -= 1
# if j < 0:
# break
# a[i], a[j] = a[j], a[i]
# while i >= 0:
# a[i] = t
# i -= 1
# return a
# a = [1,2,4,2,5,7,3,7,3,5]
# t = 5
# print(move_target(a,t))
# def freq(a):
# for i in range(len(a)):
# if a[i] > 0:
# flag = True
# while flag:
# flag = False
# idx = a[i] - 1
# if idx != i:
# if a[idx] > 0:
# # swap
# a[i] = a[idx]
# a[idx] = -1
# flag = True
# else:
# a[i] = 0
# a[idx] -= 1
# else:
# a[idx] = -1
# return a
# a = [4,4,5,3,4,5]
# print(freq(a))
# class Calculate:
# def __init__(self):
# self.save = ''
# self.cur = ''
# self.operator = ''
# self.pre = ''
#
# def calculate(self, c):
# if c == '0' and self.cur == '':
# self.pre = c
# print('')
# elif c.isdigit():
# self.cur += c
# self.pre = c
# print(self.cur)
# elif c == '+' or c == '-':
# if self.pre == '+' or self.pre == '-':
# self.operator = c
# print(self.save)
# elif self.operator == '':
# self.save = self.cur
# self.cur = ''
# self.operator = c
# self.pre = c
# print(self.save)
# else:
# self.cur = str(self.oper())
# self.operator = c
# self.save = self.cur
# self.cur = ''
# self.pre = c
# print(self.save)
#
# def oper(self):
# if self.operator == '+':
# return int(self.save) + int(self.cur)
# elif self.operator == '-':
# return int(self.save) - int(self.cur)
# else:
# return ''
# s = Calculate()
#
# s.calculate('0')
# s.calculate('1')
# s.calculate('2')
# s.calculate('+')
# s.calculate('3')
# s.calculate('-')
# s.calculate('4')
# s.calculate('+')
# s.calculate('-')
# (s.calculate('2'))
# s.calculate('-')
# def matrix_one(a):
# left = len(a[0])
# for i in range(len(a)):
# for j in range(len(a[0])):
# if a[i][j] == 1 and j < left:
# left = j
# break
# return left
#
# def matrix_one1(a):
# left = len(a[0])
# end = len(a[0]) - 1
# for i in range(len(a)):
# if a[i][end] == 1:
# end = bianary_search(a[i], 0, end)
# continue
# return end
#
# def bianary_search(array, start, end):
# while start + 1 < end:
# mid = start + (end - start) // 2
# if array[mid] == 1:
# end = mid
# elif array[mid] == 0:
# start = mid
# if array[start] == 1:
# return start
# else:
# return end
#
# def matrix_one2(a):
# left = len(a[0]) - 1
# down = 0
# while left >= 0 and down < len(a):
# if a[down][left] == 1:
# left -= 1
# else:
# down += 1
#
# return left + 1
#
#
# # a = [[0,0,1,1], [0,0,0,1],[0,0,0,0],[0,1,1,1]]
# # print(matrix_one2(a))
#
# a = [[0,0,1,1,1], [0,0,0,1,1],[0,0,0,0,1],[1,1,1,1,1]]
# print(matrix_one2(a))
# import random
# def max_index(a):
# max_num = float('-inf')
# count = 0
# res = 0
# for i in range(len(a)):
# if a[i] > max_num:
# count = 1
# max_num = a[i]
# res = i
#
# elif a[i] == max_num:
# count += 1
# rdm = random.randint(1, count)
# if rdm == count:
# res = i
# return res
# a = [11,30,2,30,30,30,6,2,62,62]
# print(max_index(a))
# def binary_search(a, target):
# start = 0
# end = len(a) - 1
# while start + 1 < end:
# mid = start + (end - start) // 2
# if a[mid][0] == target:
# return mid
# elif a[mid][0] < target:
# start = mid
# else:
# end = mid
# return start if a[start][0] == target else end
# def subset_target_k(a, k):
# a.sort()
# end = len(a) - 1
# res = 0
# for i in range(0, len(a)):
# if a[i] > k:
# break
# if end <= i:
# res += 1
# else:
# while end > i and a[i] + a[end] > k:
# end -= 1
# res += 2 ** (end - i)
# return res
#
# a = [7,3,6,4,10]
# k = 10
#
# print(subset_target_k(a, k)) # 13
#
# a = [6,3,7,4,10,11]
# k = 10
# print(subset_target_k(a, k)) #13
#
# a = [1,2,3]
# k = 10
# print(subset_target_k(a, k)) # 7
# a = [4,5,3]
# k = 2
# print(subset_target_k(a, k)) # 0
# #duplicate
#
# a = [1,1,1]
# k = 10
# print(subset_target_k(a, k)) # 7
# class Multi():
# def multi_prime(self,nums):
# res = []
# if len(nums) == 0:
# return res
# product = 1
# pos = 0
# # nums.sort()
# self.helper(res, nums, pos, product)
# return res
# def helper(self, res, nums, pos, product):
# if product != 1:
# res.append(product)
# for i in range(pos, len(nums)):
# # if i != pos and nums[i] == nums[i-1]:
# # continue
# product *= nums[i]
# self.helper(res, nums, i+1, product)
# product //= nums[i]
# class Multi1:
# def multi_prime(self, a):
# res = []
# product = 1
# a.sort()
# self.dfs(a, 0, res, product)
# return res
#
# def dfs(self, a, start, res, product):
# if product != 1:
# res.append(product)
# for i in range(start, len(a)):
# # if i > start and a[i] == a[i - 1]:
# # continue
# product *= a[i]
# self.dfs(a, i + 1, res, product)
# product //= a[i]
#
# s = Multi1()
#
# a = [2,2,2]
# print(s.multi_prime(a))
# a = [2,3,5]
# print(s.multi_prime(a))
# def operator(s, target):
# temp = []
# res = []
# # array = [ele for ele in s]
# dfs(s, 0, 0, target, temp, res)
# return res
# def dfs(array, start, cur_sum, target, temp, res):
# if start == len(array):
# if cur_sum == target:
# res.append(''.join(temp))
# else:
# for i in range(start, len(array)):
# head = int(array[start: i + 1])
# if start == 0:
# temp.append(str(head))
# dfs(array, i + 1, cur_sum + head, target, temp, res)
# temp.pop()
# # "+"
# temp.append('+' + str(head))
# dfs(array, i + 1, cur_sum + head, target, temp, res)
# temp.pop()
# # "-"
# temp.append('-' + str(head))
# dfs(array, i + 1, cur_sum - head, target, temp, res)
# temp.pop()
# print(operator('123456789', 252))
#
#
#
#
# class Pocker:
# def __init__(self, p1, p2):
# self.p1 = {}
# self.rule = {'2':2,'J': 11, 'Q':12}
# for ele in p1:
# cur = self.rule[ele]
# if ele in p1:
# self.p1[cur] += 1
# else:
# self.p1[cur] = 1
# # 2:3,K:2
# self.p2 = {}
# def winner(self):
# # p1
# if self.straigt():
# return p1
# # p2
# self.straigt()
# # p1
#
# # maxi
# maxi_p1 = self.high(self, 'p1')
# maxi_p2 = self.high(self, 'p2')
# self.run('maxi', 'p1')
# self.run('maxi', 'p2')
# if maxi_p1 > maxi_p2:
# self.run('maxi', 'p1')
# return 'p1'
# else:
# self.run('maxi', 'p2')
# return 'p2'
#
#
# def straigt(self, p):
# # return T or F
#
# def three_kind
#
#
# def high(self, player):
# maxi = 0
# if player == 'p1':
# p = self.p1
# else:
# p = self.p2
# for ele in p:
# if ele > maxi:
# maxi = ele
# return maxi
# def CheckForSequence(arr, n, k):
# # Traverse the array from end
# # to start
# for i in range(n - 1, -1, -1):
# # if k is greater than
# # arr[i] then substract
# # it from k
# if (k >= arr[i]):
# k -= arr[i]
#
# # If there is any subsequence
# # whose sum is equal to k
# if (k != 0):
# return False
# else:
# return True
#
# # Driver code
#
#
# if __name__ == "__main__":
#
# A = [1, 3, 7, 15, 31]
# n = len(A)
#
# if (CheckForSequence(A, n, 18)):
# print(True)
# else:
# print(False)
#
# LinkedIn OA
# import collections
# def find_max_in_min(a, k):
# start = 0
# deque = collections.deque()
# res = float('-inf')
# for i in range(len(a)):
# cur = a[i]
# while len(deque) > 0 and a[deque[-1]] >= cur:
# deque.pop()
# deque.append(i)
#
# if i - start + 1 > k:
# if start == deque[0]:
# deque.popleft()
# start += 1
# if i - start + 1 == k:
# res = max(res, a[deque[0]])
# return res
# # a = [8,2,4]
# # k = 2
# # print(find_max_in_min(a, k))
# a = [1,3,-1,-3,5,3,6,7,3]
# k = 3
# print(find_max_in_min(a, k))
#
# a = [1,2,3,4,5,4,3,2]
# k = 3
# print(find_max_in_min(a, k))
#
# a = [0,0,0]
# k = 2
# print(find_max_in_min(a, k))
# def arbitrary_shopping(a, tgt):
# start = 0
# i = start
# sum_up = 0
# res = float('-inf')
# while i < len(a):
# while i < len(a) and sum_up + a[i] <= tgt:
# sum_up += a[i]
# i += 1
# if sum_up == tgt:
# res = max(res, i - start)
#
# sum_up -= a[start]
# start += 1
# return res
# a = [2,3,5,1,1,2,1] # 4
# tgt = 5
# print(arbitrary_shopping(a, tgt))
#
# a = [1,1,1,3,2,1,2,1,1] # 4
# tgt = 5
# print(arbitrary_shopping(a, tgt))
# def threshold_alert(n, numCall, alertThreshold, preceding):
# start = 0
# sum_up = 0
# n = len(numCall)
# res = 0
# for i in range(n):
# sum_up += numCall[i]
# if i - start + 1 == preceding:
# if sum_up // preceding > alertThreshold:
# res += 1
# sum_up -= numCall[start]
# start += 1
# return res
#
# n = 8
# numCall = [2, 2, 2, 2, 5, 5, 5, 8]
# alertThreshold = 4
# preceding = 3
# print(threshold_alert(n, numCall, alertThreshold, preceding))
# def break_panlim(a):
# i = 0
# j = len(a) - 1
# while i <= j and a[i] == 'a':
# i += 1
# j -= 1
#
# if i >= j:
# return False
# else:
# return a[:i] + 'a' + a[i + 1:]
#
# a = 'a'
# print(break_panlim(a)) #F
# a = 'aba'
# print(break_panlim(a)) #F
# a = 'aaa'
# print(break_panlim(a)) # F
# a = 'abcba'
# print(break_panlim(a)) # 'aacba'
# def double(a, b):
# # a = set(a)
# # while b in set(a):
# # b *= 2
# for i in range(len(a)):
# if a[i] == b:
# b *= 2
# return b
# b = 2
# a = [1, 2, 4, 11, 12]
# print(double(a, b))
# def map(a):
# directions = [(-1,0), (0, 1),(1, 0),(0, -1)] #up,right,down,left
# row = 0
# col = 0
# dir = 0
# for i in range(4):
# for ele in a:
# if ele == 'G':
# row += directions[dir][0]
# col += directions[dir][1]
# if ele == 'R':
# dir = (dir + 1) % 4
# if ele == 'L':
# dir = (4 + dir - 1) % 4
# return row == 0 and col == 0 and dir == 0
#
# a = 'G'
# print(map(a))
# a = 'L'
# print(map(a))
# a = 'RG'
# print(map(a))
# a = 'GLLG'
# print(map(a))
# a = 'GL'
# print(map(a))
# a = 'GLG'
# print(map(a))
# a = 'GLGLRG'
# print(map(a))
# a = 'GLRG'
# print(map(a))
# a = 'RGRGLGL'
# print(map(a))
#
#
#
#
#
# comicBook
# coin
# coinsNeeded
# consOfferd
# def xxx(comicBook,coins, coinsNeeded, consOfferd ):
# res = 0
# for left in range(comicBook + 1):
# if left * coinsNeeded <= (comicBook - left) * consOfferd + coins:
# res = max(res, left)
# return res
#
# comicBook = 3
# coins = 6
# coinsNeeded = 4
# consOfferd = 5
# print(xxx(comicBook,coins, coinsNeeded, consOfferd))
# comicBook = 10
# coins = 10
# coinsNeeded = 1
# consOfferd = 1
# print(xxx(comicBook,coins, coinsNeeded, consOfferd))
# comicBook = 393
# coins = 896
# coinsNeeded = 787
# consOfferd = 920
# print(xxx(comicBook,coins, coinsNeeded, consOfferd))
# comicBook = 4
# coins = 8
# coinsNeeded = 4
# consOfferd = 3
# print(xxx(comicBook,coins, coinsNeeded, consOfferd))
# import random
#
#
# def selectKItems(stream, n, k):
# array = [0] * k
# # 先把前k个存array里
# for i in range(k):
# array[i] = stream[i]
# i = k
# while (i < n):
# # 从0到i随机取个数
# j = random.randrange(i + 1)
# # j 如果落在k里,求去替换 j 位置的数
# if (j < k):
# array[j] = stream[i]
# i += 1
# return array
# def getMinimumUniqueSum(arr):
# # Write your code here
# if arr is None or len(arr) == 0:
# return 0
#
# num_to_freq = [0 for i in range(11)]
# for i in range(len(arr)):
# num = arr[i]
# num_to_freq[num] += 1
# temp = 0
# not_fill = 0
# for i in range(1, 11):
# if temp == 0 and num_to_freq[i] == 0:
# not_fill += i
# elif num_to_freq[i] == 0:
# temp -= 1
# elif num_to_freq[i] > 1:
# temp += 1
# elif num_to_freq[i] == 1:
# continue
# print(not_fill)
# return (1 + 10) * 10 // 2 - not_fill
# a = [2,2,2,2,2]
# print(getMinimumUniqueSum(a))
# def shuidi(s):
# i = 0
# res = ''
# while i < len(s):
# count = 1
# while i < len(s) - 1 and s[i + 1] == s[i]:
# count += 1
# i += 1
# if ord(s[i]) - ord('a') + 1 > 9:
# res += (str(ord(s[i]) - ord('a') + 1)) + '#'
# else:
# res += (str(ord(s[i]) - ord('a') + 1))
# if count > 1:
# res += '(' + str(count) + ')'
# i += 1
# return res
#
# print(shuidi('back'))#21311#
# print(shuidi('fooood'))
# print(shuidi('aaabbbbaaaa'))
# print(shuidi('sheathery'))
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
#
#
# class Solution:
# def __init__(self):
# self.error = ''
#
# def ddd(self, a):
# aj = {}
# for ele in a:
# if ele[0] not in aj:
# aj[ele[0]] = [ele[1]]
# else:
# aj[ele[0]].append(ele[1])
# visited = set()
# head_set = {}
# for key, child in aj.items():
# if len(child) > 2:
# return 'E1'
# if key not in visited:
# pass_by = set()
# node = TreeNode(key)
# if not self.dfs(key, visited, aj, pass_by, node, head_set):
# return self.error
# head_set[key] = node
# if len(head_set) > 1:
# return 'E5'
# else:
# head = [ele for ele in head_set.values()][0]
# stack = []
# stack.append(head)
# res = []
# return self.dfs_tree(head)
# def dfs_tree(self, root):
# if not root:
# return ''
# else:
# left = self.dfs_tree(root.left)
# right = self.dfs_tree(root.right)
# return '(' + str(root.val) + left + right + ')'
#
#
# def dfs(self, cur, visited, aj, pass_by, node, head_set):
# if node.val in pass_by: # E3
# self.error = 'E3'
# return False
# elif node.val in head_set:
# head_set.remove(node.val)
# return True
# pass_by.add(node.val)
# if node.val in aj:
#
# for child in aj[node.val]:
# if child in head_set:
# new = head_set[child]
# elif child in visited:
# self.error = 'E2'
# return False
# else:
# new = TreeNode(child)
# if not node.left:
# node.left = new
# elif not node.right:
# node.right = new
# else:
# self.error = 'E1'
# return False
# if not self.dfs(child, visited, aj, pass_by, new, head_set):
# return False
# visited.add(node.val)
# return True
#
# s = Solution()
# a = [('A','C'), ('B','G'), ('C', 'H'), ('B', 'D'), ('C', 'E'), ('A', 'B'), ('E', 'F')]
# print(s.ddd(a))
# def frequency1(s):
# i = len(s) - 1
# end = i
# res = ''
# count = 1
# while i >= 0:
# if s[i] == ')':
# while s[i] != '(':
# i -= 1
# count = int(s[i + 1: end])
#
# i -= 1
# end = i
# else:
# count = 1
# if s[i] == '#':
# i -= 2
# ele = s[i:end]
# else:
# ele = s[i:end + 1]
# letter = chr(int(ele) + 97 - 1)
# for k in range(count):
# res = letter + res
# i -= 1
# end = i
# tem = [0] * 26
# for ele in res:
# index = ord(ele) - 97
# tem[index] += 1
# return ''.join([str(ele) for ele in tem])
#
#
#
# def frequency(s):
# i = len(s) - 1
# end = i
# count = 1
# tem = [0] * 26
# while i >= 0:
# if s[i] == ')':
# while s[i] != '(':
# i -= 1
# count = int(s[i + 1: end])
# i -= 1
# end = i
# else:
# count = 1
# if s[i] == '#':
# i -= 2
# ele = s[i:end]
# else:
# ele = s[i:end+1]
# index = int(ele) - 1
# tem[index] += count
#
# i -= 1
# end = i
# return tem
#
#
# print(frequency('25#16#16#18#93(5465)'))
# print(frequency('615#(4)4'))
# print(frequency('1(3)2(4)1(4)'))
# print(frequency('19#85120#8518#25#'))
# import collections
# def possible_word(s):
# q = collections.deque()
# hash = set()
# q.append((s, 0))
# hash.add((s, 0))
# res = []
# while q:
# cur, start = q.popleft()
# if start == len(cur):
# res.append(cur)
# continue
# i = start
# j = i + 1
# count = 1
# break_flag = False
# while j < len(cur):
# while j < len(cur) and cur[j] == cur[i]:
# count += 1
# j += 1
# if count > 2:
# new1 = cur[:i] + cur[i] + cur[j:]
# q.append((new1, i + 1))
# new2 = cur[:i] + cur[i] + cur[i] + cur[j:]
# q.append((new2, i + 2))
# break_flag = True
# break
# else:
# i += 1
# j = i + 1
# if not break_flag:
# res.append(cur)
# return res
#
# s = 'leetcooodeee'
# print(possible_word1(s))
#
# s = 'letcooooodee'
# print(possible_word1(s))
s = 'abcdefs'
for i in range(len(s)-1, -1, -2):
print(s[i])
|
016434f27aba32f18907f1c6918f17d48ab3d279 | dundunmao/LeetCode2019 | /71. Simplify Path.py | 2,223 | 3.609375 | 4 |
class Solution(object):
def simplifyPath(self, path):
#把每个有效路径存places里,不存‘ ’和‘.’
places = [p for p in path.split("/") if p!="." and p!=""]
stack = []
for p in places: #对于存好的每个ele
if p == "..": #如果是‘..'就从stack里pop一个ele。如果不是就往stack里压入一个ele
if len(stack) > 0:
stack.pop()
else:
stack.append(p)
return "/" + "/".join(stack) #最后把stack用/join起来
class Solution1:
def simplifyPath(self, path: str) -> str:
res = []
i = 0
while i < len(path):
if path[i] == '/':
j = i + 1
# i占到一个'/', j找到下一个'/'
while j < len(path) and path[j] != '/':
j += 1
# 处理多个'/'
if j == i + 1:
i = j
# 处理有'/./'的情况
elif path[i + 1: j] == '.':
i = j
# 处理 '/../'的情况
elif path[i + 1: j] == '..':
if res:
res.pop()
i = j
# 其他情况,就是'/字母/'的情况
else:
res.append(path[i + 1: j])
i = j
res = '/'.join(res)
return '/' + res
#简化代码
class Solution2:
def simplifyPath(self, path: str) -> str:
res = []
i = 0
while i < len(path):
if path[i] == '/':
j = i + 1
while j < len(path) and path[j] != '/':
j += 1
if path[i + 1: j] == '..':
if res:
res.pop()
elif j != i + 1 and path[i + 1: j] != '.':
res.append(path[i + 1: j])
i = j
res = '/'.join(res)
return '/' + res
s = Solution2()
a = "/home//" # "/home/foo"
b = "/a/./b/../../c/" # "/c"
c = "/a/../../b/../c//.//"# "/c"
print(s.simplifyPath(a))
print(s.simplifyPath(b))
print(s.simplifyPath(c))
|
ca29c23ac842885b8661bbd34e8fd6a20bb16d83 | dundunmao/LeetCode2019 | /381. Insert Delete GetRandom O(1) - Duplicates allowed.py | 2,717 | 3.890625 | 4 | from random import choice
class RandomizedCollection:
def __init__(self):
"""
Initialize your data structure here.
"""
self.randomized_hash = {}
self.array = []
def insert(self, val: int) -> bool:
"""
Inserts a value to the collection. Returns true if the collection did not already contain the specified element.
"""
if val in self.randomized_hash:
self.randomized_hash[val].append(len(self.array))
self.array.append(val)
return False
else:
self.randomized_hash[val] = [len(self.array)]
self.array.append(val)
return True
def remove(self, val: int) -> bool:
"""
Removes a value from the collection. Returns true if the collection contained the specified element.
"""
if val not in self.randomized_hash:
return False
else:
array_for_val = self.randomized_hash[val]
val_index = array_for_val.pop()
if len(array_for_val) == 0:
self.randomized_hash.pop(val)
if val_index == len(self.array) - 1:
self.array.pop()
return True
self.array[val_index], self.array[-1] = self.array[-1], self.array[val_index]
self.array.pop()
self.randomized_hash[self.array[val_index]].remove(len(self.array))
self.randomized_hash[self.array[val_index]].append(val_index)
return True
def getRandom(self) -> int:
"""
Get a random element from the collection.
"""
return choice(self.array)
# Your RandomizedCollection object will be instantiated and called as such:
obj = RandomizedCollection()
param_1 = obj.insert(10)
param_1 = obj.insert(10)
param_1 = obj.insert(20)
param_1 = obj.insert(20)
param_1 = obj.insert(30)
param_1 = obj.insert(30)
param_2 = obj.remove(10)
param_2 = obj.remove(10)
param_2 = obj.remove(30)
param_2 = obj.remove(30)
param_3 = obj.getRandom()
obj = RandomizedCollection()
param_1 = obj.insert(1)
param_1 = obj.insert(1)
param_2 = obj.remove(1)
param_3 = obj.getRandom()
obj = RandomizedCollection()
param_1 = obj.insert(1)
param_2 = obj.remove(2)
param_1 = obj.insert(2)
param_3 = obj.getRandom()
param_2 = obj.remove(1)
param_1 = obj.insert(2)
param_3 = obj.getRandom()
["RandomizedCollection","insert","insert","insert","insert","insert","insert","remove","remove","remove","remove","getRandom","getRandom","getRandom","getRandom","getRandom","getRandom","getRandom","getRandom","getRandom","getRandom"]
[[],[10],[10],[20],[20],[30],[30],[10],[10],[30],[30],[],[],[],[],[],[],[],[],[],[]]
|
51db392efffbfbbc86b4c8557660896b884de512 | dundunmao/LeetCode2019 | /199. Binary Tree Right Side View.py | 1,876 | 3.640625 | 4 | class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
from collections import deque
from collections import deque
class Solution(object):
def rightSideView(self, root):
"""
:type root: TreeNode
:rtype: List[int]
"""
if root is None:
return []
q = deque()
q.append(root)
res = []
while q:
size = len(q)
for i in range(size):
cur = q.popleft()
if cur.left:
q.append(cur.left)
if cur.right:
q.append(cur.right)
res.append(cur.val)
return res
class Solution(object):
def rightSideView(self, root):
res = []
if root is None:
return res
right = self.rightSideView(root.right) #左子树的res
left = self.rightSideView(root.left) #右子树的res
res.append(root.val)
res.extend(right) #右子树的res全加入res里
for i in range(len(right), len(left)): #左子树多余的res全加入res里
res.append(left[i])
return res
#####
import collections
class Solution:
def rightSideView(self, root: TreeNode) -> List[int]:
if not root:
return []
deque = collections.deque()
deque.append(root)
res = []
while len(deque):
size = len(deque)
res.append(deque[0].val)
for i in range(size):
cur = deque.popleft()
# 先加right再加left,这样每次for之前,只要把deque的第一个放res里就行
if cur.right:
deque.append(cur.right)
if cur.left:
deque.append(cur.left)
return res
|
ce3c6173edd8573af176473a0de58b581553e2ad | dundunmao/LeetCode2019 | /128. Longest Consecutive Sequence.py | 2,078 | 3.75 | 4 | # Given an unsorted array of integers, find the length of the longest consecutive elements sequence.
#
# For example,
# Given [100, 4, 200, 1, 3, 2],
# The longest consecutive elements sequence is [1, 2, 3, 4]. Return its length: 4.
#
# Your algorithm should run in O(n) complexity.
# 麻烦的做法
class Solution:
def longestConsecutive(self, nums: List[int]) -> int:
if len(nums) == 0:
return 0
num_to_count_set = set(nums)
node_list = {}
for value in num_to_count_set:
if value + 1 in num_to_count_set:
if value in node_list:
node_small = node_list[value]
else:
node_small = Node(value)
node_list[value] = node_small
if value + 1 in node_list:
node_big = node_list[value + 1]
else:
node_big = Node(value + 1)
node_list[value + 1] = node_big
node_small.next = node_big
node_big.pre = node_small
head_list = []
for node in node_list.values():
if node.pre == None:
head_list.append(node)
res = 1
for node in head_list:
length = 1
while node.next:
length += 1
node = node.next
res = max(res, length)
return res
class Node:
def __init__(self, val):
self.val = val
self.next = None
self.pre = None
##########################
class Solution(object):
def longestConsecutive(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
nums = set(nums)
maxlen = 0
while nums:
first = last = nums.pop()
while first - 1 in nums:
first -= 1
nums.remove(first)
while last + 1 in nums:
last += 1
nums.remove(last)
maxlen = max(maxlen, last - first + 1)
return maxlen
|
e23abce5463ea24cabd75aee1967d58369d52a85 | mattions/libNeuroML | /neuroml/examples/example5.py | 353 | 3.5 | 4 | """
This example shows how a morphology can be translated
such that the translated node moves to the new origin
and all other nodes move along with it
"""
import neuroml.morphology as ml
a=ml.Node([1,2,3,10])
b=ml.Node([4,5,6,20])
a.connect(b)
print a.morphology.vertices
b.translate_morphology([1,2,3])
print 'translated:'
print b.morphology.vertices
|
6108ea4b42d7de0e4059c54d6402e01bc56ba9de | jacobfdunlop/TUDublin-Masters-Qualifier | /binaryToDecimal.py | 424 | 3.984375 | 4 | user_num = input("Please Enter a binary number: ")
length = int(len(user_num))
power = ()
x = int()
z = int()
output = int()
while length >= 0:
z = int(user_num[length - 1])
if z == 1:
power = (2 ** x) * z
x += 1
length -= 1
output += power
else:
x += 1
length -= 1
print("Binary Number: ", user_num)
print(" Decimal Output: ", output)
|
9a6487e077eeefcb009581a7d4ad31284a4b064c | jacobfdunlop/TUDublin-Masters-Qualifier | /strings18.py | 368 | 3.796875 | 4 | user_str = input("Please enter a word: ")
while user_str != ".":
vowels = "aeiou"
if user_str[0] in vowels:
print(user_str + "yay")
else:
for a in range(len(user_str) + 1):
if user_str[a] in vowels:
print(user_str[a:] + user_str[0:a] + "ay")
user_str = "."
break
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.