text stringlengths 37 1.41M |
|---|
## Print all fibonacci numbers <=n
def main():
n = int(input())
vals = [0,1]
while vals[-1]<=n:
num = sum(vals[-2:])
vals.append(num)
[print(x,end=' ') for x in vals[:-1]]
if __name__ == '__main__':
main() |
## Sum of all even-valued fibonacci terms below 4 million
def get_sum(num):
ans=2
val=0
a=1
b=2
while val<num:
val=a+b
a=b
b=val
if not val%2:
print(val)
ans+=val
return ans
def main():
MAX = int(input()) ## Max Range
ans = get_sum(MAX)
print(ans)
if __name__ == '__main__':
main() |
## Print nth fibonacci number
def main():
n = int(input())
if n==1 or n==0:
print(n)
else:
vals = [0,1]
while len(vals)<=n:
num = sum(vals[-2:])
vals.append(num)
print(vals[-1])
if __name__ == '__main__':
main() |
## Find gcd of two numbers when one number is of order 10^250
def big_modulo(a,b):
small_mod = 0
for val in b:
big_mod = ((10*small_mod)%a+int(val)%a)%a
small_mod = big_mod
return big_mod
def get_gcd(a,b):
if b==0:
return a
return get_gcd(b,a%b)
def main():
t = int(input())
for _ in range(t):
a,b = input().split()
a = int(a)
if a==0:
print(b)
else:
b_mod_a = big_modulo(a,b) ## calculate b%a
gcd = get_gcd(a,b_mod_a)
print(gcd)
if __name__ == '__main__':
main() |
# Given a number N, print all its unique prime factors and their powers in N.
def get_primes(num):
sieve = [True]*(num+1)
factors = {val:[] for val in range(num+1)}
for val in range(2,num+1):
if sieve[val]:
factors[val] = [val]
for mul in range(2*val,num+1,val):
sieve[mul] = False
factors[mul].extend([val])
return factors
def get_power(num,factors):
powers = []
for prime in factors:
power = 0
while not num%prime:
num=num/prime
power += 1
powers.append(power)
return powers
def main():
t = int(input())
for _ in range(t):
num = int(input())
factors = get_primes(num)
factors_n = factors[num]
powers = get_power(num,factors_n)
for factor,power in zip(factors_n,powers):
print(factor,power,end=' ')
print()
if __name__ == '__main__':
main() |
r"""
`RK methods <https://en.wikipedia.org/wiki/Runge%E2%80%93Kutta_methods>`_ on Wikipedia.
"""
import numpy as np
from ..misc.counter import Counter
def rk_1(y0, t, f, verbose=True, **_):
"""
RK1 or Explicit Euler method
:param array_like y0: Initial value, may be multi-dimensional of size d
:param 1D_array t: Array of time steps, of size n
:param func f: Function with well shaped input and output
:param verbose: If True or a string, displays a progress bar
:type verbose: bool or str, optional
:return: numpy.ndarray - The solution, of shape (n, d)
"""
try:
n, d = len(t), len(y0)
y = np.zeros((n, d))
except TypeError:
n = len(t)
y = np.zeros((n,))
if verbose is False:
count = Counter('', 0)
elif verbose is True:
count = Counter('RK1', n)
else:
count = Counter(verbose, n)
y[0] = y0
for i in range(n - 1):
y[i + 1] = y[i] + (t[i + 1] - t[i]) * f(y[i], t[i])
count(i + 1)
return y
def rk_2(y0, t, f, verbose=True, **_):
"""
RK2 or midpoint method
:param array_like y0: Initial value, may be multi-dimensional of size d
:param 1D_array t: Array of time steps, of size n
:param func f: Function with well shaped input and output
:param verbose: If True or a string, displays a progress bar
:type verbose: bool or str, optional
:return: numpy.ndarray - The solution, of shape (n, d)
"""
try:
n, d = len(t), len(y0)
y = np.zeros((n, d))
except TypeError:
n = len(t)
y = np.zeros((n,))
if verbose is False:
count = Counter('', 0)
elif verbose is True:
count = Counter('RK2', n)
else:
count = Counter(verbose, n)
y[0] = y0
for i in range(n - 1):
h = t[i + 1] - t[i]
k1 = f(y[i], t[i])
k2 = f(y[i] + h * k1 / 2, t[i] + h / 2)
y[i + 1] = y[i] + h * k2
count(i + 1)
return y
def rk_4(y0, t, f, verbose=True, **_):
"""
RK4 method
:param array_like y0: Initial value, may be multi-dimensional of size d
:param 1D_array t: Array of time steps, of size n
:param func f: Function with well shaped input and output
:param verbose: If True or a string, displays a progress bar
:type verbose: bool or str, optional
:return: numpy.ndarray - The solution, of shape (n, d)
"""
try:
n, d = len(t), len(y0)
y = np.zeros((n, d))
except TypeError:
n = len(t)
y = np.zeros((n,))
if verbose is False:
count = Counter('', 0)
elif verbose is True:
count = Counter('RK4', n)
else:
count = Counter(verbose, n)
y[0] = y0
for i in range(n - 1):
h = t[i + 1] - t[i]
k1 = f(y[i], t[i])
k2 = f(y[i] + h * k1 / 2, t[i] + h / 2)
k3 = f(y[i] + h * k2 / 2, t[i] + h / 2)
k4 = f(y[i] + h * k3, t[i] + h)
y[i + 1] = y[i] + h * (k1 + 2 * k2 + 2 * k3 + k4) / 6
count(i + 1)
return y
def rk_butcher(a, b):
"""
Generic explicit s-stage RK method, using a Butcher tableau (*a*, *b*, *c*)
The returned method is explicit, therefore only the strictly lower triangular part of *a* is used.
The *c* array is deduced from the *a* and the *b* array so that the method is consistent:
:math:`c_{i}=\sum _{k=0}^{i-1}a_{ik}`
:param 2D_array a: The *a* array of the Butcher tableau, of shape (s, s)
:param 2D_array b: The *b* array of the Butcher tableau, of shape (s,)
:return: func - the wanted Runge Kutta method
"""
q = a.shape[0]
c = np.array([np.sum(a[i, :i]) for i in range(q)])
def rk_method(y0, t, f, verbose=True, **_):
"""
RK method from given Butcher tableau
:param array_like y0: Initial value, may be multi-dimensional of size d
:param 1D_array t: Array of time steps, of size n
:param func f: Function with well shaped input and output
:param verbose: If True or a string, displays a progress bar
:type verbose: bool or str, optional
:return: numpy.ndarray - The solution, of shape (n, d)
"""
try:
n, d = len(t), len(y0)
y = np.zeros((n, d))
p = np.zeros((q, d))
except TypeError:
n = len(t)
y = np.zeros((n,))
p = np.zeros((q,))
if verbose is False:
count = Counter('', 0)
elif verbose is True:
count = Counter('RK_butcher', n)
else:
count = Counter(verbose, n)
y[0] = y0
for i in range(n - 1):
h = t[i + 1] - t[i]
for j in range(q):
if p.ndim > 1:
p[j] = f(y[i] + h * np.sum(a[j, :j, None] * p[:j], axis=0), t[i] + h * c[j])
else:
p[j] = f(y[i] + h * np.sum(a[j, :j] * p[:j]), t[i] + h * c[j])
if p.ndim > 1:
y[i + 1] = y[i] + h * np.sum(b[:, None] * p, axis=0)
else:
y[i + 1] = y[i] + h * np.sum(b * p)
count(i + 1)
return y
return rk_method
A_RK4 = np.array([[0., 0., 0, 0],
[.5, 0., 0, 0],
[.0, .5, 0, 0],
[.0, 0., 1, 0]])
"""The *a* array for the RK4 Butcher tableau"""
B_RK4 = np.array([1. / 6, 1. / 3, 1. / 3, 1. / 6])
"""The *b* array for the RK4 Butcher tableau"""
|
def check_repeat(row):
if len(row) != len(set(row)):
return False
return True
def check_elements(row, ref):
for item in row:
if item not in ref:
return False
return True
def row_wise(arr, ref):
for row in arr:
if check_elements(row, ref) == False or check_repeat(row) == False:
return False
return True
def col_wise(arr, ref):
num = len(arr[0])
for pos in range(num):
temp_list = []
for iter_col in range(num):
temp_list.append(arr[iter_col][pos])
if check_elements(temp_list, ref) == False or check_repeat(temp_list) == False:
return False
return True
def check_sudoku(arr):
# check flags
flags = [False, False]
# collect elements
ref = [x for x in range(1, len(arr[0]) + 1)]
# checking row wise
flags[0] = row_wise(arr, ref)
# check column wise
flags[1] = col_wise(arr, ref)
# return answer
if False in flags:
return False
return True
correct = [[1,2,3],
[2,3,1],
[3,1,2]]
print(len(correct[0]))
print(check_sudoku(correct))
|
def cal(name1,name2):
combStr = name1 + "loves" + name2
strCount = ""
for c1 in combStr:
if combStr.count(c1) != 0:
strCount+=str(combStr.count(c1))
combStr = combStr.replace(c1,"")
n= list(map(int,strCount))
while len(n)>2:
n = shortn(n)
per = int(''.join(map(str,n)))
return per
def shortn(n):
i=0
i=0
j=len(n)-1
n1=[]
while i<=j :
per = n[i]+n[j]
if i==j:
per = n[i]
n1.append(per)
i+=1
j-=1
return n1
if __name__ == "__main__":
n1=input("Enter your name: ").lower()
n2=input("Enter your Partner/Crush name: ").lower()
print(f" \n{n1.upper()} and {n2.upper()}")
print(f"""
love meter:
_____ ______
( \ / )
\ \ / /
\ /
\ {cal(n1,n2)}% /
\ /
\ /
\ /
\ /
\/ """ )
|
import numpy as np
from .util import pairwise_comparison_preference
def condorcet(P):
"""
Rule: Condorcet(P) : {x} if for all y in A \{x}, x net P over Y
Take the example:
a b c
b a c
c b a
a > c
b > c
b > a
Condorcet winner:
b
"""
A = np.unique(P)
highest_alternative = {key:0 for key in A}
for (idx, x) in enumerate(A):
if idx == len(A)-1:
continue
y = A[idx + 1]
count_x, count_y = pairwise_comparison_preference(x, y, P)
highest_alternative[x] += count_x
highest_alternative[y] += count_y
highest_alternative = {key:int(value/2) for (key, value) in highest_alternative.items()}
return max(highest_alternative, key=highest_alternative.get)
|
Question 1
Print the first ArmStrong number in the range of 1042000 to 702648265 and exit the loop as soon
as you encounter the first armstrong number.
Use while loop
lower = 1042000
upper = 702648265
for num in range(lower, upper + 1):
# order of number
order = len(str(num))
# initialize sum
sum = 0
temp = num
while temp > 0:
digit = temp % 10
sum += digit ** order
temp //= 10
if num == sum:
print(num)
|
import datetime
from urllib.request import urlopen
from bs4 import BeautifulSoup, SoupStrainer
import ssl
import url
import re
"""
This code searches a page for instances of the user's keywords and creates a url object for each page with any of the keywords found.
To run, this code needs one parameter "url" that is the address of each webpage.
"""
def keyword_search(address, keywords):
"""
Checks for instances of keywords on page and finds other urls on page
return: url keywords were found and list of urls found on page
"""
ctx = ssl._create_unverified_context()
ctx.check_hostname = False
ctx.verify_mode = ssl.CERT_NONE
try:
html = urlopen(address, context=ctx)
except:
#returns empty url object and no new addresses
print(address, 'failed to open.')
return url.URL("", {i: 0 for i in keywords}, address), []
bsObj = BeautifulSoup(html.read(), "html.parser")
url_list = collect_url(bsObj,address)
bsObj = bsObj.get_text().lower()
mywords = bsObj.split()
keyword_count = {i: 0 for i in keywords}
for keyword in keywords:
# Currently set to break the loop if any keyword is found and add the url to the list to be returned
for word in mywords:
if keyword.lower() == word:
keyword_count[keyword] += 1
#break
return url.URL(datetime.datetime.now(), keyword_count, address), url_list
def collect_url(bsObj,address):
if address[-1] == '/':
address = address[:-1]
urls = []
for link in bsObj.find_all('a', href=True):
new_add = link['href']
if len(new_add) == 0:
pass
elif new_add[0] == '/':
urls += [address+new_add]
elif 'http' in new_add:
urls += [new_add]
return urls
if __name__ == "__main__":
print(keyword_search("www.emu.edu", ["Eastern", "Mennonite"])[0]) |
class SaveData:
"""
Model for game's save file. Contains the data written or read from the file.
Kind of like a serializer.
"""
def __init__(self, ai_game):
"""Initialize 'save data' instance."""
self.ai_game = ai_game
def get_data(self):
"""Return data to be saved, neatly formatted as json"""
data = {
'high_score': self.ai_game.stats.high_score,
'enemies_killed': self.ai_game.stats.enemies_killed,
'player': self.ai_game.settings.current_player
}
return data
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Aug 12 15:58:25 2019
@author: prashantpk
"""
# API KEY: 0299a321aad8b514e4873dff5b831681
# PRIVATE KEY: 5c7c66e8bfecdd1662bbaeafabfeb3ff
## Application ID: e7d78c18
## Application Key: 3b93ac98bf5e39f4e5a5dc09e9910c0a
_app_id = "e7d78c18"
_app_key = "3b93ac98bf5e39f4e5a5dc09e9910c0a"
api_key = '0299a321aad8b514e4873dff5b831681'
import requests
class Enquiry:
#### The Constructor for the Class Enquiry...
def __init__(self):
self.user_input = input("""Hi! What would you like to do.
1. Enter 1 to search for flights.
2. Enter 2 to check PNR Status.
3. Enter 3 to check Route of the Train.
4. Enter 4 to check the seat availabilty of train for a given date.
5. Enter 5 to check Train Status.
6. Enter 6 to find train between stations.
7. Enter 7 to find trains at the station.
8. Enter 8 to find cancelled trains for a given date.
9. Enter 9 to find diverted trains for a given date.
10. Enter 10 to check station location on map.
11. Enter 11 to check Coach Position for a given train number.
12. Enter 12 to exit. \n""")
if self.user_input == "1":
self.flight_search()
if self.user_input == "2":
self.pnr_status()
elif self.user_input == "3":
self.train_route()
elif self.user_input == "4":
self.seat_availability()
elif self.user_input == "5":
self.train_status()
elif self.user_input == "6":
self.find_train()
elif self.user_input == "7":
self.train_arrival()
elif self.user_input == "8":
self.cancelled_trains()
elif self.user_input == "9":
self.diverted_trains()
elif self.user_input == "10":
self.station_location()
elif self.user_input == "11":
self.coach_position()
else:
print("BYE")
#######################################################################################################
#######################################################################################################
def flight_search(self):
"""
===> Doc String of the FUNCTION: flight_search "
This Function is used to seach for flights between two places on a given date.
Date: 09 2019
Created By: Prashant Kumar
Input: Origin Airport Code (from where the journey starts, should be a valid IATA Code)
Destination Airport Code (upto where the journey has to end, should be a valid IATA Code)
Departure Date: The date of Journey.
Check: If One Way Flight: 0, otherwise if Return Flight is also considered: 1
Arrival Date: If Return Flight is also considered then date of return.
Seating Class: The type of Class in which user wants to travel, Business: B, or Economy : E
Adult Pass: Number of Adult Passengers (At least one)
Child Pass: Number of Children Passengers.
Infant Pass: Number of Infant Passengers
Counter: International: 0, Domestic: 100
Output: Flight Detais as per the User Search.
"""
source = input("Enter the Origin Airport code. \n(Should be a valid IATA code): ").upper()
dest = input("Enter the Destination Airport code. \n(Should be a valid IATA code): ").upper()
departure_date = input("Enter the Departure Date \n(for onward flights only). (Format (YYYYMMDD)): ")
check = input("Do you wish to check for return flight to. \n(If yes enter 1 else enter 0): ")
if check == '1':
arrival_date = input("Enter the Arrival Date \n(for onward & return Flights). (Format (YYYYMMDD)): ")
else:
pass
seating_class = input("Enter the Travel Class/ Cabin Type. \n(E(Economy) or B(Business)): ").upper()
adult_pass = input("Enter the number of Adult Passengers. \n(Integer value between 1-9. Minimum of one adult is required.): ")
child_pass = input("Enter the number of Children Passengers. \n(Integer value between 0-9.): ")
infant_pass = input("Enter the number of Infant Passengers. \n(Integer value between 0-9.): ")
counter = input("Enter the Counter No. \n(100 for domestic, 0 for International): ")
if check == '1':
url = "http://developer.goibibo.com/api/search/?app_id={}&app_key={}&format=json&source={}&destination={}&dateofdeparture={}&dateofarrival={}&seatingclass={}&adults={}&children={}&infants={}&counter={}".format(_app_id, _app_key, source, dest, departure_date, arrival_date, seating_class, adult_pass, child_pass, infant_pass, counter)
else:
url = "http://developer.goibibo.com/api/search/?app_id={}&app_key={}&format=json&source={}&destination={}&dateofdeparture={}&seatingclass={}&adults={}&children={}&infants={}&counter={}".format(_app_id, _app_key, source, dest, departure_date, seating_class, adult_pass, child_pass, infant_pass, counter)
response = requests.get(url)
response = response.json()
#print(response)
if check == '0':
for i in response['data']['onwardflights']:
print("\n", i['airline'], "|", i['origin'], i['deptime'], "-->", i['duration'], "(", i['stops'], "Stop)", "-->", i['destination'], i['arrtime'], "|", i['seatingclass'], i['fare']['totalfare'])
print("-------- FLIGHT INFORMATION --------")
print(i['airline'], "(", i['carrierid'], "-", i['flightno'], ")", "(Aircraft:", i['aircraftType'], ")", i['origin'], i['deptime'], "-->", i['duration'], "(", i['stops'], "STOPS)", "-->", i['destination'], i['arrtime'])
print("-------- FARE DETAILS --------")
print("Base Fare (", adult_pass, "Adults,", child_pass, "Child,", infant_pass, "Infant) :", i['fare']['totalbasefare'])
#print("Taxes and Fees (", adult_pass, "Adults,", child_pass, "Child,", infant_pass, "Infant) :", (i['fare']['adulttax'] + i['fare']['infanttaxes'] + i['fare']['childtaxes']))
print("Total Fare (", adult_pass, "Adults,", child_pass, "Child,", infant_pass, "Infant) :", i['fare']['totalfare'])
print("--------------------------------------------")
else:
for i, j in zip(response['data']['onwardflights'], response['data']['returnflights']):
print("\n", i['airline'], "|", i['origin'], i['deptime'], "-->", i['duration'], "(", i['stops'], "Stop)", "-->", i['destination'], i['arrtime'], "|", i['seatingclass'], i['fare']['totalfare'], "|||", j['airline'], "|", j['origin'], j['deptime'], "-->", j['duration'], "(", j['stops'], "Stop)", "-->", j['destination'], j['arrtime'], "|", j['seatingclass'], j['fare']['totalfare'])
print("-------- FLIGHT INFORMATION --------")
print(i['airline'], "(", i['carrierid'], "-", i['flightno'], ")", "(Aircraft:", i['aircraftType'], ")", i['origin'], i['deptime'], "-->", i['duration'], "(", i['stops'], "STOPS)", "-->", i['destination'], i['arrtime'], "|||", j['airline'], "(", j['carrierid'], "-", j['flightno'], ")", "(Aircraft:", j['aircraftType'], ")", j['origin'], j['deptime'], "-->", j['duration'], "(", j['stops'], "STOPS)", "-->", j['destination'], j['arrtime'])
print("-------- FARE DETAILS --------")
print("Base Fare (", adult_pass, "Adults,", child_pass, "Child,", infant_pass, "Infant) :", i['fare']['totalbasefare'], "\n", "Total Fare (", adult_pass, "Adults,", child_pass, "Child,", infant_pass, "Infant) :", i['fare']['totalfare'], "\n", "Base Fare (", adult_pass, "Adults,", child_pass, "Child,", infant_pass, "Infant) :", j['fare']['totalbasefare'], "\n", "Total Fare (", adult_pass, "Adults,", child_pass, "Child,", infant_pass, "Infant) :", j['fare']['totalfare'], "\n")
#print("Taxes and Fees (", adult_pass, "Adults,", child_pass, "Child,", infant_pass, "Infant) :", (i['fare']['adulttax'] + i['fare']['infanttaxes'] + i['fare']['childtaxes']))
#######################################################################################################
#######################################################################################################
def pnr_status(self):
"""
===> Doc String of the FUNCTION: pnr_status "
This Function is used to find the pnr status for a given PNR Number.
Date: 21st June 2019
Created By: Prashant Kumar
Input: A valid PNR Number of a train from India.
Output: Details related to the give PNR number.
"""
# http://indianrailapi.com/api/v2/PNRCheck/apikey/<apikey>/PNRNumber/<pnrNumber>/Route/1/
pnr_no = input("Enter the PNR number: ")
pnr_url = "http://indianrailapi.com/api/v2/PNRCheck/apikey/{}/PNRNumber/{}/Route/1/".format(api_key, pnr_no)
response = requests.get(pnr_url)
response = response.json()
#print(pnr_response)
print("PNR No.: ", response['PnrNumber'])
print("Train Number:", response['TrainNumber'], "|" , "Train Name:", response['TrainName'])
print("Date of Journey:", response['JourneyDate'], "|" , "Chart Prepared:", response['ChatPrepared'], "|", "Journey Class:", response['JourneyClass'])
print("From: ", response['From'], "---->", "Reservation Upto: ", response['To'])
for i in response['Passangers']:
print("Passenger Details: ", i['Passenger'])
print("Booking Status:", i['BookingStatus'])
print("Current Status: ", i['CurrentStatus'], "\n")
#######################################################################################################
#######################################################################################################
def train_route(self):
"""
===> Doc String of the FUNCTION: train_route "
This Function is used to find the route for a given train number.
Date: 21st June 2019
Created By: Prashant Kumar
Input: A valid Train Number from India Railway
Output: Train Name, Number and Details of the station that the train covers.
"""
# http://indianrailapi.com/api/v2/TrainSchedule/apikey/<apikey>/TrainNumber/<TrainNumber>/
self.train_no = input("Enter the Train Number: ")
self.status_url = "http://indianrailapi.com/api/v2/TrainSchedule/apikey/{}/TrainNumber/{}/".format(api_key, self.train_no)
response = requests.get(self.status_url)
response = response.json()
#print(response)
#for i in status_response['train']:
#print(response['train']['name'])
for i in response['Route']:
print("Station No.:", i['SerialNo'], "|", "Station Name:", i['StationName'], "|", "Arrival Time:", i['ArrivalTime'], "|", "Departure Time:", i['DepartureTime'], "|", "Distance Covered:", i['Distance'], "\n")
#######################################################################################################
#######################################################################################################
def seat_availability(self):
"""
===> Doc String of the FUNCTION: seat_availability "
This Function is used to find the number of seats available for a train on a given date between two stations.
Date: 21st June 2019
Created By: Prashant Kumar
Input: A vaild Train Number
Source Station Code
Destination Station code
Date of the journey
Class Code of the Class in which user wants to find the seat.
Quota Code of the quota in user wants to book a seat.
Output: Train Name, Train Number
Journey Class which user has selected along with its Code
From Station where user is starting the journey, Destination Station Name.
Selected date and the Availabilty Status for the given date.
"""
# Train Fare: http://indianrailapi.com/api/v2/TrainFare/apikey/<apikey>/TrainNumber/<trainNumber>/From/<stationFrom>/To/<stationTo>/Quota/<quota>
# https://indianrailapi.com/api/v2/SeatAvailability/apikey/{apikey}/TrainNumber/{trainNumber}/From/{stationFrom}/To/{stationTo}/Date/{yyyyMMdd}/Quota/GN/Class/{classCode}
train_no = input("Enter the Train Number: ")
source_stn = input("Enter the Source Station Code: ").upper()
dest_stn = input("Enter the Destination Station Code: ").upper()
date = input("Enter the date of journey \n(in yyyymmdd format): ")
class_code = input("Enter the class code: ").upper()
quota_code = input("Enter the Quota to book the ticket(GN: General, CK: Tatkal): ").upper()
url = "https://indianrailapi.com/api/v2/SeatAvailability/apikey/{}/TrainNumber/{}/From/{}/To/{}/Date/{}/Quota/GN/Class/{}".format(api_key, train_no, source_stn, dest_stn, date, class_code)
fare_url = "http://indianrailapi.com/api/v2/TrainFare/apikey/{}/TrainNumber/{}/From/{}/To/{}/Quota/{}".format(api_key, train_no, source_stn, dest_stn, quota_code)
response = requests.get(url)
response = response.json()
fare_response = requests.get(fare_url)
fare_response = fare_response.json()
print("Train Number:", response['TrainNo'], "|", "Train Name:", fare_response['TrainName'], "|" "From:", response['From'], "|", "To:", response['To'], "|", "Class Code:", response['ClassCode'], "|", "Quota:", response['Quota'])
for k in fare_response['Fares']:
if k['Code'] == class_code:
for i in response['Availability']:
print("Date:", i['JourneyDate'], "|", i['Availability'], "|", "Confirm Percentage:", i['Confirm'], "|", "Fare:", k['Fare'], "\n")
#######################################################################################################
#######################################################################################################
def train_status(self):
"""
===> Doc String of the FUNCTION: train_status "
This Function is used to find the Live Train status for a given Train Number, Station and Date.
Date: 21st June 2019
Created By: Prashant Kumar
Input: A valid Train Number
Date for which the user wants to check
Output: Train Number
Train Name
Curreent Position of the Train
"""
# http://indianrailapi.com/api/v2/livetrainstatus/apikey/<apikey>/trainnumber/<train_number>/date/<yyyymmdd>/
train_no = input("Enter the train number: ")
date = input("Enter the date \n(in yyyymmdd format):")
url = "http://indianrailapi.com/api/v2/livetrainstatus/apikey/{}/trainnumber/{}/date/{}/".format(api_key, train_no, date)
response = requests.get(url)
response = response.json()
#print(response)
print(response['TrainNumber'], "|", response['StartDate'])
print("Current Status:", response['CurrentStation']['StationName'], "|", "Schedule Arrival:", response['CurrentStation']['ScheduleArrival'], "|", "Actual Arrival:", response['CurrentStation']['ActualArrival'], "|", "Scheduled Departure:", response['CurrentStation']['ScheduleDeparture'], "|", "Actual Departure:", response['CurrentStation']['ActualDeparture'])
print("Train is at:", response['CurrentStation']['StationName'], "|", "Train is delayed by:", response['CurrentStation']['DelayInDeparture'], "\n")
#######################################################################################################
#######################################################################################################
def find_train(self):
"""
===> Doc String of the FUNCTION: find_train "
This Function is used to find the train between stations for a given date.
Date: 21st June 2019
Created By: Prashant Kumar
Input: Source Station Code
Destination Station Code
Output: Train Number, Train Name
From Station (from the station where the train starts), To Station (to the station where train goes.)
Source Departure Time, Destination Arrival Time
"""
# http://indianrailapi.com/api/v2/TrainBetweenStation/apikey/<apikey>/From/<From>/To/<To>
source_station = input("Enter the source station: ").upper()
dest_station = input("Enter the destination station: ").upper()
#date = input("Enter the date of journey: ")
find_train_url = "http://indianrailapi.com/api/v2/TrainBetweenStation/apikey/{}/From/{}/To/{}".format(api_key, source_station, dest_station)
response = requests.get(find_train_url)
response = response.json()
print("Total Number of Trains Found:", response['TotalTrains'])
for i in response['Trains']:
print("Train Number:", i['TrainNo'], "|", "Train Name:", i['TrainName'])
print("Source Station:", i['Source'], "--->", "Destination Station:", i['Destination'])
print("Departure from Source:", i['DepartureTime'], "---->", "Arrival at Destination:", i['ArrivalTime'])
print("Travel Time:", i['TravelTime'], "|", "Train Type:", i['TrainType'], "\n")
#######################################################################################################
#######################################################################################################
def train_arrival(self):
"""
===> Doc String of the FUNCTION: pnr_status "
This Function is used to find the number of trains arriving at a station for a given period of time.
Date: 21st June 2019
Created By: Prashant Kumar
Input: A valid Station Code
Time period in hours for which user wants to check (such as 2, 4)
Output: Train Number, Train Name
Scheduled Arrival time, Actual Arrival Time, Arrival time of Train delayed by.
Scheduled Departure time, Actual Departure Time, Departure time of Train delayed by.
"""
# http://indianrailapi.com/api/v2/LiveStation/apikey/<apikey>/StationCode/<StationCode>/hours/<Hours>/
station = input("Enter the station code for which you want to check: ").upper()
window_period = input("Enter the amount of time for which you want to check: ")
url = "http://indianrailapi.com/api/v2/LiveStation/apikey/{}/StationCode/{}/hours/{}/".format(api_key, station, window_period)
response = requests.get(url)
response = response.json()
for i in response['Trains']:
print(i['Number'], "|", i['Name'])
print(i['Source'], "|", i['Destination'])
print("Scheduled Arrival:", i['ScheduleArrival'], "|", "Expected Arrival:", i['ExpectedArrival'])
print("Scheduled Departure:", i['ScheduleDeparture'], "|", "ExpectedDeparture:", i['ExpectedDeparture'])
print("Delayed By:", i['DelayInDeparture'], "\n")
#######################################################################################################
#######################################################################################################
def cancelled_trains(self):
"""
===> Doc String of the FUNCTION: find_train "
This Function is used to find the trains that are cancelled for the given date.
Date: 21st June 2019
Created By: Prashant Kumar
Input: Date for which the user wants to check
Output: Train Number, Train Name (of the trains that are cancelled.)
Source Station name, destination Station Name
"""
# https://indianrailapi.com/api/v2/CancelledTrains/apikey/<apikey>/Date/<yyyyMMdd>
date = input("Enter the date for which you want to find cancelled train \n(in yyyymmdd format): ")
url = "https://indianrailapi.com/api/v2/CancelledTrains/apikey/{}/Date/{}".format(api_key, date)
response = requests.get(url)
response = response.json()
print("Total Number of Cancelled Trains: ", response['TotalTrain'], "\n")
for i in response['Trains']:
print(i['TrainNumber'], "|", i['TrainName'])
print(i['StartDate'], "|", i['TrainType'])
print(i['Source'], "--->", i['Destination'], "\n")
#######################################################################################################
#######################################################################################################
def diverted_trains(self):
"""
===> Doc String of the FUNCTION: find_train "
This Function is used to find the trains that are cancelled for the given date.
Date: 21st June 2019
Created By: Prashant Kumar
Input: Date for which the user wants to check
Output: Train Number, Train Name (of the trains that are cancelled.)
Source Station name, destination Station Name
"""
# https://indianrailapi.com/api/v2/DivertedTrains/apikey/<apikey>/Date/<yyyyMMdd>
date = input("Enter the date for which you want to find diverted train \n(in yyyymmdd format): ")
url = "https://indianrailapi.com/api/v2/DivertedTrains/apikey/{}/Date/{}".format(api_key, date)
response = requests.get(url)
response = response.json()
print("Total Number of Diverted Trains: ", response['TotalTrain'], "\n")
for i in response['Trains']:
print(i['TrainNumber'], "|", i['TrainName'])
print(i['StartDate'], "|", i['TrainType'])
print("Actual Route:", i['Source'], "--->", i['Destination'])
print("Diverted Route:", i['DivertedFrom'], "---->", i['DivertedTo'], "\n")
#######################################################################################################
#######################################################################################################
def station_location(self):
"""
===> Doc String of the FUNCTION: station_location "
This Function is used to find the location of the station on the map.
Date: 21st June 2019
Created By: Prashant Kumar
Input: Station Code for which the user wants to check
Output: Station Name, Station Code
URL of the Station Address.
"""
# http://indianrailapi.com/api/v2/StationLocationOnMap/apikey/<apikey>/StationCode/<StationCode>
station = input("Enter the station code for which you want to get the location URL: ").upper()
url = "http://indianrailapi.com/api/v2/StationLocationOnMap/apikey/{}/StationCode/{}".format(api_key, station)
response = requests.get(url)
response = response.json()
print(response['StationCode'], "|", response['StationName'])
print("Station Map Location URL:", response['URL'], "\n")
#######################################################################################################
#######################################################################################################
def coach_position(self):
"""
===> Doc String of the FUNCTION: coach_position "
This Function is used to find the position of coaches for a given train number.
Date: 21st June 2019
Created By: Prashant Kumar
Input: Train Number for which the user wants to check
Output: Train Number
Serial Number and Coach Name.
"""
# http://indianrailapi.com/api/v2/CoachPosition/apikey/<apikey>/TrainNumber/<TrainNumber>
train_no = input("Enter the train number for which you want to get the coach position: ")
url = "http://indianrailapi.com/api/v2/CoachPosition/apikey/{}/TrainNumber/{}".format(api_key, train_no)
response = requests.get(url)
response = response.json()
print(response['TrainNumber'])
for i in response['Coaches']:
print(i['SerialNo'], "|", i['Name'], "---->")
#######################################################################################################
Enquiry() |
import random
import time
#
# BUBBLE SORT
#
def bubble_sort(lista):
for i in range(len(lista) - 1):
for j in range(len(lista) - i - 1):
if lista[j] > lista[j + 1]:
lista[j], lista[j + 1] = lista[j + 1], lista[j]
#
# INSERTION SORT
#
def insertion_sort(lista):
for i in range(1, len(x)):
z = x[i]
j = i - 1
while j >= 0 and z < x[j]:
x[j + 1] = x[j]
j -= 1
x[j + 1] = z
#
# QUICK SORT
#
def quick_sort(vetor, ini, fim):
meio = (ini + fim) // 2
pivo = vetor[meio]
i = ini
j = fim
while i < j:
while vetor[i] < pivo: i += 1
while vetor[j] > pivo: j -= 1
if i <= j:
vetor[i], vetor[j] = vetor[j], vetor[i] # swap
i += 1
j -= 1
if j > ini: quick_sort(vetor, ini, j)
if i < fim: quick_sort(vetor, i, fim)
#
# MERGE SORT
#
def merge_sort(vetor, ini, fim):
if ini < fim:
meio = (ini + fim) // 2
merge_sort(vetor, ini, meio)
merge_sort(vetor, meio + 1, fim)
intercala(vetor, ini, meio, fim)
def intercala(vetor, ini, meio, fim):
esq = vetor[ini : meio + 1]
dir = vetor[meio + 1 : fim + 1]
esq.append(999) # sentinela
dir.append(999) # sentinela
i = j = 0
for k in range(ini, fim + 1):
if esq[i] <= dir[j]:
vetor[k] = esq[i]
i += 1
else:
vetor[k] = dir[j]
j += 1
#
# HEAP SORT
#
def heap_sort(vetor):
size = len(vetor)
# Constrói uma heap máxima (maxheap)
for i in range(size // 2 - 1, -1, -1):
heapfica(vetor, size, i)
# Extrai elementos um por um
for i in range(size - 1, 0, -1):
vetor[i], vetor[0] = vetor[0], vetor[i] # swap
heapfica(vetor, i, 0)
def heapfica(vetor, n, k):
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# 2 * k + 1 : filho esquerdo do nó k
# 2 * k + 2 : filho direito do nó k
# (k-1) / 2 : pai do nó k
# n / 2 : onde começam os nós folha
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
maior = k # Inicialmente assume pai como o maior
esq = 2 * k + 1
dir = 2 * k + 2
# Filho esquerdo existe e é maior que o pai
if esq < n and vetor[k] < vetor[esq]:
maior = esq
# Filho direito existe e é maior que o pai
if dir < n and vetor[maior] < vetor[dir]:
maior = dir
# Maior filho assume como pai
if maior != k:
vetor[k], vetor[maior] = vetor[maior], vetor[k] # swap
# Heapfica partindo da posição do maior encontrado
heapfica(vetor, n, maior)
###
n = 1000
x = random.sample(range(0, n), n)
tempo_i = time.time()
x.sort()
tempo_f = time.time()
print('Python Sort : {}'.format(tempo_f - tempo_i))
x = random.sample(range(0, n), n)
tempo_i = time.time()
bubble_sort(x)
tempo_f = time.time()
print('Bubble Sort : {}'.format(tempo_f - tempo_i))
x = random.sample(range(0, n), n)
tempo_i = time.time()
quick_sort(x, 0, len(x) - 1)
tempo_f = time.time()
print('Quick Sort : {}'.format(tempo_f - tempo_i))
x = random.sample(range(0, n), n)
tempo_i = time.time()
heap_sort(x)
tempo_f = time.time()
print('Heap Sort : {}'.format(tempo_f - tempo_i))
x = random.sample(range(0, n), n)
tempo_i = time.time()
insertion_sort(x)
tempo_f = time.time()
print('Insertion Sort: {}'.format(tempo_f - tempo_i))
x = random.sample(range(0, n), n)
tempo_i = time.time()
merge_sort(x, 0, len(x) - 1)
tempo_f = time.time()
print('Merge Sort : {}'.format(tempo_f - tempo_i))
|
import sqlite3
from myfields import myfields
conn = sqlite3.connect('mydatabase.db')
c = conn.cursor()
def insert_record(rec):
with conn:
c.execute("INSERT INTO My_Table VALUES (:field1, :field2, :field3)", {'field1': rec.field1, 'field2': rec.field2, 'field3': rec.field3})
def get_all():
c.execute("SELECT * FROM My_Table")
return c.fetchall()
def get_record_by_id(id_num):
c.execute("SELECT * FROM My_Table WHERE id=:id", {'id': id_num})
return c.fetchall()
def update_date(id_num, dateval):
with conn:
c.execute("""UPDATE My_table SET filed3 = :dateval
WHERE id = :id_num""", {'id': id_num, 'dateval': dateval})
def count_rows():
with conn:
c.execute("SELECT COUNT(*) FROM My_Table")
c.fetchall()
def remove_record(id_num):
with conn:
c.execute("DELETE from My_Table WHERE id = :id_num", {'id_num': id_num})
print(count_rows())
result = c.execute("SELECT * FROM My_Table")
#num_of_rows = result[0][0]
print(result)
all_records = get_all()
print(all_records)
recbyid = get_record_by_id(1)
print(recbyid) |
from nltk.corpus import stopwords
from nltk.tokenize import word_tokenize
import re
def dropStopWords(text):
text = re.sub("[^a-zA-Z]",' ',text)
text = text.replace(' x ','')
## text = text.replace(' ','')
word_list = text.split(' ')
filtered_words= word_list
## filtered_words = [word for word in word_list if word not in stopwords.words('english')]
filtered_words =[x for x in filtered_words if x!='']
return (" ".join(filtered_words))
|
# ==============================
# NAME
# DATE
# CLASS
# HOMEWORK NUMBER
# PROGRAM DESCRIPTION
# ==============================
import sys
# ==============================================
# Beginning of the ADD FREQUENCIES function
# ==============================================
def add_frequencies(d,file,remove_case):
f = open(file)
my_file_data=f.read()
string_length=len(my_file_data)
if remove_case == False:
for jj in "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ":
for i in range(string_length-1):
if my_file_data[i] == jj:
d.update({jj: d.get(jj)+1})
if remove_case == True:
for jj in "abcdefghijklmnopqrstuvwxyz":
for i in range(string_length-1):
if my_file_data[i] == jj or my_file_data[i] == jj.upper():
d.update({jj: d.get(jj)+1})
# ==============================================
# End of the ADD FREQUENCIES function
# ==============================================
# ==============================================
# Beginning of the MAIN function
# ==============================================
def main():
# ==============================================
# Set all command line variable to False
# ==============================================
cmd_c=False
cmd_z=False
cmd_l=False
cmd_variables=0
number_of_files=0
l_flag=0
# ==============================================
# Parse command line variables
# ==============================================
for x in range(len(sys.argv)):
if sys.argv[x] == "-c":
cmd_c=True
cmd_variables=cmd_variables+1
for x in range(len(sys.argv)):
if sys.argv[x] == "-z":
cmd_z=True
cmd_variables=cmd_variables+1
for x in range(len(sys.argv)):
if sys.argv[x] == "-l":
cmd_l=True
cmd_variables=cmd_variables+1
letters=sys.argv[x+1]
if cmd_l:
l_flag=1
for x in range(len(sys.argv)-cmd_variables-l_flag-1):
print("=================================")
# ==============================================
# Create EMPTY DICTIONARY
# ==============================================
d = {
"a": 0,
"b": 0,
"c": 0,
"d": 0,
"e": 0,
"f": 0,
"g": 0,
"h": 0,
"i": 0,
"j": 0,
"k": 0,
"l": 0,
"m": 0,
"n": 0,
"o": 0,
"p": 0,
"q": 0,
"r": 0,
"s": 0,
"t": 0,
"u": 0,
"v": 0,
"w": 0,
"x": 0,
"y": 0,
"z": 0,
"A": 0,
"B": 0,
"C": 0,
"D": 0,
"E": 0,
"F": 0,
"G": 0,
"H": 0,
"I": 0,
"J": 0,
"K": 0,
"L": 0,
"M": 0,
"N": 0,
"O": 0,
"P": 0,
"Q": 0,
"R": 0,
"S": 0,
"T": 0,
"U": 0,
"V": 0,
"W": 0,
"X": 0,
"Y": 0,
"Z": 0
}
add_frequencies(d,sys.argv[x+1+cmd_variables+l_flag],cmd_c)
# ==============================================
# Printing appropriate output
# ==============================================
if ((not cmd_c) and (not cmd_z) and (not cmd_l)):
for key, value in d.items():
print('"' + key + '",' + str(value))
if ((cmd_c) and (not cmd_z) and (not cmd_l)):
for key, value in d.items():
print('"' + key + '",' + str(value))
if ((not cmd_c) and (cmd_z) and (not cmd_l)):
for key, value in d.items():
if value != 0:
print('"' + key + '",' + str(value))
if ((cmd_c) and (cmd_z) and (not cmd_l)):
for key, value in d.items():
if value != 0:
print('"' + key + '",' + str(value))
if ((not cmd_c) and (not cmd_z) and (cmd_l)):
for key, value in d.items():
if key in letters:
print('"' + key + '",' + str(value))
if ((cmd_c) and (not cmd_z) and (cmd_l)):
for key, value in d.items():
if key in letters:
print('"' + key + '",' + str(value))
if ((not cmd_c) and (cmd_z) and (cmd_l)):
for key, value in d.items():
if key in letters and value != 0:
print('"' + key + '",' + str(value))
if ((cmd_c) and (cmd_z) and (cmd_l)):
for key, value in d.items():
if key in letters and value != 0:
print('"' + key + '",' + str(value))
main()
|
def deb_card(card_num: str):
if type (card_num) == str and card_num.isdigit() and len(card_num)==16:
return f'Номер вашей карты катрты : **** **** **** {card_num[-4:]}'
else:
return ValueError
print(deb_card(input('')))
|
# one
shopping = {
"castorama" : ['deska', 'gwoździe', 'taśma', 'młotek'],
"ikea" : ['szafka', 'swieca', 'garnek'],
"sklep modelarski" : ['model fiata 126p']
}
shopping["sklep papierniczy"] = ['ryza papieru']
all = 0
for shop in shopping:
all = all + len(shopping[shop])
print("Idę do", shop.capitalize(), "kupuję tu następujące rzeczy:", shopping[shop])
print(shopping.values())
print("W sumie kupuję", all, "produktów.")
|
# Introducción a Python
## Acerca de Python
Python es...
* **libre** – es software distribuible de código abierto
* **fácil de aprender** – tiene una sintaxis de lenguaje simple
* **fácil de leer** – no está atiborrada de signos de puntuación
* **fácil de manterner** – es modular para simplicidad
* **“baterias incluidas”** – provee una librería estándar grande para que sea fácil integrar con sus propios programas
* **interactivo** – tiene una terminal para arreglar y probar fragmentos de código
* **portable** – corre en una amplia variedad de plataformas de hardware y tiene la misma interface en todas las plataformas
* **interpretado** – no se requiere compilar el código
* **alto nivel** – tiene administración de memoria automática
* **extendible** – permite agregar módulos de bajo nivel al intérprete para personalización
* **versátil** – soporta tnato programs orientados a procesos como programación orientada a objetos (OOP)
* **flexible** – puede crear porgrams de consolas, aplicaciones con ventanas GUI (Graphical User Interface), y código CGI (Common Gateway Interface) para procesar datos de la web
## Python en las noticias
> The language’s two main advantages are its simplicity and flexibility. Its straightforward syntax and use of indented spaces make it easy to learn, read and share. Its avid practitioners, known as Pythonistas, have uploaded 145,000 custom-built software packages to an online repository. These cover everything from game development to astronomy, and can be installed and inserted into a Python program in a matter of seconds. This versatility means that the Central Intelligence Agency has used it for hacking, Google for crawling webpages, Pixar for producing movies and Spotify for recommending songs. Some of the most popular packages harness “machine learning”, by crunching large quantities of data to pick out patterns that would otherwise be imperceptible.
>
> Fuente: [The Economist, julio de 2018](https://www.economist.com/graphic-detail/2018/07/26/python-is-becoming-the-worlds-most-popular-coding-language)
> Python is not perfect. Other languages have more processing efficiency and specialised capabilities. C and C++ are “lower-level” options which give the user more control over what is happening within a computer’s processor. Java is popular for building large, complex applications. JavaScript is the language of choice for applications accessed via a web browser. Countless others have evolved for various purposes. But Python’s killer features—simple syntax that makes its code easy to learn and share, and its huge array of third-party packages—make it a good general-purpose language. **Its versatility is shown by its range of users and uses**.
>
> **For professions that have long relied on trawling through spreadsheets, Python is especially valuable**. Citigroup, an American bank, has introduced a crash course in Python for its trainee analysts. A jobs website, eFinancialCareers, reports a near-fourfold increase in listings mentioning Python between the first quarters of 2015 and 2018.
> Fuente: [The Economist, julio de 2018](https://www.economist.com/science-and-technology/2018/07/19/python-has-brought-computer-programming-to-a-vast-new-audience)

## El mercado lo demanda

Fuente: https://www.thinkful.com/blog/insights-on-the-data-science-job-market-analyzing-7k-data-science-job-descriptions/
## Descargando Python
La manera más fácil de obtener Python es descargarlo de Anaconda en https://www.anaconda.com/download/

* Hay dos versiones mayores de Python: 2 vs 3
* Asegúrese de descargar la versión 3.
## Ejecutando Python
Hay varias maneras de correr código de Python, dependiendo de lo que sea más conveniente en el momento. Muchas de las opciones pueden comenzarse desde *Anaconda Navigator*
, entre ellas:
1. en una terminal (command window)

2. en Jupyter QtConsole
Es una GUI de PyQt GUI que permite tener figuras incrustadas, edición de muchas líneas con resaltado de sintaxis, pistas de ayuda gráficas, y más.

3. en Jupyter Notebook
Es un ambiente de cuaderno computable interactivo basado en la web. Se edita y ejecutan documentos legibles para humanos mientras que se describe el análisis de los datos.

4. en Spyder
**S**cientific **PY**thon **D**evelopment **E**nvi**R**onment. Es una IDE poderosa, con edición avanzada, pruebas interactivas, correción y características de introspección.

5. en nteract
**nteract** es una excelente opción para trabajar con cuadernos de Jupyter, pues puede abrirlos sin necesidad de abrir Jupyter previamente. Es gratuito y puede descargarse del sitio [https://nteract.io/](https://nteract.io/).

6. Ejecutando Python en la nube
Una opción muy conveniente para correr programas de Python sin instalarlo en su máquina es [Google Colab](https://colab.research.google.com), el cual permite ejecutarlos en los servidores de Google. A la fecha utiliza la versión 3.6.9 de Python.

Por ejemplo, para ejecutar los cuadernos de Jupyter de este curso, puede cargarlos directamente desde mi repositorio de Github. Para ello, seleccione el menú **File >> Open notebook >> Github**, escriba **randall-romero** en el campo de búsqueda, y selecciones el repositorio EC4301.

## ¡Listos para empezar!
Un primer comando
print("Bienvenidos a este tutorial de Python") |
'''
Problem: Tower of Hanoi
Statement: Given an tower of height n, how do you move
the disks to a 3rd peg, making sure all disks
are in increasing size.
'''
class Tower:
def __init__(self, n):
self.one = [x for x in range(n)]
self.two = []
self.three = []
self.size = n
def pTowers(self):
print("---pTowers---")
print("One: ", self.one)
print("Two: ", self.two)
print("Three: ", self.three)
print()
def _verify_stack(self, stack):
return all(stack[i] < stack[i+1] for i in range(len(stack)-1))
def verify(self):
return self._verify_stack(self.one) and self._verify_stack(self.two) and self._verify_stack(self.three)
def hanoi(self, start, end, temp, amount):
if not self.verify():
self.pTowers()
assert False
if amount == 1:
end.append(start.pop())
else:
self.hanoi(start, temp, end, amount-1)
end.append(start.pop())
self.hanoi(temp, end, start, amount-1)
def solve(self):
self.hanoi(self.one, self.three, self.two, self.size)
t = Tower(4)
t.pTowers()
t.solve()
t.pTowers()
|
'''
Problem: Largest Non-Adjacent Sum
Statement: Given an input array x, return the largest possible sum of
non-adjacent elements in the array. Numbers can be 0 or
negative.
Example:
Input: [5,1,1,5]
Output: 10
Explanation:
5+5 = 10
'''
from typing import List
class Solution:
def largeSum(self, nums: List[int]) -> int:
# if the array is short
if len(nums) == 1:
return nums[0]
elif len(nums) == 2:
return max(nums[0], nums[1])
# intiialize constant-size DP array
prevMax = [nums[0], 0]
prevMax[1] = max(nums[0], nums[1])
# index and loop to calculate final maximum
ind = 2
while(ind < len(nums)):
newMax = max(prevMax[0] + nums[ind], prevMax[1], prevMax[0])
prevMax = [prevMax[1], newMax]
ind += 1
return prevMax[-1]
sum = Solution().largeSum([5, 1, 1, 5])
assert sum == 10
sum = Solution().largeSum([2, 4, 6, 2, 5])
assert sum == 13
|
#!/usr/bin/env python
# coding: utf-8
# In[23]:
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
csv_data_file=pd.read_csv('/home/greesh/Documents/verdatumcode/Democracy-Dictatorship_Index.csv')
data=csv_data_file.set_index('Regime')['Type'].to_dict()
democracy=[]
dictatorship=[]
count=0
for i in data.values():
if i== 'Democracy':
democracy.append(i)
number_of_democracy=len(democracy)
if i=='Dictatorship':
dictatorship.append(i)
number_of_dictatorship=len(dictatorship)
total_number=[]
total_number.append(number_of_democracy)
total_number.append(number_of_dictatorship)
plt.title('Democracy v/s Dictatorship in the world')
plt.xlabel('Type of government')
plt.ylabel('N.o of countries')
x = 1,2
plt.bar(1, height=total_number[0] ,color='yellow')
plt.bar(2, height=total_number[1], color='red')
plt.xticks(x, ['Democracy','Dictatorship'])
# In[ ]:
# In[ ]:
|
import pygame
class Snake:
n_added = 1 # Number of items to add to the snake when it lengthens
def __init__(self, length, x_max, y_max, step):
self.step = step
self.length = length # Initial length of the snake
self.x_max = x_max
self.y_max = y_max
self._image_surf = pygame.image.load("images/snake_mini.png").convert()
self.direction = "left"
self.x = [] # x positions of the snake's items
self.y = [] # y positions of the snake's items
for i in range(self.length):
self.x.append(int(x_max / 2) - (self.length - 1 - i) * self.step)
self.y.append(int(y_max / 2))
def update(self):
"""
Method to update the snake position
"""
# Update tail
for i in range(self.length - 1, 0, -1):
self.x[i] = self.x[i - 1]
self.y[i] = self.y[i - 1]
# Update head
if self.direction == "right":
self.x[0] += self.step
if self.direction == "left":
self.x[0] -= self.step
if self.direction == "up":
self.y[0] -= self.step
if self.direction == "down":
self.y[0] += self.step
def lengthen(self):
"""
Method to lengthen the snake when it has eaten a raspi
Its extended with self.n_added new items
:return:
"""
self.length += self.n_added
for i in range(self.n_added):
self.x.append(self.x[-1])
self.y.append(self.y[-1])
def move_right(self):
self.direction = "right"
def move_left(self):
self.direction = "left"
def move_up(self):
self.direction = "up"
def move_down(self):
self.direction = "down"
def has_eaten(self, raspi_x, raspi_y):
"""
Method to check whether the snake has eaten the raspi or not
:param raspi_x: x coordinate of the raspi
:param rapsi_y: y coordinate of the raspi
:return:
flag_eaten: True if the snake has eaten the raspi
"""
flag_eaten = self.x[0] == raspi_x and self.y[0] == raspi_y
return flag_eaten
def is_over(self, raspi_x, rapsi_y):
"""
# Method to know if the snake is over a raspi
:param raspi_x: x coordinate of the raspi
:param rapsi_y: y coordinate of the raspi
:return:
True if the snake if over the raspi
"""
return (raspi_x, rapsi_y) in list(zip(self.x, self.y))
def has_lost(self, walls):
"""
Method to know if the player has lost
- Either the snake touched the frame border
- Or it cut itself
:return:
flag_lost: True if player has lost
"""
# Find out if snake's head has touched the border
flag_lost_border = (
(self.x[0] > walls.x_max_inside - 1)
or (self.x[0] < walls.x_min_inside)
or (self.y[0] > walls.y_max_inside - 1)
or (self.y[0] < walls.y_min_inside)
)
# Find out if snake's has cut itself through
flag_lost_self_intersect = (self.x[0], self.y[0]) in list(
zip(
[self.x[i] for i in range(1, self.length)],
[self.y[i] for i in range(1, self.length)],
)
)
flag_lost = flag_lost_border or flag_lost_self_intersect
return flag_lost
def is_body_up(self):
body_is_up = any(
[
((self.y[0] - self.y[i]) == self.step) and (self.x[0] == self.x[i])
for i in range(1, self.length)
]
)
return body_is_up
def is_body_down(self):
body_is_down = any(
[
((self.y[0] - self.y[i]) == -self.step) and (self.x[0] == self.x[i])
for i in range(1, self.length)
]
)
return body_is_down
def is_body_left(self):
body_is_left = any(
[
((self.x[0] - self.x[i]) == self.step) and (self.y[0] == self.y[i])
for i in range(1, self.length)
]
)
return body_is_left
def is_body_right(self):
body_is_right = any(
[
((self.x[0] - self.x[i]) == -self.step) and (self.y[0] == self.y[i])
for i in range(1, self.length)
]
)
return body_is_right
def render(self, display_surf):
for x, y in zip(self.x, self.y):
display_surf.blit(self._image_surf, (x, y))
|
class Car:
def __init__(self, name, year):
self.name = name
self.year = year
def display(self):
print("My car model name is {} and buld in year {}".format(
self.name, self.year))
c1 = Car("Toyota", 25)
c1.display()
|
from tkinter import *
import pandas
import random
BACKGROUND_COLOR = "#B1DDC6"
current_card ={}
to_learnDict = {}
#reading data from pandas
try:
data = pandas.read_csv("data/words_to_learn.csv")
except FileNotFoundError:
data = pandas.read_csv("data/french_words.csv")
to_learnDict = data.to_dict(orient="records")
else:
#converting csv-Data to a dict
to_learnDict = data.to_dict(orient="records")
def next_card():
global current_card, flip_timer
screen.after_cancel(flip_timer)
current_card= random.choice(to_learnDict)
canvas.itemconfig(french_label,text="French")
current_word = current_card['French']
canvas.itemconfig(frenchMeaning_label, text=current_word)
canvas.itemconfig(card_bg, image= card_front)
flip_timer = screen.after(3000,func=flip_card)
def flip_card():
canvas.itemconfig(french_label,text="English",fill = 'white')
card_front.config(file = "images/card_back.png")
current_word = current_card['English']
canvas.itemconfig(frenchMeaning_label, text=current_word,fill = 'white')
canvas.itemconfig(card_bg, image=card_back)
def is_know():
to_learnDict.remove(current_card)
data = pandas.DataFrame(to_learnDict)
data.to_csv("data/words_to_learn.csv",index=False)
next_card()
screen = Tk()
screen.title("Flash Card")
screen.config(bg= BACKGROUND_COLOR,padx = 50,pady = 50)
flip_timer= screen.after(3000,func=flip_card)
canvas = Canvas(width = 800, height = 525, highlightthickness = 0,bg=BACKGROUND_COLOR)
card_front = PhotoImage(file= "images/card_front.png")
card_back = PhotoImage(file= "images/card_back.png")
card_bg = canvas.create_image(400,263, image= card_front)
canvas.grid(row = 0, column = 0,columnspan = 2)
french_label = canvas.create_text(400,150,text="",font= ("Arial", 40,"italic"))
frenchMeaning_label = canvas.create_text(400,263,text="",font= ("Arial", 60,"bold"))
right_img = PhotoImage(file= "images/right.png")
known_btn = Button(image = right_img,command = is_know)
known_btn.grid(row = 1 ,column = 1)
wrong_img = PhotoImage(file= "images/wrong.png")
unknown_btn = Button(image = wrong_img,command = next_card)
unknown_btn.grid(row = 1 ,column = 0)
next_card()
screen.mainloop() |
#!/usr/bin/env python3
# Given 2 strings, how many characters must you delete to make the two strings anagrams of each other
import math
import os
import random
import re
import sys
from collections import Counter
def makeAnagram(a, b):
count_a = Counter(a)
count_b = Counter(b)
count_a.subtract(count_b)
return sum(abs(i) for i in count_a.values())
if __name__ == '__main__':
fptr = open(os.environ['OUTPUT_PATH'], 'w')
a = input()
b = input()
res = makeAnagram(a, b)
fptr.write(str(res) + '\n')
fptr.close()
|
# -*- coding: utf-8 -*-
"""
Created on Wed Nov 20 12:50:26 2019
@author: Ahmad ALaarg
"""
"""
1-Write a Python program to accept 2 numbers from the users and print the greatest
"""
#-----------------------------------------------------
"""
x = int(input('enter your first number '))
y = int(input('enter your sucend number '))
if (x > y):
print(x)
else:
print(y)
"""
#-----------------------------------------------------
"""
2-Write a Python program to create the multiplication table for a specific number that is
accepted from the user
"""
#-----------------------------------------------------
"""
z = int(input ('plese enter the number : '))
i = 1
for i in range (10):
print (z, '*' , i + 1 ,'=' , z * (i + 1 ))
"""
#-----------------------------------------------------
"""
3. Write a Python program to construct the following pattern, using a nested for loop
"""
#-----------------------------------------------------
"""
i = 0
for i in range (6) :
print('*'*i )
for i in range (6,0,-1) :
print('*'*i )
"""
#-----------------------------------------------------
# 4
"""
letters =["x","y","z","a","b","c"]
for i in letters :
if i == "a" :
continue
elif i =="c" :
break
print(i)
"""
"""
output
x
y
z
b
"""
#-----------------------------------------------------
# 5
"""
for x in range (12,25,3) :
print (x)
"""
"""
output
12
15
18
21
24
"""
#-----------------------------------------------------
# 6
"""
i = 1
while i < 6 :
print (i)
if i == 3 :
break
i += 1
"""
"""
output
1
2
3
"""
#-----------------------------------------------------
# 7
"""
num = int(input("Enter a number :"))
total=0
for d in range(num):
total=total+d+1
print("the total is : ",total)
"""
#-----------------------------------------------------
# 8
"""
num = int(input("the num : "))
print ("even") if(num%2==0) else print ("odd")
"""
#-----------------------------------------------------
#9
for a in range(1,10,1):
for b in range(9-a):
print (" ",end=" ")
for c in range(0,a,1):
print (c+1,end=" ")
for d in range(a-1,0,-1):
print (d,end=" ")
print()
for a in range(9,0,-1):
for b in range(10-a):
print (" ",end=" ")
for c in range(1,a,1):
print (c,end=" ")
for d in range(a-1,1,-1):
print (d-1,end=" ")
print()
#-----------------------------------------------------
#10
"""
while True:
try:
n = input("Please enter an integer number : ")
n = int(n)
break
except ValueError:
print("No valid integer! Please try again ...")
print("Great, you successfully entered an integer!")
"""
#-----------------------------------------------------
#11
"""
try:
a=3
if a<4:
b=a/(a-3)
print("value of b = ",b)
except(ZeroDivisionError,NameError):
print("\nError occurred and Handled")
"""
#-----------------------------------------------------
#-----------------------------------------------------
|
# -*- coding: utf-8 -*-
"""
Created on Thu Nov 21 09:37:20 2019
@author: Ahmad ALaarg
"""
"""
s1= 'hello orange academy'
print ( s1 )
print ( s1[0 ])
print ( s1[ 2])
print ( s1[2:10])
print ( s1[5:])
print ( s1 * 2)
print ( s1.capitalize ())
print ( s1.upper ())
print (s1.center(20 ))
print (s1.replace('Orange', 'Amman '))
print (' world strip()')
s2='#'.join([' hello','Orange'])
print(s2)
"""
#-----------------
#Lists Practice
"""
Assume the following list list 1 1,20 1,0,1000 ],
1 append to list 1 the following list 2 ( list 2 23,546 ] )
2 find len , min, max, sum, sorted of the updated list 1 and print the results
3 Apply sort and pop and print the list
"""
# Lists Practice
"""
list1 = [1,20,-1,0,1000]
list2 = [23,5460]
list1.extend(list2)print (list1)
print(len(list1))
print(min(list1))
print(max(list1))
print(sum(list1))
print(sorted(list1))
"""
#Tuples
"""
my_list =['a','b']
t1 = ("Apple ",) # Note , is for one item
t2 = t1 + (1,2,3 ) + tuple (my_list)
print(t2)
print(t2 [0])
print(t2 [1:4])
"""
#Sets
"""
s1 = { 1,2,3,4,5,6}
s2 ={ 2,4,6 }
print ( s1 | s2 ) # OR
print ( s1 & s2 ) # AND
print ( s1 - s2 ) # SUPTRACT
print ( s1 ^ s2 ) # OR # in s 1 or s 2 but not in both
"""
#Dictionary
info = {
"firstName": "Ahmad",
"lastName": "Alaarg",
"year": 1996
}
print(info)
x = info["year"]
print(x)
for x in info :
print (x)
print (info[x])
|
# NLP assignment 3 - POS Tagging
# Austin Beggs - 3/8/2019
# The goal of this program was to take in training data and apply POS tags to a text file
# based on probabilities of tags from the training data. Actual training input was included in
# the pos-test and pos-train text files. To run this program you must include both of these
# in the arguments. The algorithm used to solve this was to take in the training data, process
# the data into dictionaries, calculate the probability of tags and apply to the test data. The
# output was then compared to the key given using a 2nd program called scorer.py
from sys import argv
import re
import numpy as np
#arguments
train = str(argv[1])
test = str(argv[2])
#fixing some of the training text
File = open(train, 'r')
trainingText = File.read()
trainingText = re.sub(r'\[ ', ' ', trainingText)
trainingText = re.sub(r' \]', ' ', trainingText) #removing brackets and \n
trainingText = trainingText.replace('\n', ' ')
trainingText = re.sub(r'/\.', '/. <e>/<e> <s>/<s>', trainingText) #start/end tags
trainingText = re.sub(r'\|([^ ]+)', '', trainingText) #removing whats to the right of |
trainingText = re.split(r'\s+', trainingText)
#creating dictionaries and variables
wordCount = dict()
tagCount = dict()
tagGivenWord = dict()
tagGivenPrevTag = dict()
prevWord = "<s>"
prevTag = "<s>"
word = ""
tag = ""
#looping through the training text adding the words and tags to dictionaries
for _ in trainingText:
temp = re.split('/',_)
if(len(temp) < 2):
continue
#special case with //\ would be split weird
if(len(temp) > 2):
temp[0] = temp[0] + temp[1]
temp[1] = temp[2]
word = temp[0]
tag = temp[1]
#checking if word has been added yet
if word not in wordCount.keys():
wordCount[word] = 1
else:
wordCount[word] += 1
#checking if tag has been added yet
if tag not in tagCount.keys():
tagCount[tag] = 1
else:
tagCount[tag] += 1
#word hasnt been seen
if word not in tagGivenWord.keys():
tagGivenWord[word] = {}
tagGivenWord[word][tag] = 1
#word has been seen
else:
if tag not in tagGivenWord[word].keys():
tagGivenWord[word][tag] = 1
else:
tagGivenWord[word][tag] += 1
# last tag hasnt been seen
if prevTag not in tagGivenPrevTag.keys():
tagGivenPrevTag[prevTag] = {}
tagGivenPrevTag[prevTag][tag] = 1
# last tag has been seen
else:
if tag not in tagGivenPrevTag[prevTag].keys():
tagGivenPrevTag[prevTag][tag] = 1
else:
tagGivenPrevTag[prevTag][tag] += 1
prevTag = tag
prevWord = word
File.close()
#fixing up the file to apply pos tags
File2 = open(test, 'r')
testingText = File2.read()
testingText = re.sub(r'\[ ', ' ', testingText)
testingText = re.sub(r' \]', ' ', testingText)
testingText = testingText.replace('\n', ' ')
testingText = re.sub(r'(\.\s)', '. <e> <s>', testingText)
testingText = re.split(r'\s+', testingText)
tempDict = testingText
lastTag = "<s>"
output = []
# For every word in testing data
for currentWord in testingText:
if(currentWord.isspace()):
continue
bestTagProbability = 0
bestTag = ""
if(currentWord in tagGivenWord.keys()):
# For every tag
for aTag in tagGivenWord[currentWord].keys():
taglist = tagGivenWord[currentWord].keys() #for debugging
x = tagGivenWord[currentWord][aTag]
y = tagCount[aTag]
if (aTag not in tagGivenPrevTag[lastTag].keys()):
tagGivenPrevTag[lastTag][aTag] = 1
u = tagGivenPrevTag[lastTag][aTag]
v = tagCount[lastTag]
probabilityOfCurrentTag = (x/y)*(u/v)
#comparing the probability of current tag to highest probability so far, then storing both values
if ( probabilityOfCurrentTag > bestTagProbability):
bestTagProbability = ((tagGivenWord[currentWord][aTag])/(tagCount[aTag]))*((tagGivenPrevTag[lastTag][aTag])/(tagCount[lastTag]))
bestTag = aTag
lastTag = bestTag
if(lastTag != "<e>" ) & (lastTag != "<s>"):
output.append(currentWord + "/" + bestTag)
else:
output.append(currentWord+"/NN")
for _ in output:
print(_)
|
start_list = [5, 3, 1, 2, 4]
square_list = []
for list in start_list:
quadrado = list ** 2
square_list.append(quadrado)
square_list.sort()
print square_list
|
from random import randint #Importar random de randint
#Variavel responsavel pelo tabuleiro
board = []
#Laco para criar uma grade 5x5, inicializado com 'O's em todas as posicoes do tabuleiro
for x in range(5):
board.append(["O"] * 5)
#Mostra se o tabuleiro foi criado
#print board
#Funcao identificada para personalisar a exibicao do tabuleiro esteticamente
def print_board(board):
for row in board:
print " ".join(row)
print "Vamos jogar Batalha Naval!"
print_board(board)
# Agora vamos ocultar as informacoes de onde esta o navio de forma randomizada, auxiliada pelo import da linha 3
def random_row(board):
return randint(0, len(board) - 1)
def random_col(board):
return randint(0, len(board[0]) - 1)
#Adicionar quatro novas variaveis, 2 primeiras para colocar o navio
ship_row = random_row(board)
ship_col = random_col(board)
#Depurando o local real nesse momento do navio, comentar as duas linhas que refere-se a resultado do jogo
print ship_row
print ship_col
#Laco para fazer a contagem e limite de quatro tentativas
for turn in range(4):
#Adicionar duas variaveis para fazer a procura do navio, fazendo com que o usuario digite o local do navio
guess_row = int(raw_input("Adivinhe a Linha:"))
guess_col = int(raw_input("Adivinhe a Coluna:"))
# Fazendo o teste se o usuarios acertar e exibir mensagem de acerto
if guess_row == ship_row and guess_col == ship_col:
print "Parabens, voce afundou meu couracado!"
# Parar a funcao de tentativas caso usuario acerte o navio
break
# Quando usuario errar o navio
else:
# Se os valores inseridos pelo usuario estam fora do alcance da batalha
if (guess_row < 0 or guess_row > 4) or (guess_col < 0 or guess_col > 4):
print "Oops, isso nao e nem mesmo no oceano."
# Verificando se o usuario ja tentou o mesmo lugar
elif(board[guess_row][guess_col] == "X"):
print "Voce ja tentou esse."
else:
print "Voce errou meu couracado!"
# Marcar todos os locais digitados com "X"
board[guess_row][guess_col] = "X"
# Se ele completar o ciclo de 4x e errando 4x eh Game Over
if turn == 3:
print "Game Over"
# Mostra qual eh a volta do "for"
print "Turn", turn + 1
print turn
print_board(board)
|
import time
def bubbleSort(array, drawArr):
if len(array) == 1:
return array
l = len(array)-1
while l != 0:
for i in range(l):
if array[i] > array[i+1]:
array[i], array[i+1] = array[i+1], array[i]
drawArr(array, ["pink" if x == i or x == i +
1 else "dark red" for x in range(len(array))])
time.sleep(0.3)
l = l-1
drawArr(array, ["pink" for _ in range(len(array))])
def insertionSort(array, drawArr):
for i in range(1, len(array)):
x = array[i]
j = i
while x < array[j-1] and j > 0:
array[j] = array[j-1]
drawArr(array, ["pink" if n == i or n ==
j else "dark red" for n in range(len(array))])
time.sleep(0.3)
j = j-1
array[j] = x
drawArr(array, ["pink" for _ in range(len(array))])
def selectionSort(array, drawArr):
for j in range(len(array)):
m = 0
x = array[j]
for i in range(j, len(array)):
drawArr(array, ["pink" if n == i or n ==
j else "dark red" for n in range(len(array))])
time.sleep(0.3)
if array[i] < x:
x = array[i]
m = i
if m != 0:
array[m], array[j] = array[j], array[m]
drawArr(array, ["pink" for _ in range(len(array))])
def quickSort(array, drawArr):
helper(array, 0, len(array) - 1, drawArr)
def helper(array, start, end, drawArr):
if start >= end:
return
pivot = start
left = start + 1
right = end
while left <= right:
if array[left] > array[pivot] and array[right] < array[pivot]:
array[left], array[right] = array[right], array[left]
drawArr(array, ["pink" if n == left or n == right or n ==
pivot else "dark red" for n in range(len(array))])
time.sleep(0.3)
if array[left] <= array[pivot]:
drawArr(array, ["pink" if n == left or n == right or n ==
pivot else "dark red" for n in range(len(array))])
time.sleep(0.3)
left += 1
if array[right] >= array[pivot]:
drawArr(array, ["pink" if n == left or n == right or n ==
pivot else "dark red" for n in range(len(array))])
time.sleep(0.3)
right -= 1
array[pivot], array[right] = array[right], array[pivot]
leftIsSmaller = (right - 1) - start < end - (right + 1)
if leftIsSmaller:
helper(array, start, right - 1, drawArr)
helper(array, right + 1, end, drawArr)
else:
helper(array, right + 1, end, drawArr)
helper(array, start, right - 1, drawArr)
drawArr(array, ["pink" for _ in range(len(array))])
def heapSort(array, drawArr):
buildHeap(array, drawArr)
sortBound = len(array)
for i in range(sortBound):
array[0], array[sortBound - 1] = array[sortBound - 1], array[0]
drawArr(array, ["pink" if n == 0 or n == sortBound -
1 else "dark red" for n in range(len(array))])
sortBound = sortBound - 1
siftDown(array, 0, drawArr, sortBound)
drawArr(array, ["pink" for _ in range(len(array))])
def buildHeap(array, drawArr):
firstParentInd = (len(array) - 2) // 2
for i in range(firstParentInd, -1, -1):
drawArr(array, [
"pink" if n == firstParentInd else "dark red" for n in range(len(array))])
siftDown(array, i, drawArr, arrLen=len(array))
def siftDown(array, curInd, drawArr, arrLen):
while 2*curInd + 1 < arrLen:
childOneInd = 2*curInd + 1
if 2*curInd + 2 < arrLen:
childTwoInd = 2*curInd + 2
if array[childOneInd] > array[childTwoInd]:
indToCompare = childOneInd
else:
indToCompare = childTwoInd
else:
indToCompare = childOneInd
if array[curInd] < array[indToCompare]:
array[curInd], array[indToCompare] = array[indToCompare], array[curInd]
drawArr(array, ["pink" if n == curInd or n ==
indToCompare else "dark red" for n in range(len(array))])
time.sleep(0.2)
curInd = indToCompare
|
#PYTHON DICTIONARY
import randomfunctions
books ={
"novels": "things fall a part",
"science" : "Physics text",
"motivational" : "Richest man in babylon",
}
print(books["novels"])
#updating the values
books["motivational"] = "think big"
print(books)
#printing the values of dict using a loop
for x in books.values():
print(x)
print(len(books))
#changeing to a list
mylist = list(books.keys())
print(type(mylist))
print(mylist)
print(mylist[2])
for x in mylist:
print(x)
print("EMPLOYEE DETAILS")
employee = {
"name" : "musa",
"dept" : "IT",
"degree" : "BSC",
"state" : "Kano",
"hobby" : "chess",
}
print(employee)
# new details
employee["name"] = str(input())
employee["dept"] = str(input())
employee["degree"] = str(input())
employee["state"] = str(input())
employee["hobby"] = str(input())
for x,y in employee.items():
print(x,":",y)
#A MODULE CREATED
randomfunctions.nameteller(employee["name"],employee["state"],employee["degree"]) |
"""
CODILITY DEMO
A non-empty array A consisting of N integers is given. The array contains an odd number
of elements, and each element of the array can be paired with another element that
has the same value, except for one element that is left unpaired.
For example, in array A such that:
A[0] = 9 A[1] = 3 A[2] = 9
A[3] = 3 A[4] = 9 A[5] = 7
A[6] = 9
the elements at indexes 0 and 2 have value 9,
the elements at indexes 1 and 3 have value 3,
the elements at indexes 4 and 6 have value 9,
the element at index 5 has value 7 and is unpaired.
Write a function:
class Solution { public int solution(int[] A); }
that, given an array A consisting of N integers fulfilling the above conditions, returns the value of the unpaired element.
For example, given array A such that:
A[0] = 9 A[1] = 3 A[2] = 9
A[3] = 3 A[4] = 9 A[5] = 7
A[6] = 9
the function should return 7, as explained in the example above.
"""
def unpaired(Arey):
arraylen = len(Arey)
uppperbound = arraylen - 1
lowerbound = 0
mid = arraylen // 2
for i in range(0, arraylen,2):
for j in range(0, arraylen,2):
if Arey[i] == Arey[j] and i != j:
return False
else:
return Arey[i]
thelist = [9, 3, 9, 3, 9, 7, 9]
thelist.sort()
result = unpaired(thelist)
print(result)
# The sum of two odd numbers are even e'g 3 = 3 = 6 , 9+ 9 = 18 , 21 + 21 = 42
# Thus we find from the array the sum of number of occurrence of an element if it is even or odd
# TESTING EVEN- NESS
# if EVEN : using the modulo division of 2 remainder == 0 solution is not found
# if ODD : using the modulo division of 2 remainder == 1 solution is found
def oddoccurence( odds):
arraylen = len(odds)
for i in odds:
#this checks for number of time a particular element occurs in the list
if odds.count(i) % 2 == 1:
return i
else:
continue
thelist = [9, 3, 9, 3, 9, 7, 9]
result = oddoccurence(thelist)
print(result)
|
#mutli-level inheritance
class Animals:
def livinfthings(self):#TOP LEVEVL PARENT CLASS
print("Animals are living things")
class Dogs(Animals):
def response(self):
print("Animals like dogs bark")
class puppies(Dogs): #CHILD CLASS
def nutrition(self): # METHOD
print("Animals like dogs have puppies that loves taking milk")
#METHOD OVERIDING
def livinfthings(self):
print("overiding: puppies are animals ")
bingo = puppies() #OBJECT
bingo.nutrition()
bingo.response()
bingo.livinfthings()
|
#basic python
import datetime
today = datetime.date.today()
print("Today date is :", today)
print (' ')
'''Loopoing - control flow in python '''
#WHILE
i = 0
while (i <= 5):
print ('The value of while loop :', i)
if(i == 5):
break
else:
i += 1
#FOR
for i in range(5):
print ('This is for loop:',i)
for j in range(0,10,2):
print ('for loop skips 2 elem:',j)
print('---------------------------------------------------------')
''' Multiline comment -
This is LIST examples '''
primes = list()
rmv = list()
alphabets = ['A', 'B', 'C']
print('This is list:', alphabets)
print('This is 1st element :', alphabets[0])
# Check if element exist and append
if 'D' not in alphabets:
alphabets.append('D')
print('This is list:', alphabets)
nxt = ['E','F','G']
alphabets.extend(nxt)
alphabets.extend(('I','J'))
print('This is list with nxt elem:', alphabets)
abcd = alphabets[0:4]
print('This is list with sliced elem:', abcd)
rmv = alphabets.pop(8)
print('remove with position using popped:', rmv,'. This is new list:', alphabets)
alphabets.remove('I')
print('remove (I) with value, new list:', alphabets)
print('This is empty prime list:', primes)
''' Multiline comment -
This is TUPLE examples '''
tup = ('red','blue','green')
print ("This is tuple: ", tup)
print ("This is 1st elem in tuple: ", tup[0])
print ("Slicing tuple: ", tup[1:2], "note the comma")
|
totalValidPasswords = 0
with open('advent2020/day2/day2input.txt', 'r') as file:
for testPassword in file.readlines():
rangeAndLetter = testPassword.split(':')[0]
letter = rangeAndLetter[-1]
num1 = int(rangeAndLetter.split('-')[0])
num2 = int(rangeAndLetter.split('-')[1].strip(letter))
password = testPassword.split(':')[1]
if (password[num1] == letter and password[num2] != letter) or (password[num2] == letter and password[num1] != letter):
totalValidPasswords += 1
print (totalValidPasswords)
|
from typing import List
class Solution:
def moveZeroes(self, nums: List[int]) -> None:
first_zero_index = None
for i in range(len(nums)):
if nums[i] == 0:
if first_zero_index is None:
first_zero_index = i
elif first_zero_index is not None:
nums[i], nums[first_zero_index] = nums[first_zero_index], nums[i]
first_zero_index += 1
if __name__ == "__main__":
solver = Solution()
nums = [0, 1, 0, 3, 12]
solver.moveZeroes(nums)
print(nums)
|
from typing import List, Optional, Tuple
Interval = Tuple[int, int]
def overlap(intx: Interval, inty: Interval) -> Optional[Interval]:
xs, xe = intx
ys, ye = inty
if xs <= ye and ys <= xe:
return max(xs, ys), min(xe, ye)
class Solution:
def intervalIntersection(
self,
firstList: List[Interval],
secondList: List[Interval],
) -> List[Interval]:
ans = []
j = 0
secondList.append((float("inf"), float("inf")))
for i in range(len(firstList)):
flag = False
while j < len(secondList):
intx, inty = map(tuple, [firstList[i], secondList[j]])
into = overlap(intx, inty)
if into:
ans.append(into)
flag = True
elif flag:
j -= 1
break
elif intx < inty:
break
j += 1
return ans
if __name__ == "__main__":
solver = Solution()
print(
solver.intervalIntersection(
firstList=[[0, 2], [5, 10], [13, 23], [24, 25]],
secondList=[[1, 5], [8, 12], [15, 24], [25, 26]],
)
)
print(solver.intervalIntersection(firstList=[[1, 7]], secondList=[[3, 10]]))
print(
solver.intervalIntersection(
firstList=[[4, 6], [7, 8], [10, 17]],
secondList=[[5, 10]],
)
)
print(
solver.intervalIntersection(
firstList=[[0, 5], [12, 14], [15, 18]],
secondList=[[11, 15], [18, 19]],
)
)
|
from typing import List
from string import ascii_lowercase
class Solution:
def letterCasePermutation(self, s: str) -> List[str]:
stack = [""]
s = s.lower()
while stack:
w = stack.pop()
if len(w) == len(s):
yield w
else:
if s[len(w)] in ascii_lowercase:
stack.append(w + s[len(w)])
stack.append(w + s[len(w)].upper())
else:
stack.append(w + s[len(w)])
if __name__ == "__main__":
solver = Solution()
print(list(solver.letterCasePermutation("a1b1")))
|
from typing import List, Optional
# Definition for a binary tree node.
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def preorderTraversal(self, root: Optional[TreeNode]) -> List[int]:
if root:
CALL = 0
HANDLE = 1
stack = [(CALL, root)]
while stack:
action, data = stack.pop()
if action == CALL:
if data.right:
stack.append((CALL, data.right))
if data.left:
stack.append((CALL, data.left))
stack.append((HANDLE, data.val))
else:
yield data
|
from typing import Optional
class MyQueue:
def __init__(self):
self._left = []
self._right = []
def _rebalance(self):
right = self._right
take = max(len(right) >> 1, 1)
self._left = right[:take][::-1]
self._right = right[take:]
def push(self, x: int) -> None:
self._right.append(x)
def pop(self) -> Optional[int]:
if not self._left:
self._rebalance()
return self._left.pop() if self._left else None
def peek(self) -> Optional[int]:
if not self._left:
self._rebalance()
return self._left[-1] if self._left else None
def empty(self) -> bool:
return (len(self._left) + len(self._right)) == 0
# Your MyQueue object will be instantiated and called as such:
# obj = MyQueue()
# obj.push(x)
# param_2 = obj.pop()
# param_3 = obj.peek()
# param_4 = obj.empty()
|
from typing import List
from collections import Counter
Board = List[List[str]]
VALID_CHARS = ".123456789"
class Solution:
def isValidSudoku(self, board: Board) -> bool:
def validate(xs: List[str]) -> bool:
seen = set()
for x in xs:
if x not in VALID_CHARS or (x != "." and x in seen):
return False
seen.add(x)
return True
return (
all(validate(board[i][j] for j in range(9)) for i in range(9))
and all(validate(board[i][j] for i in range(9)) for j in range(9))
and all(
validate(
board[i + offseti][j + offsetj] for i in range(3) for j in range(3)
)
for offseti in range(0, 9, 3)
for offsetj in range(0, 9, 3)
)
)
if __name__ == "__main__":
solver = Solution()
board = [
["5", "3", ".", ".", "7", ".", ".", ".", "."],
["6", ".", ".", "1", "9", "5", ".", ".", "."],
[".", "9", "8", ".", ".", ".", ".", "6", "."],
["8", ".", ".", ".", "6", ".", ".", ".", "3"],
["4", ".", ".", "8", ".", "3", ".", ".", "1"],
["7", ".", ".", ".", "2", ".", ".", ".", "6"],
[".", "6", ".", ".", ".", ".", "2", "8", "."],
[".", ".", ".", "4", "1", "9", ".", ".", "5"],
[".", ".", ".", ".", "8", ".", ".", "7", "9"],
]
print(solver.isValidSudoku(board))
|
from typing import Any, Iterable, Optional
# Definition for a binary tree node.
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def iter_tree(root: Optional[TreeNode]) -> Iterable[Any]:
CALL, HANDLE = 0, 1
call_stack = [(CALL, root)]
while call_stack:
action, node = call_stack.pop()
if action == CALL:
if node:
if node.right:
call_stack.append((CALL, node.right))
call_stack.append((HANDLE, node))
if node.left:
call_stack.append((CALL, node.left))
else:
yield node.val
class Solution:
def findTarget(self, root: Optional[TreeNode], k: int) -> bool:
nums = list(iter_tree(root))
i, j = 0, len(nums) - 1
while i < j:
s = nums[i] + nums[j]
if s < k:
i += 1
elif s > k:
j -= 1
else:
return True
return False
|
from typing import List
class Solution:
def minimumTotal(self, triangle: List[List[int]]) -> int:
if triangle:
min_path = triangle[-1].copy()
for i in range(len(triangle) - 2, -1, -1):
for j in range(len(triangle[i])):
min_path[j] = triangle[i][j] + min(min_path[j], min_path[j + 1])
return min_path[0]
else:
return -1
if __name__ == "__main__":
solver = Solution()
print(solver.minimumTotal(triangle=[[2], [3, 4], [6, 5, 7], [4, 1, 8, 3]]))
print(solver.minimumTotal(triangle=[[-10]]))
|
from typing import Optional
from itertools import repeat
# Definition for a Node.
class Node:
def __init__(
self,
val: int = 0,
left: "Node" = None,
right: "Node" = None,
next: "Node" = None,
):
self.val = val
self.left = left
self.right = right
self.next = next
class Solution:
def connect(self, root: Optional[Node]) -> Optional[Node]:
CALL, HANDLE = 0, 1
call_stack = [(CALL, [root])]
return_stack = []
while call_stack:
action, old_nodes = call_stack.pop()
if old_nodes:
if action == CALL:
childrens = []
for node in old_nodes:
if node:
childrens.append(node.left)
childrens.append(node.right)
call_stack.append((HANDLE, old_nodes))
call_stack.append((CALL, childrens))
else:
childrens = (
iter(return_stack.pop()) if return_stack else repeat(None)
)
new_nodes = []
prev = None
for node in old_nodes:
if node:
nl = next(childrens)
nr = next(childrens)
new_node = Node(node.val, nl, nr)
new_nodes.append(new_node)
if prev:
prev.next = new_node
prev = new_node
else:
new_nodes.append(None)
return_stack.append(new_nodes)
return return_stack[-1][0]
|
from collections import OrderedDict
class Solution:
def firstUniqChar(self, s: str) -> int:
seen = set()
ordered_map = OrderedDict()
for i in range(len(s) - 1, -1, -1):
char = s[i]
if char not in seen:
ordered_map[char] = i
elif char in ordered_map:
ordered_map.pop(char)
seen.add(char)
return ordered_map.popitem()[1] if ordered_map else -1
if __name__ == "__main__":
solver = Solution()
print(solver.firstUniqChar(s="leetcode"))
print(solver.firstUniqChar(s="loveleetcode"))
print(solver.firstUniqChar(s="acaadcad"))
|
# Autor:Andersson Sanabria
# Fecha:15/04/2021
# Version:1.0
# Nombre del Proyecto:Ejercicio #9
# ----------------------Ejercicio #9-----------------------------
# Escribir un programa que solicite ingresar su nombre y edad, luego los almacene,
# y los muestre en pantalla, mediante la funcion f-string, luego utilizar un condicional
# if para saber si es mayor de edad.
if __name__=='__main__':
nombre = str(input('Ingrese su nombre: '))
edad = int(input('Ingrese su edad: '))
print(f"Hola, my nombre es {nombre} y mi edad es {edad}")
if(edad>=18):
print(f'{nombre} Es mayor de edad')
else:
print(f'{nombre} No es mayor de edad') |
def primos(n):
es_prim=True
if n % 1 == 0:
for values in range(2,n-1):
if n % values==0:
es_prim=False
return es_prim
if __name__=='__main__':
n=int(input('escribe un numero: '))
primo=primos(n)
if primo==True:
print('El numero {} es primo'.format(n))
else:
print('El numero {} no es primo'.format(n)) |
# Autor:Andersson Sanabria
# Fecha:28/04/2021
# Version:1.0
# Nombre del Proyecto:Ejercicio #7
# ----------------------Ejercicio #7-----------------------------
# Escribí un programa que solicite al usuario que ingrese cuántos shows musicales
# ha visto en el último año y almacene ese número en una variable. A continuación
# mostrar en pantalla un valor de verdad (True o False) que indique si el usuario
# ha visto más de 3 shows.
if __name__=='__main__':
shows = int(input('Ingrese la cantidad de shows musicales que ha visto en el último año: '))
masdetres = False
print(masdetres >= 3)
|
class PaymentTypes():
def __init__(self):
self.paymentTypes = {
"Efectivo": 10,
"Cheque": 11,
"CreditCard local": 12,
"CreditCard online": 13
}
def paymentTypesIs(self, types):
if types in self.paymentTypes.keys():
if types == list(self.paymentTypes.keys())[0]:
types = self.paymentTypes[types]
return types
elif types == list(self.paymentTypes.keys())[1]:
types = self.paymentTypes[types]
return types
elif types == list(self.paymentTypes.keys())[2]:
types = self.paymentTypes[types]
return types
elif types == list(self.paymentTypes.keys())[3]:
types = self.paymentTypes[types]
return types
else:
return {"Error":500,"Mensaje":"El tipo de transaccion no es valida"}
|
import re
import pandas as pd
import time
import datetime
def StringToDatetime(s):
"""
Check whether the string s is a time format string.
return datetime or s
Example: '2014/02/03' return '%Y/%m%d'
'2014-02-03 00:00:00' return '%Y-%m-%d %H:%M:%S'
"""
if type(s) != str and type(s) != unicode:
return s
if type(s) == str:
s = unicode(s)
mapFormat = {
u'^\s*\d{4}-\d{2}-\d{1,2}\s*\d{1,2}:\d{2}:\d{2}\s*$': '%Y-%m-%d %H:%M:%S',
u'^\s*\d{4}-\d{1,2}-\d{1,2}\s*$': '%Y-%m-%d',
u'^\s*\d{4}/\d{1,2}/\d{1,2}\s*\d{2}:\d{2}:\d{2}\s*$': '%Y/%m/%d %H:%M:%S',
u'^\s*\d{4}/\d{1,2}/\d{1,2}\s*$': '%Y/%m/%d'
}
for k, v in mapFormat.items():
if re.search(k, s) != None:
return datetime.datetime.strptime(s,v)
return s
def DfStringToDatetime(data):
"""
convert pandas.DataFrame columns from time string format to datetime type format
"""
if type(data) != pd.DataFrame:
return data
for col in data.columns:
data[col] = data[col].apply(StringToDatetime)
return data
|
# -*- coding:UTF-8 -*-
import random
import pprint
from copy import deepcopy
pp = pprint.PrettyPrinter(width=20)
A = [[1,2,3],
[2,3,3],
[1,2,5]]
B = [[1,2,3,5],
[2,3,3,5],
[1,2,5,1]]
#生成一个r行c列矩阵
def random_matrix(r,c):
m = [[0]*c for row in range(r)]#初始化r行r列的0矩阵
for e in m:
for i in range(len(e)):
e[i] = random.randint(1,10)
return m
m1 = random_matrix(2,3)
m2 = random_matrix(3,4)
m3 = random_matrix(4,4)
print 'm1 = ',m1
print 'm2 = ',m2
print 'm3 = ',m3
# 创建一个4*4的单位矩阵
def unit_matrix(r):
m = [[0]*r for row in range(r)]#初始化r行r列的0矩阵
for i in range(r):
m[i][i] = 1
return m
I = unit_matrix(4)
print I
# 返回矩阵的行数和列数
def shape(M):
return len(M),len(M[0])
#矩阵中每个元素四舍五入到特定小数数位
def matxRound(M, decPts=4):
for e in M:
for i in range(len(e)):
e[i] = round(e[i], decPts)
# return M
pass
# print matxRound(I, decPts=4)
a = [1,2,3]
b = [4,5,6]
zipped = zip(a,b)
print zipped
print zip(*zipped)
#计算矩阵的转置
def transpose(M):
return map(list, zip(*M))
return
print transpose(m1)
#计算矩阵乘法 AB,如果无法相乘则返回None
def matxMultiply(A, B):
ra = shape(A)[0]
ca = shape(A)[1]
rb = shape(B)[0]
cb = shape(B)[1]
if ca == rb:
m = [[0]*cb for row in range(ra)]
for i in range(ra):
for j in range(cb):
for k in range(ca):
m[i][j] += A[i][k]*B[k][j]
return m
else:
pass
print 'm1m2 = ', matxMultiply(m1,m2)
print 'm1m3 = ', matxMultiply(m1,m3)
print '测试1.2 返回矩阵的行和列---------------------'
pp.pprint(B)
print (shape(B))
print '测试1.3 每个元素四舍五入到特定小数数位---------------------'
C = [[1.0001,2.000002,3.000003,4.04040404,5.55555555,6.1616161616]]
pp.pprint(C)
matxRound(C)
pp.pprint(C)
print '测试1.4 计算矩阵的转置-----------------------'
pp.pprint(B)
pp.pprint (transpose(B))
print '测试1.5 计算矩阵乘法AB,AB无法相乘-----------------------'
B = transpose(B)
pp.pprint(A)
pp.pprint(B)
pp.pprint (matxMultiply(A,B))
print '测试1.5 计算矩阵乘法AB,AB可以相乘-----------------------'
B = transpose(B)
pp.pprint(A)
pp.pprint(B)
pp.pprint (matxMultiply(A,B))
#构造增广矩阵,假设A,b行数相同
def augmentMatrix(A, b):
a = deepcopy(A)
for i in range(len(a)):
a[i].append(b[i][0])
return a
a = [['a11','a12'],['a21','a22']]
# b = [['b1'],['b2']]
# print augmentMatrix(a,b)
# print a
# print b
# TODO r1 <---> r2
# 直接修改参数矩阵,无返回值
def swapRows(M, r1, r2):
M[r1],M[r2] = M[r2],M[r1]
pass
# TODO r1 <--- r1 * scale, scale!=0
# 直接修改参数矩阵,无返回值
def scaleRow(M, r, scale):
if scale == 0:
raise ValueError
else:
for i in range(len(M[r])):
M[r][i] = M[r][i]*scale
pass
# TODO r1 <--- r1 + r2*scale
# 直接修改参数矩阵,无返回值
def addScaledRow(M, r1, r2, scale):
for i in range(len(M[r1])):
M[r1][i] += M[r2][i] * scale
pass
pp.pprint(A)
addScaledRow(A, 0, 1 ,3)
pp.pprint(A)
# TODO 实现 Gaussain Jordan 方法求解 Ax = b
def gj_Solve(A, b, decPts=4, epsilon = 1.0e-16):
res = [[0] for row in A] # 用于存储计算结果
rA = shape(A)[0]
rb = shape(b)[0]
if rA != rb: # 检查A,b是否行数相同
return None
else:
s = 0 # 用于储存忽略行变换的次数,此次数与行数相等时,说明得到了结果
Ab = augmentMatrix(A, b) # 构造增广矩阵Ab
j = 0
while j < (shape(Ab)[1]):
c = [] # 用于储存当前列主对角线及以下元素
for i in range(j, shape(Ab)[0]):
c.append(abs(Ab[i][j])) # 对元素取绝对值
# print '第{0}列主对角线及以下元素绝对值的列表为{1}'.format(j, c)
m = max(c) # 获得c中的最大值
# print '第{0}列的最大值为{1}'.format(j, m)
# print 'm:', m
# print 'i:', i
# print 'j:', j
r = c.index(max(c)) + j # 获得绝对值最大的元素所在的行
if m <= epsilon:
return None
elif m == 1.0 and r == j:
s += 1
j += 1
# print 's+1'
pass
else:
# print '第{0}列最大值所在的行为{1}'.format(j, r)
swapRows(Ab, j, r) # 使用第一个行变换,将绝对值最大值所在行交换到对角线元素所在行(行c)
# pp.pprint(Ab)
scale = 1.0/Ab[j][j] # 第j行第j列元素的乘子
# print '第二个行变换的scale是:', scale
scaleRow(Ab, j, scale) # 使用第二个行变换,将列c的对角线元素缩放为1
# print '第二个行变换的结果是:'
# pp.pprint(Ab)
for k in range(shape(Ab)[0]): # 多次使用第三个行变换,将列c的其他元素消为0
if k == j:
pass
else:
addScaledRow(Ab, k, j, -Ab[k][j]) # 使用第三个行变换,将列c的其他元素消为0
# print '第{0}次使用第三个行变换'.format(k)
# pp.pprint(Ab)
j = 0
s = 0
# print 's:', s
if s == shape(Ab)[0]:
break
matxRound(Ab, decPts) # 对增广矩阵元素进行四舍五入到特定小数位
resc = shape(Ab)[0]
for x in range(shape(Ab)[0]):
res[x][0] += Ab[x][resc]
# print s
return res
a = [[1,3,1],[2,1,1],[2,2,1]]
b = [[11],[8],[10]]
print gj_Solve(a,b)
print '测试奇异矩阵的结果---------------------\n'
A = [[1,0,4],[0,1,0],[0,0,0]]
b = [[1],[2],[3]]
pp.pprint(A)
print '\n'
pp.pprint(b)
print '\n'
print gj_Solve(A, b)
print '\n'
print '测试非奇异矩阵的结果---------------------\n'
A = [[1,3,1],[2,1,1],[2,2,1]]
b = [[11],[8],[10]]
pp.pprint(A)
print '\n'
pp.pprint(b)
print '\n'
print '求解 x 使得 Ax = b\n'
x = gj_Solve(A, b)
pp.pprint(x)
print '\n'
print '计算 Ax \n'
Ax = matxMultiply(A, x)
pp.pprint(Ax)
print '\n'
print '比较 Ax 与 b \n'
def compare(A, B):
if A == B:
return True
else:
return False
print compare(Ax,b)
# TODO 实现线性回归
def linearRegression(points):
X = [[points[i][0],1] for i in range(len(points))]
Y = [[points[i][1]]for i in range(len(points))]
XT = transpose(X)
A = matxMultiply(XT, X)
b = matxMultiply(XT, Y)
h = gj_Solve(A, b)
m = h[0]
b = h[1]
return m, b
# TODO 构造线性函数
m = 2
b = 4
# TODO 构造 100 个线性函数上的点,加上适当的高斯噪音
gs = [random.gauss(0,1) for i in range(100)] # 产生100个服从标准正态分布的数
# print gs
x = [random.uniform(-10,10) for i in range(100)]
y = [m*x[i] + b + gs[i] for i in range(100)]
# print x
# print y
points = map(list,zip(x, y))
# print points
print linearRegression(points) |
# ================================================
# Hangman Game
# ================================================
# Here's a hangman game made by Vincent J. U.
# How it works : the hidden words are saved in variable:words in which is randomly copied from variable:collection.
# user's answer will be saved in variable:s which is a list, variable:i for counting how many mistakes have been
# done ( as hangman consists of 7 characters so there 7 is the maximum number of attempts allowed ).
# variable:attempt is just a mark for the first user's input, while variable:ulang is a bool will be False
# if the user's answer matches the hidden word, input's answer will be saved in variable:c
# Feel free to change the codes if there are more efficient way and please let me know!
# Thankyou very much!
import random
collection = ("crocodile","triceratops","llama","dragontail","monster","garlic","dinosaurus","jackfruit","penguin")
words = collection[random.randint(0,len(collection)-1)] #
i=0
s = list('')
ulang = True
attempt = 1
for j in range (0,len(words)):
s+="_"
print("".join(s))
while(i<7 and ulang == True):
c = str(input("Enter a word: "))
if(c in words):
for j in range(0,len(words)):
if(words[j]==c):
s[j]=c
answer = "".join(s)
print(answer)
if(answer == words):
print("Yes! You're right!")
ulang = False
else:
i+=1
print("Wrong! ",7-i,"chance(s) left")
if(i==7):
print("Game Over! The answer is [",words,"]") |
print("Welcome! type any number.")
print("type \"quit\" to exit")
if exit != 0:
loop=0
loop = 1
while loop == 1:
x = input("--> ")
if x != "quit" :
x = int(x) #converts to integer
if x > 0:
print("input is greater than 0!")
if x < 100:
print("input is also less than 100!")
if x == 10:
print("input is 10!")
if x < 0:
print("input is less than 0!")
if x == 0:
print("input is zero!")
if x == quit:
exit = 1
|
#!/bin/python3
#print string
print ("strings and things")
print ('hello0o0o')
print (''' hello
this is a multi line string''')
print ("this is "+" a string")
print ('\n') # new line
#math
print ("math time")
print (5+5) #add
print (5-5) #subtract
print (5*5) #multiply
print (5/5) #division
print (5+5-5*5/5)
print (5 ** 2) # exponents
print (5 % 2) #modulo
print (5 // 3) #number without leftover
print ("fun with titles and vars")
#variables
quote = "live laugh love"
print(len(quote)) #length
print(quote.upper()) #uppercase
print(quote.lower()) #lowercase
print(quote.title()) #title
name = "browski"
age = 32 #int
gpa = 3.5 #float
print (int(age))
print (int(29.9)) #does not round
#concatenations + types
print ("my name is " + str(name) + " and i am " + str(age) + " years old ")
print ('\n') #new line
age += 1
print (age)
birthday = 1
age += birthday
print (age)
#functions
print ("now , some functions ")
def who_am_i():
name = "browski"
age = 32
print ("my name is " + str(name) + " and i am " + str(age) + " years old ")
who_am_i()
#adding in parameters
def add_one_hundred(num):
print(num + 100)
add_one_hundred(100)
#add in multiple parameteres
def add(x,y):
print(x + y)
add(7,7)
add(100,20)
#using return
def multiply(x,y):
return x * y
print(multiply(7,7))
def square_root(x):
return x ** .5
print(square_root(64))
print ('\n') #new line
#function for new line lulz
def nl():
print ('\n')
nl
#boolean expressions (true or false)
#boolean expressions (true or false)
print("boolean expressions")
bool1 = True
bool2 = 3*3 == 9
bool3 = False
bool4 = 3*3 != 9
print(bool1,bool2,bool3,bool4)
print(type(bool1))
bool5 = "True"
print(type(bool5))
#relation + Bool operators
nl
greater_than = 7 > 5
less_than = 5 < 7
greater_than_equal_to = 7 >= 7
less_than_equal_to = 7 <= 7
print(greater_than, less_than,greater_than_equal_to, less_than_equal_to)
test_and = (7 > 5) and (5 < 7) # one false makes it all false
test_or = (7 > 5) or (5 < 7) #only both false makes it false
test_not = not True # will be false
print(test_and)
nl
#conditional statements
print("conditionals statements")
def soda(money):
if money >= 2:
return "You've got yo self a soda bruh!!!"
else:
return "no diabetes bruh!!"
print(soda(3))
print(soda(1))
nl
def alcohol(age,money):
if (age >= 18) and (money >= 5):
return "we gettin litttt!"
elif (age >=18) and (money < 5):
return "come back wit doh"
elif (age < 18) and (money >= 5):
return "nice try kiddo"
else:
return "u broke kiddie"
print(alcohol(18,5))
print(alcohol(18,4))
print(alcohol(17,4))
print(nl)
#lists (has brackets not parentheses)
print("lists have brackets")
movies = ["where harry met sally", "the hanvover", "flowers", "titanic"]
print(movies[0])
# numbering starts at 0, not 1
print(movies[0:2])
#you have to call the next number if you want the exact number
#slicing (up to but not including)
print(movies[1:]) #pulls starting from 1 till the end
print(movies[:1]) #pulls first item?
print(movies[-1])#pulls last item
print(len(movies))
movies.append("jaws")
print(movies)
movies.pop() #no number means rm last items
print(movies)
movies.pop(1)
print(movies)
movies = ["where harry met sally", "the hanvover", "flowers", "titanic"]
person = ["heath", "jake", "leah", "jef"]
combined = zip(movies, person)
print(list(combined))
#the above does a list in a list -- list inception,
#tuples (has parentheses and are immutable - cant change)
print("tuples have parentheses and canNOT change!")
grades = ("A", "B", "C", "D", "F")
print(grades[1]) #will print B
#looping
print("for loops - start to finish of iterate:")
vegetables = ["cucumber", "spinach", "carrot"]
for x in vegetables:
print(x)
print("while loops - exe as long as True:")
i = 1
while i < 10: #while true, do smthing
print(i)
i += 1
|
a = 10
b = 20
def display():
print("Hello to the functions")
display()
def add():
a = 10
b = 20
c = a + b
print("Addition is",c)
add()
def sub():
c = a - b
print("Subtraction is",c)
sub() |
import time
start = time.time()
a = []
for i in range(0,100000000):
a.append(i)
##print(a)
end = time.time()
print("Time", end-start)
|
a = [1,2,3,"Hello",10.5,True,120.00000]
print(a)
print(a[-1])
print(a[::-1])
print(a[:-1])
b = "Hello","Python"
print(b)
|
def add(num_1,num_2):
return num_1 + num_2
def sub(num_1,num_2):
return num_1 - num_2
def div(num_1,num_2):
return num_1 / num_2
def mul(num_1,num_2):
return num_1 * num_2
def mainFunction():
while True:
print("""
1. Add
2. Sub
3. Div
4. Mul
""")
user_choice = input("Enter your choice : ")
num_1 = int(input("Enter first number : "))
num_2 = int(input("Enter second number : "))
# if user_choice == "1":
# print(add(num_1,num_2))
# elif user_choice == "2":
# print(sub(num_1,num_2))
# elif user_choice == "3":
# print(div(num_1,num_2))
# else:
# print(mul(num_1,num_2))
to_calc = {
"1" : add,
"2" : sub,
"3" : div,
"4" : mul
}
print(to_calc.get(user_choice)(num_1,num_2))
mainFunction() |
def division():
a = int(input("Enter a number: "))
b = a/2
try:
assert(b > 0 ), "Try Again"
print("Result is ",b)
except AssertionError as er:
print(er)
division()
|
a = input("Enter first number : ")
b = input("Enter Second number : ")
c = int(a) + int(b)
print("Sum is",c) |
thislist=["hello man",12548696,"We go out"]
print(type(thislist))
print(thislist[0])
print(thislist)
print("######Writing diff #######")
for items in thislist:
print(items)
#lets see operations in a list
print("###### operations in the list #######")
#Change the second item:
thislist[1]=365489652
print(thislist)
#check if the item included
if "We dont go out" in thislist:
print("Yes found")
else:
thislist.append("Cherry")
print(thislist)
#adding the list where we want
thislist.insert(0,"Apple")
print(thislist)
thislist.remove("hello man")
print(thislist)
# we can use pop() to remove as well
thislist.pop(2)
print(thislist)
#we can use del to delete all the list or some element
del thislist[0]
print(thislist)
#The clear() method empties the list:
thislist.clear()
print(thislist)
#Using the list() constructor to make a List:
thislist = list(("orange", "lemon", "cherry"))
print(thislist)
"""
List Methods
Python has a set of built-in methods that you can use on lists.
Method Description
append() Adds an element at the end of the list
clear() Removes all the elements from the list
copy() Returns a copy of the list
count() Returns the number of elements with the specified value
extend() Add the elements of a list (or any iterable), to the end of the current list
index() Returns the index of the first element with the specified value
insert() Adds an element at the specified position
pop() Removes the element at the specified position
remove() Removes the item with the specified value
reverse() Reverses the order of the list
sort() Sorts the list
""" |
def search(arr, left, right):
obj = {}
for i in arr:
if i not in obj:
obj[i] = 1
else:
obj[i] += 1
tar = max(obj.values())
if tar > len(arr)/2:
return 1
return 0
n = int(input())
num_list = []
num_list.append(list(map(int,input().split())))
i = search(num_list[0],0,n)
print(i) |
x = 3
y = 10
if x == y:
print('X and Y are equal')
else:
if x > y:
print('X is greater than Y')
else:
print('X is less than Y')
###############################################
hours = input('Enter hours : ')
rate = input('Enter rate : ')
if float(hours) > 40:
pay = float(hours) * float(rate) * 1.5
else:
pay = float(hours) * float(rate)
print('Pay : ' + str(pay))
# Exercise 2 Rewrite your pay program using try and except so that your program handles non-numeric input gracefully
# by printing a message and exiting the program. The following shows two executions of the program:Enter Hours: 20
#Enter Rate: nine
#Enter Hours: forty
#Error, please enter numeric input
hours = input('Enter Hours')
rate = input('Enter Rate')
try:
if float(hours) > 40:
print('Pay : ', float(hours) * float(rate) * 1.5)
else:
print('Pay : ', float(hours) * float(rate))
except:
print("Please enter a number")
'''Exercise 3 Write a program to prompt for a score between 0.0 and 1.0. If the score is out of range print an error.
If the score is between 0.0 and 1.0, print a grade using the following table:Score Grade
>= 0.9 A
>= 0.8 B
>= 0.7 C
>= 0.6 D
< 0.6 F
Enter score: 0.95
A
Enter score: perfect
Bad score
Enter score: 10.0
Bad score
Enter score: 0.75
C
Enter score: 0.5
F
'''
score = input('Please insert score')
try:
if float(score) <= 1.0 and float(score) >= 0.9:
print('A')
elif float(score) < 0.9 and float(score) >= 0.8:
print('B')
elif float(score) < 0.8 and float(score) >= 0.7:
print('C')
elif float(score) < 0.7 and float(score) >= 0.6:
print('D')
elif float(score) < 0.6:
print('F')
elif float(score) > 1.0:
print('Bad Score')
except:
print('Bad Score')
|
class Node():
def __init__(self, data):
self.data = data
self.next = None
def __str__(self):
return str(self.data)
class LinkedList():
def __init__(self):
self.head = None
self.tail = None
def addNode(self, data):
temp = Node(data)
if self.head == None:
self.head = temp
self.tail = temp
else:
self.tail.next = temp
self.tail = temp
def removeNode(self,data):
# If deleting first node, update head
if self.head.data == data:
self.head = self.head.next
else:
current = self.head
while current.next != None:
if current.next.data == data:
# If deleting the last node, update tail
if current.next.next == None:
self.tail = current
current.next = current.next.next
break
else:
current = current.next
def printList(self):
current = self.head
while current != None:
print(current)
current = current.next
# With Dictionary - O(n) Time, O(n) Space
def removeDups(self):
hash = {}
current = self.head
while current != None:
if current.data not in hash:
hash[current.data] = 0
hash[current.data] += 1
current = current.next
for key in hash:
while hash[key] > 1:
hash[key] -= 1
self.removeNode(key)
# Without Temporary Buffer - O(n^2) Time - O(1) Space
def removeDups2(self):
i = self.head
j = self.head
while i != None:
while j.next != None:
if i.data == j.next.data:
j.next = j.next.next
else:
j = j.next
i = i.next
j = i
test1 = LinkedList()
test1.addNode(1)
test1.addNode(1)
test1.addNode(2)
test1.addNode(2)
test1.addNode(3)
test1.addNode(3)
test1.removeDups2()
test1.printList()
|
import random
sides = 0
rolls = 0
roll_count = 0
print("This program is a simple dice roll program.")
input("press enter to continue...")
sides = int(input("How many sides do you want the dice to have? "))
rolls = int(input("How many dice do you want to roll? "))
while roll_count < rolls:
print(random.randint(1, sides))
roll_count += 1
|
# Поработайте с переменными, создайте несколько, выведите на экран,
# запросите у пользователя несколько чисел и строк и сохраните в переменные, выведите на экран.
a = "a"
b = 1
c = True
print(a)
print(b)
print(c)
d = input("Введите число ")
print(f"Введенное число {d}")
e = input("Введите строку ")
print("Введенная строка {}".format(e))
|
import itertools
import random
m_list = []
t_list = []
for i in itertools.count(97):
m_list.append(random.randint(i, 122))
if len(m_list) > 5:
print(m_list)
break
for j in itertools.cycle(m_list):
t_list.append(chr(j))
if len(t_list) > 2 * len(m_list):
print(t_list)
break
# 6. Реализовать два небольших скрипта:
# а) итератор, генерирующий целые числа, начиная с указанного,
# б) итератор, повторяющий элементы некоторого списка, определенного заранее.
# Подсказка: использовать функцию count() и cycle() модуля itertools.
# Обратите внимание, что создаваемый цикл не должен быть бесконечным.
# Необходимо предусмотреть условие его завершения.
# Например, в первом задании выводим целые числа, начиная с 3, а при достижении числа 10 завершаем цикл.
# Во втором также необходимо предусмотреть условие, при котором повторение элементов списка будет прекращено.
|
# Пользователь вводит строку из нескольких слов, разделённых пробелами.
# Вывести каждое слово с новой строки.
# Строки необходимо пронумеровать.
# Если в слово длинное, выводить только первые 10 букв в слове.
text = input("Опишите себя: ")
list = text.split()
print("Вы утверждаете, что: ")
for i in range(len(list)):
print(f"{i}. {list[i][:10]}")
|
import random
# Направления
DIRS = ("Лево", "Право", "Назад")
class Car:
def __init__(self, speed, color, name, is_police):
self.speed = speed
self.color = color
self.name = name
self.is_police = is_police
def go(self):
print(f"{self.name} поехала")
def stop(self):
print(f"{self.name} остановилась")
def turn(self, direction):
print(f"{self.name} повернула {direction}")
def show_speed(self):
print(f"Текущаяя скорость {self.name} - {self.speed}")
class TownCar(Car):
_speed_limit = 60
def show_speed(self):
print(f"Текущаяя скорость {self.name} - {self.speed}")
if self.speed > self._speed_limit:
print(f"Превышение скорости для {self.name}")
class SportCar(Car):
pass
class WorkCar(Car):
_speed_limit = 40
def show_speed(self):
print(f"Текущаяя скорость {self.name} - {self.speed}")
if self.speed > self._speed_limit:
print(f"Превышение скорости для {self.name}")
class PoliceCar(Car):
def __init__(self, speed, color, name, is_police, car):
super().__init__(speed, color, name, is_police)
self.purpose = car
def go(self):
print(f"{self.name} выдвинулся за {self.purpose.name}")
work1 = WorkCar(42, "Белый", "Грузовик", False)
work2 = WorkCar(30, "Синий", "Камаз", False)
work1.go()
work2.go()
work2.show_speed()
work1.show_speed()
police1 = PoliceCar(120, "Черный", "PoliceCar1", True, work1)
police1.go()
work1.turn(random.choice(DIRS))
police1.turn(random.choice(DIRS))
# 4. Реализуйте базовый класс Car.
# У данного класса должны быть следующие атрибуты: speed, color, name, is_police (булево).
# А также методы: go, stop, turn(direction),
# которые должны сообщать, что машина поехала, остановилась, повернула (куда).
# Опишите несколько дочерних классов: TownCar, SportCar, WorkCar, PoliceCar.
# Добавьте в базовый класс метод show_speed, который должен показывать текущую скорость автомобиля.
# Для классов TownCar и WorkCar переопределите метод show_speed.
# При значении скорости свыше 60 (TownCar) и 40 (WorkCar) должно выводиться сообщение о превышении скорости.
# Создайте экземпляры классов, передайте значения атрибутов.
# Выполните доступ к атрибутам, выведите результат.
# Выполните вызов методов и также покажите результат.
|
class MComplex:
def __init__(self, x: float, y: float):
self.x = x
self.y = y
def __add__(self, other):
return MComplex(self.x + other.x, self.y + other.y)
def __mul__(self, other):
# (x1x2 - y1y2) + (x1y2 + x2y1)i
x = self.x * other.x - self.y * other.y
y = self.x * other.y + other.x * self.y
return MComplex(x, y)
def __str__(self):
return f"{self.x} {self.y}i"
com1 = MComplex(1, 2)
com2 = MComplex(3, 4)
print(com1 + com2)
print(com1 * com2)
# 7. Реализовать проект «Операции с комплексными числами».
# Создайте класс «Комплексное число»,
# реализуйте перегрузку методов сложения и умножения комплексных чисел.
# Проверьте работу проекта, создав экземпляры класса (комплексные числа)
# и выполнив сложение и умножение созданных экземпляров.
# Проверьте корректность полученного результата.
|
"""
Veti primi un numar intreg de la tastatura.
Va trebui sa spuneti daca acel numar este palindrom, folosind tipul de date
boolean (True, False)
Observatii:
- palindrom: numarul este acelasi de la stranga la dreapta,
si de la dreapta la stanga
exemplu:
Veti primi: 12321
Veti printa: True
Veti primi: 1232
Veti printa: False
"""
x = int(input())
is_palindrom = True
#transform the int into a list using list comprehension
num_list = [int(i) for i in str(x)]
for n in range(int(len(num_list) / 2)):
if num_list[n] != num_list[len(num_list) - n - 1]:
is_palindrom = False
if is_palindrom:
print(True)
else:
print(False) |
"""
Finding a Motif in DNA
"""
import fileinput
line_list = []
for line in fileinput.input("rosalind_subs.txt"):
line_list.append(line.strip())
dna_string = line_list[0]
dna_substring = line_list[-1]
#get 1st position and position - length of the substring
for x in range(0, len(dna_string)-len(dna_substring)):
if dna_string[x] == dna_substring[0]:
if dna_string[x: x + len(dna_substring)] == dna_substring:
print x + 1,
|
# 암호걸린 PDF 파일 불러오기
import PyPDF2
pdfFile = open('encrypted.pdf', 'rb')
pdfReader = PyPDF2.PdfFileReader(pdfFile)
#값을 붙여넣을 빈 객체를 생성
pdfWriter = PyPDF2.PdfFileWriter()
# 암호를 입력하지 않으면 에러가 발생합니다.(암호:rosebud)
pdfReader.decrypt('rosebud')
for pageNum in range(pdfReader.numPages):
pdfWriter.addPage(pdfReader.getPage(pageNum))
pdfReader.numPages
print(pdfReader.numPages,"페이지")
print("=======================================================")
pageObj = pdfReader.getPage(9)
pageObj.extractText()
print(pageObj.extractText())
|
#!/usr/bin/env python3
import sys
import glob
import os
# Read multiple text files
inputPath = sys.argv[1]
output_file = sys.argv[2]
for input_file in glob.glob(os.path.join(inputPath,'*.txt')):
print(os.path.basename(input_file))
print("-------------------------------")
with open(input_file, 'r', newline='') as filereader:
with open(output_file, 'a', newline='') as filewriter:
for row in filereader:
filewriter.write(row)
|
age = input("생후 몇개월: ")
age = int(age)
if 0 <= age <= 1 :
print("결핵 접종")
if 0 <= age <= 2 :
print("B형 간염 접종")
if 2 <= age <= 6 :
print("파상풍 접종")
if 2 <= age <= 15 :
print("폐렴구균접종")
|
field = [["-" for j in range(3)] for i in range(3)] #предупреждаю код ужасен)) не знаю как улучшить(
def find_tire():
check = 0
for row in field:
for elem in row:
if elem == "-":
check += 1
return check
def win(x):
for i in range(len(field) - 1):
if field[i][0] == field[i][1] == field[i][2] == x:
return True
if field[0][i] == field[1][i] == field[2][i] == x:
return True
if field[0][0] == field[1][1] == field[2][2] == x:
return True
if field[0][2] == field[1][1] == field[2][0] == x:
return True
return False
def field_output():
print(" 1 2 3")
n_row = 1
for row in field:
print(n_row, end=" ")
for elem in row:
print(elem, end=' ')
print()
n_row += 1
return None
def change_field(n_m, value): # хотел сделать через декоратор, но так как у меня одна ф-я подумал что все проверки лучше сделать в ней
if any([n_m[0] < 1, n_m[1] < 1]): # обработка значений < 1, если ввести 0 или меньше строку или столбец питон в обратную сторону считает, поэтому нужно)
print("Некорректно! Попробуйте снова =)")
return False
if field[n_m[0] - 1][n_m[1] - 1] != "-":
print("Место занято! Попробуйте снова")
return False
else:
field[n_m[0] - 1][n_m[1] - 1] = value
return True
n_moves = 1 # счётчик хода, нечётный = х, чётный 0
while True:
try: # помню из с++ о нём, тем самым обробатываю некорренктный ввод данных пользователя (слова, одно число и тд)
field_output()
if not find_tire():
print("Победила дружба!!!)))")
input()
break
if n_moves % 2 == 1:
step = list(map(int, input("ходит 'х' введите строку и столбец (через пробел) x: ").split()))
if change_field(step, "x"):
if win("x"):
print("Поздравляю!!! Выиграл игрок 'x'")
field_output()
input()
break
n_moves += 1
else:
step = list(map(int, input("ходит '0' введите строку и столбец (через пробел) 0: ").split()))
if change_field(step, "0"):
if win("0"):
print("Поздравляю!!! Выиграл игрок '0'")
field_output()
input()
break
n_moves += 1
except:
print("Некорректно! Попробуйте снова =)")
|
# Задача-1:
# Дан список, заполненный произвольными целыми числами, получите новый список,
# элементами которого будут квадратные корни элементов исходного списка,
# но только если результаты извлечения корня не имеют десятичной части и
# если такой корень вообще можно извлечь
# Пример: Дано: [2, -5, 8, 9, -25, 25, 4] Результат: [3, 5, 2]
import math
a=[2, -5, 8, 9, -25, 25, 4]
b=[]
print(a)
for i in a:
if i>=0:
if int(math.sqrt(i))**2==i:
b.append(int(math.sqrt(i)))
print(b)
# Задача-2: Дана дата в формате dd.mm.yyyy, например: 02.11.2013.
# Ваша задача вывести дату в текстовом виде, например: второе ноября 2013 года.
# Склонением пренебречь (2000 года, 2010 года)
ddn=[]
#инициализация словаря дней
for i in range(1,32):
if i<10:
ddn.append('0'+str(i))
else:
ddn.append(str(i))
ddw0=['первое','второе','третье','четвертое','пятое','шестое','седьмое','восьмое','девятое']
ddw1=['десятое','одиннадцатое','двенадцатое','тринадцатое','четырнадцатое','пятнадцатое','шестнадцатое','семьнадцатое','восемьнадцатое','девятнадцатое']
ddw2=['двадцатое']
for w in ddw0:
ddw2.append('двадцать '+w)
ddw3=['тридцатое','тридцать первое']
ddw=ddw0+ddw1+ddw2+ddw3
dd=dict()
#инициализация словаря месяцев
for i in range(0,31):
dd[ddn[i]]=ddw[i]
mmw=['января','февраля','марта','апреля','мая','июня','июля','августа','сентября','октября','ноября','декабря']
mm=dict()
for i in range(0,12):
mm[ddn[i]]=mmw[i]
#перевод даты
dt='23.02.2015'
dtw=dd[dt[0:2]] + ' ' + mm[dt[3:5]] + ' ' +dt[6:] + ' года'
print(dtw)
# Задача-3: Напишите алгоритм, заполняющий список произвольными целыми числами
# в диапазоне от -100 до 100. В списке должно быть n - элементов.
# Подсказка:
# для получения случайного числа используйте функцию randint() модуля random
from random import randint
N=5
a=[]
for i in range(N):
a.append(randint(0,N))
print(a)
# Задача-4: Дан список, заполненный произвольными целыми числами.
# Получите новый список, элементами которого будут:
# а) неповторяющиеся элементы исходного списка:
# например, lst = [1, 2, 4, 5, 6, 2, 5, 2], нужно получить lst2 = [1, 2, 4, 5, 6]
# б) элементы исходного списка, которые не имеют повторений:
# например, lst = [1 , 2, 4, 5, 6, 2, 5, 2], нужно получить lst2 = [1, 4, 6]
lst = [1, 1, 2, 4, 5, 6, 6, 2, 2, 3]
a=set(lst)
print(a)
b=[]
ll=sorted(lst)
cur=ll[0]
n=0
for i in ll:
if i==cur:
n +=1
else:
if n==1:
b.append(cur)
n=1
cur=i
if n==1:
b.append(cur)
print(b)
|
#Pulls the data from the api with a start and end date
def api_search(code,start,end):
url="http://api.worldweatheronline.com/premium/v1/past-weather.ashx?key=6230647e6745477995c00355202410&q="+code+"&format=json&date="+start+"&enddate="+end +"&tp=24"
return url
import json
import urllib.request
import re
#allows user to enter what they want to search
code=input('Enter a zip code:')
start=input('Enter a start date in the format yyyy-mm-dd:')
end=input('Enter an end date in the format yyyy-mm-dd:')
graph_type=input('Do you want the data displayed daily, monthly, or yearly?')
minTemp={}
maxTemp={}
windSpeed={}
humidity={}
#splits the start and end date into groups
dateRegex=re.compile(r'(\d\d\d\d)-(\d\d)-(\d\d)')
mo=dateRegex.search(start)
dateRegex=re.compile(r'(\d\d\d\d)-(\d\d)-(\d\d)')
mo2=dateRegex.search(end)
start2=start
month=int(mo.group(2))+1
if month>9:
end2 = mo.group(1) + '-' + str(month) + '-' + mo.group(3)
else:
end2=mo.group(1)+'-'+'0'+str(month)+'-'+'01'
j=2
#pulls the data from the api seperately since the max amount of dates is 35. This allows for unlimited time
while(end2!=end):
url = api_search(code, start2, end2)
obj = urllib.request.urlopen(url)
rawdata = json.load(obj)
data = rawdata['data']
# pulls the data and places it into dictionaries
for item in data['weather']:
i = 0
date = item['date']
minTemp.update({date: item['mintempF']})
maxTemp.update({date: item['maxtempF']})
for item2 in item['hourly']:
test = item['hourly']
test2 = test[i]
windSpeed.update({date: test2['windspeedMiles']})
humidity.update({date: test2['humidity']})
i = i + 1
dateRegex = re.compile(r'(\d\d\d\d)-(\d\d)-(\d\d)')
mo3 = dateRegex.search(end2)
day = int(mo3.group(3)) + 1
if day > 9:
start2 = mo3.group(1) + '-' + mo3.group(2) + '-' + str(day)
else:
start2 = mo3.group(1) + '-' + mo3.group(2) + '-' + '0' + str(day)
month = int(mo.group(2)) + j
if month > 9:
end2 = mo3.group(1) + '-' + str(month) + '-' + '01'
else:
end2 = mo3.group(1) + '-' + '0' + str(month) + '-' + '01'
j = j + 1
dateRegex = re.compile(r'(\d\d\d\d)-(\d\d)-(\d\d)')
mo4 = dateRegex.search(start2)
if (mo4.group(2) == '12'):
end2 = str(int(mo4.group(1)) + 1) + '-01-' + '01'
j = 1
if (mo2.group(1) == mo4.group(1) and mo2.group(2) == mo4.group(2)):
end2 = end
url = api_search(code,start2,end2)
obj = urllib.request.urlopen(url)
rawdata = json.load(obj)
data = rawdata['data']
print("\n")
#pulls the data and places it into dictionaries
for item in data['weather']:
i=0
date=item['date']
minTemp.update({date:item['mintempF']})
maxTemp.update({date:item['maxtempF']})
for item2 in item['hourly']:
test=item['hourly']
test2 = test[i]
windSpeed.update({date:test2['windspeedMiles']})
humidity.update({date:test2['humidity']})
i=i+1
finalMinTemp=[]
finalMaxTemp=[]
finalwindSpeed=[]
finalHumidity=[]
#puts the data into an array so it can be graphed. Will also average the data based on month or year if needed
if(graph_type=='daily'):
for key, value in minTemp.items():
finalMinTemp.append(int(value))
for key, value in maxTemp.items():
finalMaxTemp.append(int(value))
for key, value in windSpeed.items():
finalwindSpeed.append(int(value))
for key, value in humidity.items():
finalHumidity.append(int(value))
elif(graph_type=='monthly'):
total = 0
count=0
temp = ''
for key, value in minTemp.items():
date=key
dateRegex=re.compile(r'\W\d\d\W')
mo=dateRegex.search(date)
if(mo.group()==temp or temp==''):
temp=mo.group()
total=total+int(value)
count=count+1
else:
temp=mo.group()
average=total/count
finalMinTemp.append(average)
total=int(value)
count=1
average = total / count
finalMinTemp.append(average)
total = 0
count = 0
temp = ''
for key, value in maxTemp.items():
date=key
dateRegex=re.compile(r'\W\d\d\W')
mo=dateRegex.search(date)
if(mo.group()==temp or temp==''):
temp=mo.group()
total=total+int(value)
count=count+1
else:
temp=mo.group()
average=total/count
finalMaxTemp.append(average)
total=int(value)
count=1
average = total / count
finalMaxTemp.append(average)
total = 0
count = 0
temp = ''
for key, value in windSpeed.items():
date=key
dateRegex=re.compile(r'\W\d\d\W')
mo=dateRegex.search(date)
if(mo.group()==temp or temp==''):
temp=mo.group()
total=total+int(value)
count=count+1
else:
temp=mo.group()
average=total/count
finalwindSpeed.append(average)
total=int(value)
count=1
average = total / count
finalwindSpeed.append(average)
total = 0
count = 0
temp = ''
for key, value in humidity.items():
date=key
dateRegex=re.compile(r'\W\d\d\W')
mo=dateRegex.search(date)
if(mo.group()==temp or temp==''):
temp=mo.group()
total=total+int(value)
count=count+1
else:
temp=mo.group()
average=total/count
finalHumidity.append(average)
total=int(value)
count=1
average = total / count
finalHumidity.append(average)
else:
total = 0
count=0
temp = ''
for key, value in minTemp.items():
date=key
dateRegex=re.compile(r'\d\d\d\d')
mo=dateRegex.search(date)
if(mo.group()==temp or temp==''):
temp=mo.group()
total=total+int(value)
count=count+1
else:
temp=mo.group()
average=total/count
finalMinTemp.append(average)
total=int(value)
count=1
average = total / count
finalMinTemp.append(average)
total = 0
count = 0
temp = ''
for key, value in maxTemp.items():
date=key
dateRegex=re.compile(r'\d\d\d\d')
mo=dateRegex.search(date)
if(mo.group()==temp or temp==''):
temp=mo.group()
total=total+int(value)
count=count+1
else:
temp=mo.group()
average=total/count
finalMaxTemp.append(average)
total=int(value)
count=1
average = total / count
finalMaxTemp.append(average)
total = 0
count = 0
temp = ''
for key, value in windSpeed.items():
date=key
dateRegex=re.compile(r'\d\d\d\d')
mo=dateRegex.search(date)
if(mo.group()==temp or temp==''):
temp=mo.group()
total=total+int(value)
count=count+1
else:
temp=mo.group()
average=total/count
finalwindSpeed.append(average)
total=int(value)
count=1
average = total / count
finalwindSpeed.append(average)
total = 0
count = 0
temp = ''
for key, value in humidity.items():
date=key
dateRegex=re.compile(r'\d\d\d\d')
mo=dateRegex.search(date)
if(mo.group()==temp or temp==''):
temp=mo.group()
total=total+int(value)
count=count+1
else:
temp=mo.group()
average=total/count
finalHumidity.append(average)
total=int(value)
count=1
average = total / count
finalHumidity.append(average)
print(finalMinTemp)
print(finalMaxTemp)
print(finalwindSpeed)
print(finalHumidity)
|
def main() :
comm = input("Please specify a command [list, add, mark, archive]: ")
if comm == "add" :
add()
if comm == "list" :
listw()
if comm == "mark" :
mark()
if comm == "archive" :
archive()
def listw() :
fr = open ('todolist', 'r')
i = 1
print ('\n')
for line in fr:
print (i,". [ ] " + line )
i = i + 1
def add():
fa = open ('todolist', 'a')
element = input(('Add an item: '))
fa.write(element + '\n' )
print('Item added.')
def mark() :
f = open('todlist', 'a')
task = input("Which one you want to mark as completed: ")
f.write(task +"\n")
print( task, " is completed")
main() |
#PROGRAMA 18
#Ejercicio 18 condicional doble
import os
dias=0
#INPUT VIA OS
dias=int(os.sys.argv[1])
#processing
#Si el producto supera los 22 dias
#aplicar descuento
descuento=dias>22
if(dias>22):
print("con descuento")
else:
print("sin descuento")
#finif
|
import random
EASY_LEVEL_ATTEMPTS = 10
HARD_LEVEL_ATTEMPTS = 7
def check_answer(guess,random_number):
if guess < random_number:
print("Too low")
elif guess > random_number:
print("Too high")
elif guess == random_number:
print("You've won!")
def set_difficulty(difficulty):
if difficulty == 'easy':
return EASY_LEVEL_ATTEMPTS
else:
return HARD_LEVEL_ATTEMPTS
def game():
print("Welcome to the Number Guessing Game \n I'm thinking of a number between 1 and 100")
difficulty = input("Choose a difficulty. Type 'easy' or 'hard': ")
random_number = random.randint(1,100)
attempts = set_difficulty(difficulty)
# While loop to allow for continous guessing until attempt ends
guess = 0
while guess != random_number and attempts > 0:
print(f"You have {attempts} attempts remaining")
guess = int(input("Make a guess: "))
attempts -= 1
check_answer(guess,random_number)
game()
|
# write a program that reads character one by one and store them in UPPER if in upper case or in LOwer if in other.
def convertOpposite(str):
ln = len(str)
for i in range(ln):
if str[i] >= 'a' and str[i] <= 'z':
# Convert lowercase to uppercase
str[i] = chr(ord(str[i]) - 32)
elif str[i] >= 'A' and str[i] <= 'Z':
# Convert lowercase to uppercase
str[i] = chr(ord(str[i]) + 32)
# Driver code
if __name__ == "__main__":
str = input("Enter the sting :\t")
str = list(str)
# Calling the Function
convertOpposite(str)
str = ''.join(str)
print(str)
|
# Write a program that recieves 4 digit no. and calculate sum of squares of first 2 digits and last 2 digits.
import math
def sum_of_squares(number):
x = int(number[0:2])
y = int(number[2:5])
z = math.pow(x, 2)+ math.pow(y, 2)
print(f"the sum of the square of the two numbers is {z}.")
number = input("enter a four digit number:\t")
sum_of_squares(number)
|
# Glossary
# Indentation https://www.learnpython.org/en/Hello,_World!
# Variables and Types https://www.learnpython.org/en/Variables_and_Types
# Numbers
# Strings
# Lists
# Basic Operators https://www.learnpython.org/en/Basic_Operators
# Arithmetic Operators
# Using Operators with Strings
# Using Operators with Lists
# Notes from https://www.learnpython.org
# Python is a very simple language, and has a very straightforward syntax.
# It encourages programmers to program without boilerplate (prepared) code.
# The simplest directive in Python is the "print" directive - it simply
# prints out a line (and also includes a newline, unlike in C).
# Printing a String
print("Hello World!")
# Indentations
# Python uses indentation for blocks, instead of curly braces.
# Both tabs and spaces are supported, but the standard indentation
# requires standard Python code to use four spaces.
x = 10
if x == 10:
#indented four spaces
print("x is 10")
# Variables and Types
# Python is completely object oriented, and not "statically typed".
# You do not need to declare variables before using them,
# or declare their type. Every variable in Python is an object.
# Numbers
# Python supports two types of numbers - integers and floating point numbers.
# (It also supports complex numbers, which will not be explained in this
# tutorial).
# Integers
myint = 7
print(myint)
# Floating Point Numbers
myfloat = 20.0
print(myfloat)
myfloat = float(20)
print(myfloat)
# Strings
# Strings are defined either with a single quote or a double quotes.
mystring = 'ciao'
print(mystring)
mystring2 = "hola"
print(mystring2)
# The difference between the two is that using double quotes makes it easy to
# include apostrophes (whereas these would terminate the string if using
# single quotes)
mystring = "Don't you worry about apostrophes"
print(mystring)
# There are additional variations on defining strings that make it easier to
# include things such as carriage returns, backslashes and Unicode characters.
# These are beyond the scope of this tutorial, but are covered in the
# Python documentation: https://docs.python.org/3/tutorial/introduction.html#strings
two = 2
three = 3
five = two + three
print(five)
hola = "hola"
mundo = "mundo"
holamundo = hola + " " + mundo
print(holamundo)
# Assignments can be done on more than one variable "simultaneously" on the same line
# like this
a, b = 10, 20
print (a, b)
# Lists
# Lists are very similar to arrays. They can contain any type of variable, and they can contain
# as many variables as you wish. Lists can also be iterated over in a very simple manner.
# Here is an example of how to build a list.
mylist = []
mylist.append(10)
mylist.append(20)
mylist.append(30)
print(mylist[0]) # prints 10
print(mylist[1]) # prints 20
print(mylist[2]) # prints 30
# prints out 10,20,30
for x in mylist:
print(x)
# Accessing an index which does not exist generates an exception (an error).
mylist = [1,2,3]
print(mylist[10])
# Arithmetic Operators
# Just as any other programming languages, the addition, subtraction, multiplication,
# and division operators can be used with numbers.
# Try to predict what the answer will be. Does python follow order of operations?
# Another operator available is the modulo (%) operator, which returns the integer
# remainder of the division. dividend % divisor = remainder.
remainder = 11 % 3
print(remainder)
# Using two multiplication symbols makes a power relationship.
squared = 7 ** 2
cubed = 2 ** 3
print(squared)
print(cubed)
# Using operators with strings
# Python supports concatenating strings using the addition operator:
ciaomondo = "ciao" + " " + "mondo"
print(ciaomondo)
# Python also supports multiplying strings to form a string with a
# repeating sequence:
lotsofciaos = "ciao" * 4
print(lotsofciaos)
# Using Operators as Lists
# Lists can be joined with the addition operators:
even_numbers = [2,4,6,8]
odd_numbers = [1,3,5,7]
all_numbers = odd_numbers + even_numbers
print(all_numbers)
# Just as in strings, Python supports forming new lists
# with a repeating sequence using the multiplication operator:
print([1,2,3] * 3) |
#import matplotlib
from matplotlib.pyplot import figure, show
import matplotlib.pyplot as plt
from numpy import arange, sin, pi, cos, tan
import numpy as np
import math
def a1(x,a,b,c,d):
return a*sin(b*x+c)+d
def a2(x,a,b,c,d):
return a*cos(b*x+c)+d
def a3(x,a,b,c,d):
return a*tan(b*x+c)+d
if __name__ == '__main__':
a = float(input("A: "))
b = float(input("B: "))
c = float(input("C: "))
d = float(input("D: "))
p = ((2*math.pi)/b)
x = arange(0.0,p,0.1)
fig = figure(0.5)
y1 = a1(x,a,b,c,d)
y2 = a2(x,a,b,c,d)
y3 = a3(x,a,b,c,d)
ax1 = fig.add_subplot(111)
ax1.set_xticks([0., .5*np.pi, np.pi, 1.5*np.pi, 2*np.pi])
ax1.set_xticklabels(["$0$", r"$\frac{1}{2}\pi$",r"$\pi$", r"$\frac{3}{2}\pi$", r"$2\pi$"])
ax1.plot(x, sin(2*math.pi*x))
ax1.grid(True)
ax1.set_ylim((-3, 3))
ax1.set_ylabel('')
ax1.set_title('seno')
plt.draw()
plt.show()
|
import numpy as np # multi-dimensional arrays
from PIL import Image # images
import matplotlib.pyplot as plt # used to display a matrix as an image
#-------------------------------------------------
# Utility functions for images.
#
# An image is represented as a 3-dimensional array of unsigned
# integers. The 3 dimensions represent:
# - the image columns (size: the image width in pixels)
# - the image lines (size: the image height in pixels)
# - the pixels (3 unsigned integers representing the RGB values)
#-------------------------------------------------
#-------------------------------------------------
# Read an image from a file and return a 3-dimensional array of
# unsigned integers.
#
# input:
# filename: the name of the image file to be read
#
# output:
# a 3-dimensional array of unsigned integers representing the image
#-------------------------------------------------
def read_img(filename):
img = np.array(Image.open(filename))
# get a read-only array of the image
try:
pixels = np.asarray(img, dtype='uint8')
except SystemError:
pixels = np.asarray(img.getdata(), dtype='uint8')
# make the image writable
pixels.setflags(write=1)
return pixels
#-------------------------------------------------
# Convert a 3-dimensional array of integers to an image and write it
# to a file.
#
# input:
# filename: the name of the file where the image should be written
# pixels: a 3-dimensional array of unsigned integers representing
# the image
#-------------------------------------------------
def write_img(filename, pixels):
img = Image.fromarray(pixels)
img.save(filename)
#-------------------------------------------------
# Make a 3-dimensional array of integers to represent an image having
# the given dimensions.
#
# input:
# width: the image width in pixels
# height: the image height in pixels
#
# output:
# a 3-dimensional array of unsigned integers a black image (all
# pixels are zeros)
#-------------------------------------------------
def empty_img(width, height):
return np.zeros((width, height, 3), dtype='uint8')
#-------------------------------------------------
# Give the width in pixels of an image represented as a 3-dimensional
# array of unsigned integers.
#
# input:
# pixels: a 3-dimensional array of unsigned integers representing
# the image
#
# output:
# width: the image width in pixels
#-------------------------------------------------
def get_width(pixels):
return np.shape(pixels)[0]
#-------------------------------------------------
# Give the height in pixels of an image represented as a 3-dimensional
# array of unsigned integers.
#
# input:
# pixels: a 3-dimensional array of unsigned integers representing
# the image
#
# output:
# height: the image height in pixels
#-------------------------------------------------
def get_height(pixels):
return np.shape(pixels)[1]
#-------------------------------------------------
# Display an image represented as a 3-dimensional
# array of unsigned integers.
#
# input:
# pixels: a 3-dimensional array of unsigned integers representing
# the image
#
# output:
# the image displayed
#-------------------------------------------------
def display_img(pixels):
plt.imshow(pixels)
return plt.show()
|
#!/usr/bin/env python3
sz1 = 23
sz2 = 9
tipp = int(input ('Mennyi ' + str(sz1) + '+' + str(sz2) + ' ? '))
if tipp == sz1 + sz2:
print ('Nem rossz, nem rossz...')
else:
print('Háát mit csinálsz?!')
|
# -*- coding: utf-8 -*-
__author__ = 'Benjamin Grandfond <benjaming@theodo.fr>'
class Toilet:
FREE = 'free'
USED = 'used'
def __init__(self, name, captor, status=True):
self.name = name
self._captor = captor
self._status = self.convert_status(status)
def __unicode__(self):
return '%s is %s' % (self.name, self._status)
def is_free(self):
"""
Check if the toilet is free or used.
"""
return True if self._status == self.FREE else False
def captor(self):
"""
Return the captor name.
"""
return self._captor
def update(self, status):
status = self.convert_status(status)
if status is not self._status:
self._status = status
@classmethod
def convert_status(cls, status):
"""
Convert a boolean or a int into a Toilet status (free or used).
A toilet is free if the status var is True or an int > 80.
A toilet is used if the status var is False or an int <= 80.
"""
# Convert a bool or an int into free or false
if status in [cls.FREE, cls.USED]:
return status
else:
if isinstance(status, bool):
return Toilet.FREE if status == True else Toilet.USED
elif isinstance(status, int):
return Toilet.FREE if status > 80 else Toilet.USED
else:
raise ValueError('status must be a boolean or an int, %s given' % type(status))
|
from cs50 import get_int
while True:
n = get_int("Positive number: ")
if n > 0:
break
for i in range(n):
for j in range(n-i):
print(" ", end="")
for k in range(i+1):
print("#", end="")
print()
|
"""Functions for common math operations."""
def add(num1, num2):
"""Return the sum of the two inputs."""
addition = num1 + num2
return addition
def subtract(num1, num2):
"""Return the second number subtracted from the first."""
sub = num1 - num2
return sub
def multiply(num1, num2):
"""Multiply the two inputs together."""
mult = num1*num2
return numlt
def divide(num1, num2):
"""Divide the first input by the second and return the result."""
div = num1/num2
return div
def square(num1):
"""Return the square of the input."""
sq = num1**num1
return sq
def cube(num1):
"""Return the cube of the input."""
c = num1**3
return c
def power(num1, num2):
"""Raise num1 to the power of num2 and return the value."""
p = num1**num2
return p
def mod(num1, num2):
"""Return the remainder of num1 / num2."""
modulo = num1%num2
return modulo
|
#Given an array nums and a value val, remove all instances
#of that value in-place and return the new length.
#Do not allocate extra space for another array, you must do this by
#modifying the input array in-place with O(1) extra memory.
#The order of elements can be changed. It doesn't matter what you leave beyond
#the new length.
def remove(nums, val):
if len(nums) < 1:
return len(nums)
if len(nums) ==1 and nums[0]!=val:
return len(nums)
elif len(nums) ==1 and nums[0]== val:
return 0
i = 0
j = 0
for j in nums:
if j != val:
nums[i]=j
i+=1
return i
#print(remove([3,2,2,3], 3))
print(remove([0,1,2,2,3,0,2], 2))
|
def safe_pawns(pawns):
pawns = list(pawns)
count = 0
for i in pawns:
ad1 = chr(ord(i[0])-1) + str(int(i[1])-1)
ad2 = chr(ord(i[0])+1) + str(int(i[1])-1)
if ad1 in pawns or ad2 in pawns:
count += 1
return count
print(safe_pawns({"b4", "d4", "f4", "c3", "e3", "g5", "d2"}))
|
"""
This module contains classes to be used to read a LilyPond .notes file
created using an events listener. The events are parsed into a set of
Notes which are held in Voices (think instrument or choral part). The
voices are held in a Score, which does the main parsing work.
"""
class Note:
"""
represents a music note
"""
STRESS_INCREMENT = 9
def __init__(self, midi_pitch, at=0, clicks=0.25, position=None):
self.pitch = int(midi_pitch)
self.duration = clicks
self.start_time = at
self.volume = float(71 / 127)
self.score_position = position
self.slurred = False
def __repr__(self):
return f"{self.pitch} {self.duration} {int(self.volume * 127)}"
def check_valid(self):
"""
add in some validation checking
"""
try:
# assert type(self.duration) is int
assert self.duration > 1
except AssertionError as a_error:
print(self)
raise a_error
def extend(self, clicks=0.25):
"""
when a tie is spotted and we need to extend the previous note
by the length of the new note
"""
if self.is_rest():
# should not be extending a rest, implies a tie
raise ValueError
self.duration += clicks
def accent(self, stress_type):
"""
stress this note (add velocity), typically for first beat in bar
"""
if self.is_rest():
return
if stress_type == 0:
self.volume += Note.STRESS_INCREMENT / 127
else:
self.volume += Note.STRESS_INCREMENT / 127 * 2 / 3 # less
self.volume = min(127, self.volume)
def set_in_slur(self):
"""
this note is in slur and should not be staccato'd
"""
self.slurred = True
def set_not_slurred(self):
"""
this note is at the end of a slur so may be stacatto'd
"""
self.slurred = False
def set_velocity(self, velocity):
"""
update the note's volume with an explicit midi velocity
"""
self.volume = min(127, velocity)
def staccato(self, factor=0):
"""
shorten this note by a factor
"""
if self.is_rest():
return
if factor == 0:
factor = 0.1 # really short (for staccato dot)
if not self.slurred:
self.duration *= factor
def is_rest(self):
"""
rests use a dummy pitch of -1
"""
return self.pitch == -1
def as_mido_on_attrs(self):
"""
return the note's midi attributes in a format suitable for
generating a mido message
"""
if self.is_rest():
return None
attribs = {
"type": "note_on",
"time": 0,
"channel": 1,
"note": self.pitch,
"velocity": int(self.volume * 127),
}
return attribs
def as_mido_off_attrs(self):
"""
return the note's midi attributes in a format suitable for
generating a mido message
"""
if self.is_rest():
return None
attribs = {
"type": "note_off",
"time": self.duration,
"channel": 1,
"note": self.pitch,
"velocity": 0,
}
return attribs
|
#defining function for getting tripltes
def func(a, n):
found =False
for i in range(0, n - 2):
#creating range
for j in range(i + 1, n - 1):
for k in range(j + 1, n):
if (a[i] + a[j] + a[k] == 0):
print( a[i], a[j], a[k])
found = True
if (found == False):
print(" No Triplets ")
#defining array
a = [-4, -3, -2, -1, 0, 1, 2, 3]
#defining length
n = len(a)
func(a, n) |
class DisWords:
def __init__(self):
pass
def measureWords(self, wA, wB):
lenMin = min(len(wA), len(wB))
lo = -1
for i in range(1, lenMin):
if(i < lenMin and wA[-i:-1] + wA[-1:] == wB[0:i]):
lo = i
i = i + 1
if lo == -1:
return 0
else:
return lo
def measureWList(self, words):
wordsDis = [[0 for j in range(len(words))] for i in range(len(words))]
for i in range(len(words)):
for j in range(len(words)):
if i == j:
wordsDis[i][j] = 0
else:
wordsDis[i][j] = self.measureWords(words[i], words[j])
return wordsDis
if __name__ == '__main__':
disWords = DisWords()
words = ['0_0_1', '0_1_2', '3_2_1']
wordsList = []
for word in words:
wordsList.append(word.split('_'))
print(disWords.measureWList(wordsList)) |
i = 1
while i < 31:
if i % 15 == 0:
print("TanaWaii!")
elif i % 3 == 0:
print("Tana!")
elif i % 5 == 0:
print("Waii!")
else:
print(i)
i += 1 |
# Uses python3
import sys
def get_max_pairwise_sum(n):
pairs = list()
pairs.append(1)
temp = 2
while n != 0:
if n > (temp * 2):
pairs.append(temp)
n -= temp
temp += 1
else:
pairs.append(n)
break
print(len(pairs))
for x in pairs:
print(x, end=' ')
def main():
num = int(input())
if num <= 2:
print("1\n", num)
else:
get_max_pairwise_sum(num - 1)
if __name__ == "__main__":
main()
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.