text stringlengths 37 1.41M |
|---|
#!/usr/bin/env python
#
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
#
# Jiao Lin
# California Institute of Technology
# (C) 2005 All Rights Reserved All Rights Reserved
#
# {LicenseText}
#
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
#
class SlicingInfo:
def __init__(self, inputs):
"""
SlicingInfo( (3.0, 5.5) )
SlicingInfo( (,) )
SlicingInfo( (1,99) )
SlicingInfo( SlicingInfo( (3,5) ) )
SlicingInfo( front, 33 )
"""
#convert inputs from list to tuple
if isinstance(inputs, list): inputs = tuple(inputs)
#tuple
if isinstance(inputs, tuple):
if len(inputs) == 0:
#inputs is (,)
self.start, self.end = front, back
elif len(inputs) == 2:
#inputs is (a,b)
start, end = inputs
if start is None: start = front
if end is None: end = back
self.start = start
self.end = end
else:
#unknown inputs
raise ValueError("Don't know how to get slicing info from {0!s}".format(inputs))
elif isinstance(inputs, SlicingInfo):
#copy ctor
self.start, self.end = inputs.start, inputs.end
else:
#unknown inputs
raise ValueError("Don't know how to get slicing info from {0!s}".format(inputs))
return
def __str__(self):
return "{0!s}:{1!s}".format(self.start, self.end)
__repr__ = __str__
class SpecialPosition:
def __init__(self, name):
self.name = name
return
def __str__(self): return "{0!s}".format(self.name)
pass # end of SpecialPosition
pass # end of SlicingInfo
front = SlicingInfo.SpecialPosition("front")
back = SlicingInfo.SpecialPosition("back")
all = SlicingInfo((front, back))
# version
__id__ = "$Id$"
# Generated automatically by PythonMill on Sat Jul 8 08:20:17 2006
# End of file
|
"""
Working with dictionaries in python
https://github.com/flaberenne/python3rep/textManipulation.py
Author:flaberenne
"""
#Building a dictionary from 2 lists, the 1st one define the keys, the 2nd the values
a=['en','fr','br','es']
b=['Hello','Bonjour',"Bom dia","Buenos dias"]
dictionary={i:j for (i,j) in zip(a,b) }
print(dictionary)
#Building 2 lists from a dictionary,one list with the keys, the other one with the values
keys=list(dictionary.keys())
values=list(dictionary.values())
print("KEYS:"+ str(keys))
print("VALUES:"+ str(values))
|
def vowels(x):
for i in range(len(y)) :
if y[i] in h:
print(y[i])
x=input("Insert any word : ")
y=x.lower()
h=['a','e','i','o','u']
i=0
vowels(x)
|
# -*- coding: UTF-8 -*-
# 输出 Python 的每个字母
for letter in 'Python':
if letter == 'h':
pass
print ("这是 pass 块")
print ("当前字母 :", letter)
print ("Good bye!")
'''
当前字母 : P
当前字母 : y
当前字母 : t
这是 pass 块
当前字母 : h
当前字母 : o
当前字母 : n
Good bye!
''' |
import random
from common.city import City
def generate_random_cities(count=100):
"""
:type count: int
:rtype: list[]
"""
cities = []
for number in xrange(0, count):
x = random.uniform(-100, 100)
y = random.uniform(-100, 100)
cities.append(City(number, x, y))
return cities
|
class City(object):
def __init__(self, number, x, y):
"""
:type number: int
:type x: float
:type y: float
"""
self.number = number
self.x = x
self.y = y
def __str__(self):
return "City #{0} [{1:.2f}; {2:.2f}]".format(self.number, self.x, self.y)
def __repr__(self):
return self.__str__()
def __eq__(self, other):
return self.number == other.number
def __hash__(self):
return hash(self.number)
|
#!/usr/bin/env python
import sys
"""Module for reading command line arguments
Loosely follows the POSIX.1-2017 guidelines:
https://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap12.html
The command line arguments should consist of options, option-arguments,
operands and a special argument --
Options have to be single alphanumeric characters. Some options are followed
by option-arguments. Option-arguments are not optional. So if a option O
can be followed by an option-argument, then it must always be followed by
an option-argument. The property of having an option-argument is defined in
option_types dict.
If 'utility_name -A a' is valid and 'a' is an option-argument,
then 'utility_name -A' is not valid
Option-arguments are strings which must not start with -.
Operands are strings which usually must not with - (see next paragraph).
After first -- argument every following argument is treated as an operand.
This means that operands can also start with - if they are placed after --.
Before the first -- or in absence of --
1. Arguments starting with - are treated as strings of option characters
2. Every option should be in the option_types dict
3. Only options without option-arguments may be concatenated i.e. -abc
4. An option (with or without option-arguments) may occur many times but only
the first occurrence is considered. Each of these repeats should be followed by
an option-argument if the option requires it.
5. If an argument is not an option or option-argument, then it is handled as a
operand.
Usage
-----
Simply call read. For example:
option_values, operands = read(sys.argv, ['a', 'b'], ['c', 'd'])
Now option_values will be a dict of read options and possible corresponding values.
Value == None for options without arguments. Operands is a list of operands.
"""
def read(argv, options_without_arguments=[], options_with_arguments=[]):
"""Read options from an argv list.
Parameters
----------
argv : list (str)
Content of sys.argv.
Command line arguments to be read.
options_without_arguments: list (str)
Elements are single alphanumeric characters
options_with_arguments: list (str)
Elements are single alphanumeric characters
Every alphanumeric character should occur at most once
and only in one of the lists
Returns
-------
(option_values, operands)
option_values : dict (str: str)
Read options and possible corresponding values. Value == None
for options without arguments
operands : list (str)
Read operands
"""
#check that argv is an output of sys.argv
check_command_line_argument_validity(argv)
#construct a dict from the option lists
option_types = make_option_dict(options_without_arguments, options_with_arguments)
return parse_command_line_arguments(argv, option_types)
def make_option_dict(options_without_arguments, options_with_arguments):
"""Construct a option dict from two lists of options
"""
options = {}
for x in options_without_arguments:
if x in options:
raise ValueError("Multiple definitions of the same option")
options[x] = 'no_option_argument'
for x in options_with_arguments:
if x in options:
raise ValueError("Multiple definitions of the same option")
options[x] = 'option_argument'
check_option_dict_validity(options)
return options
def check_option_dict_validity(option_types):
"""Checks the validity of options and option arguments
Option set is valid only if:
1. Type of every element of 'options' is correct
2. Every option name is an alphanumeric character
3. Every option-argument belongs to the set ['option_argument', 'no_option_argument']
Parameters
----------
options : dict ('str', 'str')
Key is the value of the option.
Value is 'option_argument' if the option has an option-argument
'no_option_argument' for an option without an option-argument.
"""
for key, value in option_types.items():
if not isinstance(key, str):
ok = False
raise TypeError("Option name not string")
if len(key) != 1:
raise ValueError("Option name not a single character")
if not key.isalnum():
raise ValueError("Option name not alphanumeric")
#NOTE
#How to handle this? The user should never set these values
if value not in ['option_argument', 'no_option_argument']:
raise Exception("Internal error in option list processing")
def check_command_line_argument_validity(argv):
"""Basic sanity check for argv.
1. argv is list of string
2. len(argv) > 0
3. For every element s (except the first one) should hold len(s) > 0
Parameters
----------
argv : list of strings
Content of sys.argv
Command line arguments to be checked.
Returns
-------
ok : bool
True if no errors were detected
False if argv is not a valid argument list
TODO
----
Should only raise exceptions and not return anything
"""
ok = True
#must be a list
if not isinstance(argv, list):
return False
for x in argv:
if not isinstance(x, str):
return False
#must always at least contain the program name
if len(argv) < 1:
ok = False
#apart from the program name, every other argument must be nonempty
for i in range(1, len(argv)):
if len(argv[i]) == 0:
ok = False
return ok
def parse_command_line_arguments(argv, option_types):
"""Extract options and operands from the argv.
Parameters
----------
argv : list of strings
Content of sys.argv
First element is the program name
For subsequent elements s should hold |s| > 0
option_types : dict (str: str)
Key is the value of the option.
Value is 'option_argument' if the option has an option-argument
'no_option_argument' for an option without an option-argument.
Returns
-------
(argv_options, operands) : tuple
argv_options : dict (str: (None | str))
Options with their corresponding option-arguments or None
operands : list (str)
"""
#options encountered in the argv
#for options without option-arguments (c, None) is added
#for option with option-arguments (c, d) is added where
#where c is the option and d is the option-argument
argv_options = {}
#list of strings
operands = []
#will be switched to True if -- is encountered
only_operands = False
#we can skip the first argument which is the file name
#and should be correct
pos = 1
while pos < len(argv):
#after first --, every argv[i] is an operand
if only_operands:
operands.append(argv[pos])
else:
#which to only operands mode if -- is encountered
if argv[pos] == '--':
only_operands = True
#if new argument start with -, then it is an option
elif argv[pos][0] == '-':
#if at least one of the options has arguments
has_argument = False
for i in range(1, len(argv[pos])):
if argv[pos][i] not in option_types:
raise ValueError(f"Option {argv[pos]} not valid")
#if the option argv[i] requires an option-argument
if option_types[argv[pos][i]] == 'option_argument':
has_argument = True
#option cannot be empty
if len(argv[pos]) == 1:
raise ValueError(f'Option cannot be empty (only -)')
if has_argument:
if len(argv[pos]) == 2:
#check that there is a option-argument in argv
if pos + 1 >= len(argv):
raise ValueError(f'No option-argument was provided for: {argv[pos]}')
#check that the option-argument doesn't start with -
if argv[pos+1][0] == '-':
raise ValueError(f'Option-argument for {argv[pos]} starts with an illegal character: {argv[pos+1]}')
#only update the value if not already present
if argv[pos][1] not in argv_options:
argv_options[argv[pos][1]] = argv[pos+1]
#because we handled two elements
pos += 1
#options with arguments can't be concatenated
elif len(argv[pos]) > 2:
raise ValueError(f'Options with option-arguments cannot be concatenated: {argv[pos]}')
#we should never end up here
else:
raise ValueError()
#if options don't require option-arguments, just add every option to argv_options
else:
for option in argv[pos][1:]:
if option not in argv_options:
argv_options[option] = None;
#otherwise we will just add it to the operands
else:
operands.append(argv[pos])
pos += 1
return (argv_options, operands)
options_without_arguments = ['A', 'a', '1']
options_with_arguments = ['B', 'b', '2']
if __name__ == "__main__":
print("options_without_arguments: ", end='')
print(options_without_arguments);
print("options_with_arguments: ", end='')
print(options_with_arguments)
print("sys.argv: ", end='')
print(sys.argv)
result = read(sys.argv, options_without_arguments, options_with_arguments)
print(result)
|
from question1 import *
import datetime
from PIL import Image
import re
# testing basic class functions
c = Content('Example', 'This is a test', 'James', 2014, 3, 1)
p = Picture('Example', 'This is a test', 'James', 2014, 3, 1, None)
a = Article('Example', 'This is a test', 'James', 2014, 3, 5, 'fake_image.txt')
c.show()
print
p.show()
print
a.show()
print
# URL functions
print c.matches_url("http://www.thecrimson.com/Content/2014/3/1/This_is_a_test") # True
print p.matches_url("http://www.thecrimson.com/Content/2014/3/1/This_is_a_test") # False
print a.matches_url("http://www.thecrimson.com/Content/2014/3/1/This_is_a_test") # False
print
print from_url([c], "http://www.thecrimson.com/Content/2014/3/1/This_is_a_test") # Prints same output as c.show()
print
print from_url([c], "http://www.thecrimson.com/Article/2014/3/1/This_is_a_test") # Prints "No items match this URL."
print
print from_url([c, c, c], "http://www.thecrimson.com/Content/2014/3/1/This_is_a_test") # Prints "Error: No items match this URL."
print
# posted_after calls .show()
posted_after([c, p, a], datetime.date(2014, 2, 28)) # Shows all three
print
posted_after([c, p, a], datetime.date(2014, 3, 5)) # Shows none of the three
print
posted_after([c, p, a], datetime.date(2014, 3, 2)) # Shows a |
# Basics of randomization
'''
One of the things that makes games replayable is the pseudo-random nature
of random numbers- in physical games that's easily done with dice.
'''
import random
# How many sides on the dice do we want? 6, 8, 10, 12, 20 and 100 are normal
SIDES = 6
# We want a random intenger, meaning only full round numbers
x = random.randint(1, SIDES)
# Lets print out what we got!
print(x)
# What happens when we do it a lot?
for x in range(1, 101):
print(x, str(random.randint(1, SIDES)))
|
"""
The __init__.py serves double duty: it will contain the application factory,
and it tells Python that the flaskr directory should be treated as a package.
"""
import os
from flask import Flask
"""
create_app is the application factory function.
You’ll add to it later in the tutorial, but it already does a lot.
"""
def create_app(test_config=None):
# create and configure the app
"""
__name__ is the name of the current Python module.
The app needs to know where it’s located to set up some paths,
and __name__ is a convenient way to tell it that.
"""
"""
instance_relative_config=True tells the app
that configuration files are relative to the instance folder.
The instance folder is located outside the flaskr package
and can hold local data that shouldn’t be committed to version control,
such as configuration secrets and the database file.
"""
app = Flask(__name__, instance_relative_config=True)
# sets some default configuration that the app will use:
"""
SECRET_KEY is used by Flask and extensions to keep data safe.
It’s set to 'dev' to provide a convenient value during development,
but it should be overridden with a random value when deploying.
"""
"""
DATABASE is the path where the SQLite database file will be saved.
It’s under app.instance_path,
which is the path that Flask has chosen for the instance folder.
You’ll learn more about the database in the next section.
"""
app.config.from_mapping(
SECRET_KEY='dev',
DATABASE=os.path.join(app.instance_path, 'flaskr.sqlite'),
)
"""
app.config.from_pyfile() overrides the default configuration
with values taken from the config.py file in the instance folder if it exists.
For example, when deploying, this can be used to set a real SECRET_KEY.
"""
"""
test_config can also be passed to the factory,
and will be used instead of the instance configuration.
This is so the tests you’ll write later in the tutorial can be configured
independently of any development values you have configured.
"""
if test_config is None:
# load the instance config, if it exists, when not testing
app.config.from_pyfile('config.py', silent=True)
else:
# load the test config if passed in
app.config.from_mapping(test_config)
# ensure the instance folder exists
"""
os.makedirs() ensures that app.instance_path exists.
Flask doesn’t create the instance folder automatically,
but it needs to be created because your project will create the SQLite database file there.
"""
try:
os.makedirs(app.instance_path)
except OSError:
pass
# a simple page that says hello
"""
It creates a connection between the URL /hello
and a function that returns a response,
the string 'Hello, World!' in this case.
"""
@app.route('/hello')
def hello():
return 'Hello, World!'
from . import db
db.init_app(app)
from . import auth
app.register_blueprint(auth.bp)
from . import blog
app.register_blueprint(blog.bp)
app.add_url_rule('/', endpoint='index')
return app
# TO RUN THE APP:
"""
export FLASK_APP=flaskr
export FLASK_ENV=development
flask run
"""
|
import array_stack
stack = array_stack.ArrayStack()
# input_file = open("input.txt", "r")
input_file = "4 6 + 13 11 - / 3 *"
answer_list = []
numerical_vals = "1234567890"
valid_operators = "+ - * /"
def calculate(expression):
hold = []
reversed_hold = []
exp = ""
expression_list = expression.split()
for value in expression_list:
if value.isnumeric():
stack.push(value)
elif value in valid_operators:
hold.append(stack.pop())
hold.append(value)
hold.append(stack.pop())
for i in range(3):
reversed_hold.append(hold.pop())
exp = ''.join(reversed_hold)
reversed_hold = []
hold = []
answer = eval(exp)
stack.push(str(answer))
return stack.top()
def main():
print(calculate(input_file))
if __name__ == '__main__':
main() |
import os, sys
from sys import platform
if platform == "linux" or platform == "linux2":
if os.getuid() == 0:
file_or_dir = input("File or Directory [file, dir]: ")
file_name = input("File or directory name for search: ")
find_dir = input("Finding directory: ")
print()
print("*************************************************************")
if file_or_dir == "file":
os.system("find " + find_dir + " -type f" + " -name " + file_name)
elif file_or_dir == "dir":
os.system("find " + find_dir + " -type d" + " -name " + file_name)
print("*************************************************************")
print()
print("Process Compileted")
else:
print("ERROR: application must be run as root")
else:
print("Necessarily Linux")
|
################### Topics #######################
#What is variable
## DIfferent between mutable and immutale type Variable Type: Change in value in same memory (Mutable) and change in memory address when value changes (immutable).
## Stack and Heap memory : Queue and List . RAM and ROM
#python is case sensitive
# Precedence
#################### Topics #########################
###############Naming rules #########################
#must begin with letter or _.
#Followed by any number of letters, digits, or underscores
#Should not be a built-in name or Keyword
#PEP 8, the style guide for Python, recommends lowercase with underscores as necessary: first_name
# Immutable types: String , Integer, floating , Tuples .
# Mutable: Lists, dictionaries, and sets are mutable
# Python memory allocation for small and large values : Dynamic allocation: Bit/Bytes: Medical shop example
############## Variables ############################
#int, FLoat, String is immuable still below will give fdififerent id
a=10.12
b=10.12
print(id(a))
a=20.12
print(id(a))
# FOr int -5 to 256 use same id , for FLoat every variable will have different id even having same value.
#for string small string like "Hello" will have same address ut long string will have different address.
# TO prove these are immutale we have to mdify the variale value and check if memory adress is changig.
###################################################
Item_name="Computer"
Item_qty=10
Item_value=12000.11
print(Item_name)
print(Item_qty)
print(Item_value)
#Multiple assignment
x=y=z=1
print(x)
print(y)
print(z)
a,b,c=10,'ABCD',11.11
print(a)
print(b)
print(c)
#we can reuse the variable by simply assigning new values
x=100
print(x)
x="Python"
print(x)
#Exercise 1. swap two numbers
x=10
y=20
print("Before swapping",x,y)
x,y=y,x
print("After swapping",x,y)
print("********************Data Type*********************************")
#Numbers , String , List, Tuple , Dictionary
###Numbers --> int float double complex
a=1243
print(type(a))
print(id(a))
print(a)
b=-123
f1=11.11
f2=.22
a=15555.3838888888888888888888888888888888
b=1555544444444444444444555555555555555555555556666666666666.3838888888888888888888888888888888
c=222222222222233333333333333333333455555555555555555555999999999999999666666666666
print(a)
print(b)
print(c)
# No limit on Lenght of Integer and float. Only values after floating point (Decimal values use to roud off )
# Updating variables
count=100
print (count)
count+100
print(count)
count=count+100
count+=100
print(count)
# Compare variables:
a=10
b=a
c=10
print(a is b)
print(a is c) # Check memory address point to same object
print(a==b) # check values
print(a==c)
###complex numbers
aComplex= -8.3 - 1.4j
print("*********************")
print(aComplex)
print(type(aComplex))
print(id(aComplex))
print(aComplex.real)
print(type(aComplex.real))
print(id(aComplex.real))
print(aComplex.imag)
print(type(aComplex.imag))
print(id(aComplex.imag))
print(aComplex.conjugate())
### Boolean
print(True)
print(False)
print(True==1)
print(False==0)
#python assumes any non-zero and non-null values as TRUE. And if it is zero or null then it is assumed as false
#Use booleans numerically
foo=42
bar=foo <100
print('**************************')
print(bar)
print(bar+100)
print('%s'%bar) #if we print using %s it print true
print('%d'%bar) #if we print using %d it orints one
# Results of operations on objects of the same type yield results of the same type
# Results of operations on objects of mixed types are converted to the bigger type
# Python 3 integer division always yields a floating point result
5/3
5/3.0
5*3
5%3
5//3
5/-2
# The float() and int() functions return the argument in the specified type
#Argument may be the string representation of a numeric value
#Argument may be an expression
num='100'
num1=100
num2=100.12
print (int(num))
print (float(num))
print (int(num1))
print (float(num1))
print (int(num2))
print (float(num2))
num='100.12'
num1=100.12
print (int(num)) # Will throw error while converting STRING float values to int .
print (int(num1)) # NOT throw error and work fine while converting normal float to int.
print (float(num))
print (float(num1))
num='abc'
print (int(num)) # Will throw error
print (float(num)) # Will throw error
print (int(9/5))
print (int(9/5.0))
#print (int('9/5')) # Throw an error : int() method can not have STRING expressions.
print (float(9/5.0))
#print (float('9/5.0')) # Throw an error: float() method can not have STRING expressions.
# Converting Int/Float to String
num=100
print(str(num))
#The oct(), hex(), and bin() functions return the argument as a string in the specified base
num1 = 12
print(oct(num1))
print(hex(num1))
print(bin(num1))
Oct,Hex, bin to base 10
print(int(0b1100))
print(int(0xc))
#Delete Variable:
del var1[,var2[,var3[....,varN]]]]
|
#Decision making
#Yield a Boolean True or False value
# • The strings 'True' and 'False' both evaluate to Boolean True
#Types of conditional expressions
# Object identity, is
# Arithmetic relational; e.g., > or ==
# Strings use the same equality and inequality operators as numeric objects
# Several simple conditions joined by Boolean operators
# and yields True if both operands are True
# or yields True if either is True
# not reverses the Boolean value
"""Begin with a header statement that is terminated by a colon, :
Followed by a group of statements that are syntactically treated as a unit—a suite
• A code block
• For example: a loop body
Following statements are tied to the header based on the same
indentation
• One of Python’s readability features
• Python Enhancement Proposal (PEP) 8 recommends indentation of four spaces
End of code block detected by lack of indentation
Or an empty line if entering statements into the interpreter"""
#Evaluates an expression’s Boolean value and executes the associated block
• False is 0, empty string, empty collection, and None and Boolean False; anything else is considered True
# simple if else
a=10
if a==10:
print("Hello")
else:
print("Mpt Hello")
# Other type of if else:
a=100
#Type1
if a is 10 :
print("Hello User")
print("statement2")
print("Statement3") #This statement is not associated with if block.
#Type2
if a== 100 :
print("Using == operator to check equality")
#Type3 with parenthesis
if (a==100): print("value is 100")
print("Good Bye !!!")
#Type4
num1=10
if num1:
print("True")
print(num1)
#Type5
num2=0
if num2:
print("True")
print(num2)
print("Normal prog execution starts here...1")
#Type6
flag=None
if flag:
print("True")
print("Normal prog execution starts here...2")
#Type7 #oops python is case sensitive and T is capital here in True
var=True
if var:
print("It's True")
# Syntax of If and elif. The block associated with first condition that yields True is executed• The else: block is executed if no condition yields True.
if conditionA:
blockA
elif conditionB:
blockB
elif conditonC:
blockC
else:
blockD
restOfCode
#####
# As soon as the first criteri wil match the other conditions will not be checked.
a=10
if a>5:
print("Helo")
elif a>7:
print ("Hi")
elif a>9:
print('Hey')
else:
print('Not hello')
#python assumes any non-zero and non-null values as TRUE. And if it is zero or null then it is assumed as false
#Evaluates an expression’s Boolean value and executes the associated block
• False is 0, empty string, empty collection, and None; anything else is considered True
#Try with a=0,[],(),'',None,True,False,'True','False'
a='True'
if a:
print("Hello")
else:
print("Mpt Hello")
#---------- IF ELSE ---------------------
age=19
if age > 18:
print("Welcome to vote")
print("statement 1")
else :
print("Need to wait")
print("statement 2")
print("Normal program starts here")
#---------- ELSE IF Ladder -------------------
a=10
if (a>=20):
print("Condition is true")
elif (a>=10):
print("Checking second value")
else:
print("All conditions are false")
# Switch case with Python .
choice='a'
choice=input("Enter your choice among a,b,c")
if choice == 'a':
function_a()
elif choice == 'b':
function_b()
elif choice == 'c':
function_c()
else:
print "Invalid choice."
#----------- NESTED IF ELSE ------------------------
num=100
if num>= 200:
print("True")
else:
if num>=150:
print("Checking second value")
else:
print("All conditions are false")
#---- AND Or operator : Multi comparison in if else.
x=False
y=True
if x and y:
print('Both x and y are True')
# Multi condition : AND and OR rule will be followed..if all true then true , if anything false then all false.
a=10
b=20
c=30
if a<b<c:
print('Hello')
## and/or condition in if:
a=200
b=300
c=50
if (a==200 and b==300):
print("value is 100")
print("Good Bye !!!")
# If with in statement: simiar as is statement.
name="Sachin"
listOfPlayers=["Rahul","Saurav","Sachin"]
if name in listOfPlayers:
print("Selected in team")
# The pass Statement: Explicitly does nothing,Serves as a placeholder where a statement is required
if not sea:
pass
else:
print ('Hello')
#code optimization write it in single line
#if n is greater than 500, n is multiplied by 7, otherwise n is divided by 7
n=150
result= n*7 if n> 500 else n/7
print(result)
#***************** PROG TIP **********************************************************
'''
0 is false; all other numbers are true.
An empty string ("") is false, all other strings are true.
An empty list ([]) is false; all other lists are true.
An empty tuple (()) is false; all other tuples are true.
An empty dictionary ({}) is false; all other dictionaries are true.
The following are defined as having false values in python
None
False (Boolean)
Any numeric zero:
0 (integer)
0.0 (float)
0L (long integer)
0.0+0.0j (complex)
"" (empty string)
[] (empty list)
() (empty tuple)
{} (empty dictionary)
'''
#Exercise 1. write a program to accept number from user and check its data type
|
#Iterators in Python:
#Iterator in python is any python type that can be used with a ‘for in loop’. Python lists, tuples, dicts and sets are all examples of inbuilt iterators. These types are iterators because they implement following methods. In fact, any object that wants to be an iterator must implement following methods.
"""1) __iter__ method that is called on initialization of an iterator. This should return an object that has a next or __next__ (in Python 3) method.
2) next ( __next__ in Python 3) The iterator next method should return the next value for the iterable. When an iterator is used with a ‘for in’ loop, the for loop implicitly calls next() on the iterator object. This method should raise a StopIteration to signal the end of the iteration.
#Iterable Object : By default python for loop use the same method internally for iteration.
#The iter() built-in function returns an iterable object
#The __next__() method provides each element
#• Raises the StopIteration exception when sequence is exhausted
airports = ['LAX', 'HNL', 'YYZ']
airport_iter = iter(airports)
airport_iter.__next__()
>>> airport_iter.__next__()
'HNL'
>>> airport_iter.__next__()
'YYZ'
>>> airport_iter.__next__()
Traceback (most recent call last): # Exception raised when iteration is complete
"""
########### Yield and Generator
#Return sends a specified value back to its caller whereas Yield can produce a sequence of values. We should use yield when we want to iterate over a sequence, but don’t want to store the entire sequence in memory.
#The yield keyword in Python is used to create generators. A generator is a type of collection that produces items on-the-fly and can only be iterated once. By using generators you can improve your application's performance and consume less memory as compared to normal collections, so it provides a nice boost in performance. IN normal we use range funcation in which the iterable object is actually created on which the iteration happens. This object consume the memory so by using generator we can create the collection on the fly which can be used once and do not need memory space as it is not stored.
#Lists or any iterable collection object like tuple ,set, dict keys store all of the elements in memory at once, whereas generators "create" each item on-the-fly, displays it, and then moves to the next element, discarding the previous element from the memory.
#you can iterate over a list or any iterable collection object like tuple ,set, dict keys as many times as you want but you can iterate over a generator only once. To iterate again, you must create the generator again.
### Yield: Yield is a keyword which is used to create generator in python. Yield is similar to keyword "return" which is used in funcation to return the result. The difference between "return" and "yield" is as return give the value at once (final value) and yield can give the value for multiple times. Like if we have list of elemets , return will give the whole list and yield can give one element of list at a time. If we return whole list it requires to store the list in memory , in yield as each element is getting reutrened on the fly we do not need to store so it is used in generator and ultimately saves memory and also be fast.
# Suppose we need a itertator as square of values given as list
def cube_numbers(nums):
cube_list =[]
for i in nums:
cube_list.append(i*i)
return cube_list # Here we are returning the list . so we are returning the whole value at once. we are returning the iterable object as list of sqaue value of nums.
cubes = cube_numbers([1,2,3,4,5]) # now cubes can be used as iterable object . This is same as normal
print(type(cubes),cubes)
for temp in cubes: # here we are iterating over list cubes and this need a memory to store the cubes list. If we use random keyword also , that also created a list and need memory space.
print(temp)
## Same iterable object by using generator:
def cube_numbers(nums):
for i in nums:
yield(i**3) # Here instead ot return we have used yield which will make it generator. we do not need to store the output in any variable like we did in above to store it in cube_list. Although cube_numbers is method it can duirectly be used as genertor object.
cubes = cube_numbers([1, 2, 3, 4, 5]) #Now, when cube_number function is called, a generator is returned
print(type(cubes),cubes)
for temp in cube_numbers([1, 2, 3, 4, 5]): # here we are iterating over method cube_numbers which weill give the genertor object. we do not have any list created here so no memory wastage.
print(temp)
#In the above script, the cube_numbers function returns a generator(as yield is used) instead of list of cubed number. It's very simple to create a generator using the yield keyword. Here we do not need the temporary cube_list variable to store cubed number, so even our cube_numbers method is simpler. Also, no return statement is needed, but instead the yield keyword is used to return the cubed number inside of the for-loop.
# Another example:
# A generator function that yields 1 for first time, 2 second time and 3 third time
def simpleGeneratorFun():
yield 1
yield 2
yield 3
# Driver code to check above generator function
for value in simpleGeneratorFun():
print(value)
# Example to create generator on the fly for any lenght value:
1
def genfuncation():
i = 1;
# An Infinite loop to generate yield.
while True:
yield i # we can have i*i if we need iterable of square of all elements or modifiy the i as per our iterable object requirement, like for all even number we can have i+1 and so.
i = i+1 # Next execution resumes
# from this point
for num in genfuncation():
if num > 10:
break
print(num)
# Excersice: A Python program to generate squares from 1 to 100 using yield and therefore generator
# An infinite generator function that prints
# next square number. It starts with 1
def nextSquare():
i = 1;
# An Infinite loop to generate squares
while True:
yield i*i
i += 1 # Next execution resumes
# from this point
# Driver code to test above generator
# function
for num in nextSquare():
if num > 100:
break
print(num)
############## Decorator ###################
#A decorator is a design pattern in Python that allows a user to add new functionality to an existing object without modifying its structure. Decorators are usually called before the definition of a function you want to decorate.
# Decorators allow us to wrap another function in order to extend the behavior of wrapped function, without permanently modifying it.–
# To understand lets see the powerness of funcation first.
#Functions are objects; they can be referenced to, passed to a variable and returned from other functions as well.Functions can be defined inside another function and can also be passed as argument to another function.
#Essentially, decorators work as wrappers,
# modifying the behavior of the code before and after a target function execution,
# without the need to modify the function itself,
#augmenting the original functionality, thus decorating it.
#********* What you need to know ***********************
#in python functions are first class citizens they are objects and that means we can do
#a lot of useful stuff with them
# Different funcation capabilities to be understand before getting into decorator:
#A) Assigning Functions to Variables
#To kick us off we create a function that will add one to a number whenever it is called. We'll then assign the function to a variable and use this variable to call the function.
def plus_one(number):
return number + 1
add_one = plus_one
add_one(5)
#B)Defining Functions Inside other Functions
#Next, we'll illustrate how you can define a function inside another function in Python.
def plus_one(number):
def add_one(number):
return number + 1
result = add_one(number)
return result
plus_one(4)
#C) Passing Functions as Arguments to other Functions
#Functions can also be passed as parameters to other functions. Let's illustrate that below.
def plus_one(number):
return number + 1
def function_call(function):
number_to_add = 5
return function(number_to_add)
function_call(plus_one)
# D) Functions Returning other Functions
#A function can also generate another function.
def hello_function():
def say_hi():
return "Hi"
return say_hi
hello = hello_function()
hello()
# E) Nested Functions have access to the Enclosing Function's Variable Scope
#python allows a nested function to access the outer scope of the enclosing function. This is a critical concept in decorators -- this pattern is known as a Closure.
def print_message(message):
"Enclosong Function"
def message_sender():
"Nested Function"
print(message) # Here enclosing funcation message_sender is having access to 'message'
message_sender()
print_message("Some random message")
# In Decorators, functions are taken as the argument into another function and then called inside the wrapper function.
#Syntax:
@gfg_decorator # Decorator.
def hello_decorator():
print("Gfg")
'''Above code is equivalent to -
def hello_decorator():
print("Gfg")
hello_decorator = gfg_decorator(hello_decorator)'''
#In the above code, gfg_decorator is a callable function, will add some code on the top of some another callable function, hello_decorator function and return the wrapper function.
# Decorator example:
# defining a decorator
def hello_decorator(func):
# inner1 is a Wrapper function in which the argument is called .
# inner1 function can access the outer local functions like in this case "func" .
def inner1():
print("Hello, this is before function execution")
func() # calling the actual function now inside the wrapper function.
print("This is after function execution")
return inner1
# Now we can use the decorator in our methods in two different syntax.
#syntax 1:
@hello_decorator # Here we are using decorator funcation in which funcation_to_be_used will be passed as an arguments. like hello_decorator(function_to_be_used).
def function_to_be_used():
print("This is inside the function !!")
function_to_be_used()
# Syntax 2: (This is equivalent to syntax 1 , ultimatley syntax 1 will also be converted something as below)
def function_to_be_used():
print("This is inside the function !!") # passing 'function_to_be_used' inside the decorator to control its behavior or add to its behaviour
function_decorator_call = hello_decorator(function_to_be_used)
# calling the function
function_decorator_call()
# Excersise 1:decorator that will convert a sentence to uppercase.
def uppercase_decorator(function):
def wrapper():
func = function()
make_uppercase = func.upper()
return make_uppercase
return wrapper
def say_hi():
return 'hello there'
decorate = uppercase_decorator(say_hi)
decorate()
# With east syntax:
@uppercase_decorator
def say_hi():
return 'hello there'
say_hi()
# Excersise 2: Applying Multiple Decorators to a Single Function
def split_string(function):
def wrapper():
func = function()
splitted_string = func.split()
return splitted_string
return wrapper
@split_string
@uppercase_decorator
def say_hi():
return 'hello there'
say_hi()
# Exc ersie 3: Accepting Arguments in Decorator Functions
#Sometimes we might need to define a decorator that accepts arguments. We achieve this by passing the arguments to the wrapper function. The arguments will then be passed to the function that is being decorated at call time.
def decorator_with_arguments(function):
def wrapper_accepting_arguments(arg1, arg2):
print("My arguments are: {0}, {1}".format(arg1,arg2))
function(arg1, arg2)
return wrapper_accepting_arguments
@decorator_with_arguments
def cities(city_one, city_two):
print("Cities I love are {0} and {1}".format(city_one, city_two))
cities("Nairobi", "Accra")
############### Lamda Function ###############
# A lambda function is a small anonymous function .
# A lambda function can take any number of arguments, but can only have one expression
#One is free to use lambda functions wherever function objects are required.
#You need to keep in your knowledge that lambda functions are syntactically restricted to a single expression.
#Lambda expression also known as anonymous fun. becoz used only one time becoz of that we dont give name nor use def keyword.so instead of keyword def and fun name we replace it with keyword lambda
#NOTE:- lambda is an expression not a statement
#lambda's body is a single expression not a block of statements.
#Becoz it is limited to an expression a lambda is less general that a def.
#we can only squeeze design to limit prog neating.
#lambda is designed for coding simple functions and def handles larger tasks.
# By using lambda you can simplifies the syntax of simple or small funcation:
#syntax:
lambda arguments(argument1, argument2, ...argumentn) : expression
# Example:
# showing difference between def() and lambda().
def cube(y): # This is simple method .
return y*y*y;
print(cube(5))
g = lambda y: y*y*y # this is lambda expression equivalent to above method. lambda funcation returns funcation object and it is quite faster.
print(g(7))
#The power of lambda is better shown when you use them as an anonymous function inside another function.
#Say you have a function definition that takes one argument, and that argument will be multiplied with an unknown number:
# Example:
x = lambda a : a + 10
print(x(5))
# Lambda funcation with multiple argument
x = lambda a, b : a * b
print(x(5, 6))
# lambda function inside another funcation
def myfunc(n):
return lambda a : a * n # here funcation myfunc is returning the another funcation.
mydoubler = myfunc(2) #mydoubler will have the funcation object and 2 will be passed as n.
mytripler = myfunc(3)
print(mydoubler(11)) # 11 will be passed as value a.
print(mytripler(11))
#we can use lambda in conjuction with map and filter
#Now in case of map we do write a function and then call inside map
#this thing can be more optimised by using lambda
li1=list(map(lambda num:num**2 , mynumbers))
print(li1)
#covert checkevene fun to lambda
li2=list(filter(lambda num:num % 2 ==0 ,mynumbers))
print(li2)
#write a lambda to grab first char of names
allnames=['Sachin','Ashish','Rahul','Mahendrasingh']
li3=list(map(lambda name:name[0],allnames))
print(li3)
#write a lambda to reverse the names
li4=list(map(lambda n:n[::-1],allnames))
print("Reversed names ---->",li4)
#Example
allcars=(lambda a='FordFigo',b='Audi',c='Swift':a+b+c)
print(allcars('Accent','Wolkswagen'))
|
n = int(input())
for i in range(n):
arr = input().split()
ans = []
for word in arr:
ans.append(word[::-1])
print(*ans)
|
A = " " + input()
B = " " + input()
matrix = [[""]*(len(B)) for _ in range(len(A))]
for i in range(1, len(A)):
for j in range(1, len(B)):
if A[i] == B[j]:
matrix[i][j] = matrix[i-1][j-1] + A[i]
else:
if len(matrix[i - 1][j]) > len(matrix[i][j - 1]):
matrix[i][j] = matrix[i-1][j]
else:
matrix[i][j] = matrix[i][j-1]
print(len(matrix[len(A)-1][len(B)-1]))
print((matrix[len(A)-1][len(B)-1]))
|
alphabet = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']
ans = [-1 for i in range(26)]
word = input()
for i in range(len(word)):
for j in range(26):
if word[i] == alphabet[j] and ans[j] == -1:
ans[j] = i
break
for i in range(len(ans)):
print(str(ans[i]) + " ", end='')
|
"""
lumberjack.py
Simple tool that can be used to generate 2D BSP trees by hand. Currently
limited to only vertical and horizontal partitions, because I'm bad at
geometry. :(
This tool uses the graphics.pyd extension module, which is an old wrapper
around Pygame that I wrote a while back. graphics.pyd was intended to
encapsulate Pygame functions into stupidly easy function calls so I could
more easily teach beginners some basic graphics programming. However, I found
that it's also stupidly useful for easily writing small graphical tools
without needing a bunch of of boilerplate, which is why I use it for
lumberjack.py. Since graphics.pyd suffers from some performance issues if you
give it a lot of draw commands in a tight loop, I don't use it for vismain.py.
Thankfully, lumberjack.py does not require a lot of individual draw commands,
so graphics.pyd works perfectly fine in this tool.
"""
import sys
import graphics
from bsp import BSPTree, BSPElement, BSPNode, BSPLeaf
BLOCK_SIZE = 32
BL_WIDTH = 32
BL_HEIGHT = 24
WIDTH = BL_WIDTH * BLOCK_SIZE
HEIGHT = BL_HEIGHT * BLOCK_SIZE
FRAMERATE = 60
COLOR_BLACK = (0, 0, 0)
COLOR_GRAY = (128, 128, 128)
COLOR_WHITE = (255, 255, 255)
COLOR_RED = (255, 0, 0)
COLOR_MAGENTA = (255, 0, 255)
COLOR_CYAN = (0, 255, 255)
def draw_grid(canvas):
for i in xrange(BL_WIDTH):
x = i * BLOCK_SIZE
start = (x, 0)
end = (x, HEIGHT)
canvas.draw_line(start, end, COLOR_GRAY)
for i in xrange(BL_HEIGHT):
y = i * BLOCK_SIZE
start = (0, y)
end = (WIDTH, y)
canvas.draw_line(start, end, COLOR_GRAY)
def snap_to_grid(x, y):
""" Returns the grid line intersection nearest to the given point. """
return (
int(round(float(x) / BLOCK_SIZE) * BLOCK_SIZE),
int(round(float(y) / BLOCK_SIZE) * BLOCK_SIZE),
)
def main():
c = graphics.Canvas(WIDTH, HEIGHT)
c.show()
c.set_title("Lumberjack Tree Carver")
if len(sys.argv) > 1:
bspFilePath = sys.argv[1]
with open(bspFilePath, 'r') as f:
data = f.read()
b = BSPTree.from_vdf(data)
else:
bspFilePath = 'out-bsp.vdf'
b = BSPTree(WIDTH, HEIGHT)
startPos = None
clickLock = False
while c.is_active():
mousePos = c.get_mouse_pos()
snappedCoords = snap_to_grid(*mousePos)
b.draw_leaves(c)
draw_grid(c)
b.draw_partitions(c)
leaf = b.leaf_from_coords(*mousePos)
assert leaf
# for neighbor in leaf.iter_neighbors():
# c.draw_box(
# neighbor.get_top_left(),
# neighbor.get_bottom_right(),
# COLOR_CYAN,
# )
c.draw_box(leaf.get_top_left(), leaf.get_bottom_right(), COLOR_RED)
keysPressed = c.get_keys_pressed()
if c.get_mouse_l():
if not startPos:
startPos = snappedCoords
elif c.get_mouse_r():
if not clickLock:
leaf.solid = not leaf.solid
clickLock = True
elif keysPressed['delete']:
if not clickLock:
b.merge_leaf(leaf)
clickLock = True
elif keysPressed['left ctrl'] and keysPressed['s']:
if not clickLock:
with open(bspFilePath, 'w') as f:
f.write(b.to_vdf())
clickLock = True
else:
if startPos:
endPos = snappedCoords
if startPos != endPos:
left, top, right, bottom = leaf.bounds
if startPos[0] == endPos[0]:
orientation = BSPNode.Orientation.VERTI
partition = startPos[0]
if not (left < partition < right):
partition = None
elif startPos[1] == endPos[1]:
orientation = BSPNode.Orientation.HORIZ
partition = startPos[1]
if not (top < partition < bottom):
partition = None
else:
orientation = None
partition = None
if None not in (orientation, partition):
b.divide_leaf(leaf, orientation, partition)
startPos = None
if clickLock:
clickLock = False
if startPos:
c.draw_line(startPos, snappedCoords, COLOR_MAGENTA)
c.fill_circle(snappedCoords, 5, COLOR_RED)
c.refresh()
graphics.wait_framerate(FRAMERATE)
return 0
if __name__ == '__main__':
sys.exit(main())
|
from os import read
buffer = None
#readString reads a string to a buffer
def readString():
global buffer
buffer = read(0, 1000) #reads to the buffer
if(buffer == 0): #Buffer has reached the end of the file
return "EOF"
return buffer
def readLine():
global buffer
line = ""
i = 0
if(buffer == None): #if the buffer is empty
buffer = readString()
while len(buffer) > 0:
line += chr(buffer[i]) #add to the line
if ("\n" in line): #encounters a new line
buffer = buffer[i + 1:]
return line
i += 1
if(i == len(buffer)): #resets the buffer
i = 0
buffer = readString()
return line
#def main():
# b = readLine()
# print(b)
# main() |
# Declare the variables input from the user :
P = int(input("Enter the Principle Amount Please :"))
n = int(input("Enter the Number of Years :"))
r = float(input("Enter the rate of Interest :"))
# Declare the formula
A = P*(1+r/100)**n
# The Final Amount
print("The Total Amount including compound interest is :", A) |
#You have been hired by the University of Data Science to manage their students' records. Your job is to create the student management system for the university. Let's try to build the system using basic Python operations.
#After completing this project, you will get to know how to solve basic Python problems. In this project, you will be applying the following concepts:
#Mathematical operations
#List operations
#Dictionary operations
#String indexing and formatting
class_1 = ['Geoffrey Hinton','Andrew Ng','Sebastian Raschka','Yoshua Bengio']
class_2 = ['Hilary Mason','Carla Gentry','Corinna Cortes']
new_class = class_1.extend(class_2)
print(new_class)
new_class.append('Peter Warden')
print("Updated Class :", new_class)
new_class.remove('Carla Gentry')
print("Updated Class :", new_class)
print("="*80)
Geoffrey_courses = {'Maths':65, 'English':70,'History':80,'French':70,'Science':60}
#print("The marks for Geoffrey Hinton are : ",Geoffrey_courses)
#total = sum(Geoffrey_courses)
#print("The total marks of Geoffrey Hinton from 500 is :", total)
#percentage = total/500*100
#print("The Percentage Geoffrey scored is : ", percentage)
mathematics = {'Geoffrey Hinton': 78,'Andrew Ng': 95,
'Sebastian Raschka': 65,
'Yoshua Benjio': 50,
'Hilary Mason': 70,
'Corinna Cortes': 66,
'Peter Warden': 75}
topper = max(mathematics, key=mathematics.get)
print(topper) |
from unittest import TestCase
from blog.blog import Blog
class BlogTest(TestCase):
def test_create_blog(self):
b = Blog('Test', 'Test Author')
self.assertEqual('Test', b.title)
self.assertEqual('Test Author', b.author)
self.assertListEqual([], b.posts)
# same assert as above, just another way to do it:
# self.asertEqual(0, len(b.posts))
# print("tests in test_create_blog complete")
def test_repr(self):
b = Blog('Title', 'Author')
c = Blog('My Day', 'Bob')
self.assertEqual(b.__repr__(), 'Title by Author (0 posts)')
self.assertEqual(c.__repr__(), 'My Day by Bob (0 posts)')
# print("tests in test_repr complete")
def test_repr_multiple_posts(self):
b = Blog('Title', 'Author')
b.posts = ['post1']
b2 = Blog('My Day', 'Bob')
b2.posts = ['Test Blog', 'another']
self.assertEqual(b.__repr__(), 'Title by Author (1 post)')
self.assertEqual(b2.__repr__(), 'My Day by Bob (2 posts)')
# print("tests in test_repr_multiple_posts complete")
def test_create_post_in_blog(self):
b = Blog('Test', 'Test Author')
b.create_post('Test Post', 'Test Content')
self.assertEqual(len(b.posts), 1)
self.assertEqual(b.posts[0].title, 'Test Post')
self.assertEqual(b.posts[0].content, 'Test Content')
|
#!/usr/bin/env python
import os
import re
import sys
def convert_roman_to_arabic(roman):
"""Converts Roman numerals to Arabic number equilvalents
@param num: Roman numeral to convert
@type num: str
@rtype: int
@return: Integer equivalent of Roman numeral
"""
roman_numeral_pattern = '^M{0,3}(CM|CD|D?C{0,3})(XC|XL|L?X{0,3})(IX|IV|V?I{0,3})$'
if not re.search(roman_numeral_pattern, str(roman)):
raise ValueError("Invalid Roman numerals")
d = dict()
d["I"] = 1
d["IV"] = 4
d["V"] = 5
d["IX"] = 9
d["X"] = 10
d["XL"] = 40
d["L"] = 50
d["XC"] = 90
d["C"] = 100
d["CD"] = 400
d["D"] = 500
d["CM"] = 900
d["M"] = 1000
result = None
try:
result = d[roman[-1]]
for i in range(len(roman)-2, -1, -1):
if d[roman[i]] < d[roman[i+1]]:
result -= d[roman[i]]
else:
result += d[roman[i]]
except Exception as e:
raise e
return result
def convert_arabic_to_roman(num):
"""Converts Arabic number to Roman numerals equilvalents
@param num: Arabic number to convert
@type num: int
@rtype: str
@return: String containing Roman numerals
"""
roman = ""
roman_numerals = [
"M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"]
numbers = [
1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1]
try:
for i in range(len(numbers)):
while num >= numbers[i]:
roman += roman_numerals[i]
num = num - numbers[i]
except Exception as e:
raise e
return roman
def _print_usage(error_msg=None):
""" Prints usage
@param error_msg: Error message to print
@type error_msg: str
"""
if error_msg:
sys.stderr.write(error_msg + "\n")
sys.stderr.write("-------------------------------------\n")
sys.stderr.write(sys.argv[0] + " mode=<mode> <number>\n")
sys.stderr.write("Mode=1 for Arabic to Roman conversion\n")
sys.stderr.write("Mode=2 for Roman to Arabic conversion\n")
sys.stderr.write(str(type(e)))
if __name__ == "__main__":
exit_code = os.EX_OK
try:
conversion_mode = sys.argv[1].split("=")[1]
result = None
if conversion_mode == "1":
# Mode is Arabic to Roman conversion
result = convert_arabic_to_roman(int(sys.argv[2]))
else:
# Mode is Roman to Arabic conversion
result = convert_roman_to_arabic(sys.argv[2])
sys.stdout.write(str(result))
sys.stdout.write("\n")
sys.stdout.flush()
except IndexError:
exit_code = os.EX_USAGE
_print_usage("Too few arguments supplied")
except ValueError:
exit_code = os.EX_DATAERR
_print_usage("Incorrect input format found")
except Exception as e:
exit_code = os.EX_SOFTWARE
_print_usage("Internal error occured")
finally:
sys.exit(exit_code)
|
# dictionary
students = {'a':"ram", 'b': "govind", 'c': "asura"}
student = ["ram","govind","asura"]
print(students)
print(students['a'])
print(len (students))
for i,v in students.items ():
print(i,v)
for j in student:
print(j)
|
import unittest
from city import Neighborhood
class NeighborhoodTest(unittest.TestCase):
def testNeighborhood(self):
sqMiles : float = 4.5
education : str = "Highschool"
neighborhood : Neighborhood = Neighborhood(sqMiles, education)
self.assertEqual(neighborhood.sqMiles, sqMiles)
self.assertEqual(neighborhood.education, education)
if __name__ == '__main__':
unittest.main() |
#자료구조필요하니까
stack =[]
def push(item):
stack.append(item)
def pop():
if len(stack) == 0:
print("Stack is empty") #비어있는지 고려해야함!
return
else:
return stack.pop()
push(1)
push(2)
push(3)
print(pop())
print(pop())
print(pop()) |
arr=[1,2,3]
N=3
#sel안만들고, arr의 위치를 변경하면서 순열을 바꾸는것
def perm(idx):
if idx==N:
print(arr)
return
for i in range(idx,N):
arr[idx],arr[i]=arr[i],arr[idx]
perm(idx+1)
arr[idx],arr[i]=arr[i],arr[idx]
perm(0) |
import sys
sys.stdin = open("input.txt", "r")
nums=[]
for _ in range(9):
nums.append(int(input()))
MAX=max(nums)
print(MAX,nums.index(MAX)+1,sep='\n') |
import sys
sys.stdin=open('input.txt')
def reverse(s):
global tmp
for j in s[::-1]:
tmp+=j
reversed.append(tmp)
if __name__=='__main__':
n=int(input())
nums=list(input().split())
reversed=[]
tmp=''
for i in range(n):
reverse(i) |
import requests
import json
import csv
# Define the URL of the API
url = "https://api.steampowered.com/ISteamApps/GetAppList/v2/"
# Define the query parameters
params = {
'format':'json',
}
# Make a GET request to the URL with the parameters
response = requests.get(url, params=params)
if response.status_code == 200:
data=response.json()
json_data=json.dumps(data)
with open("data.json", "w") as f:
# Write the JSON string to the txt file
f.write(json_data)
else:
# Print an error message if the request failed
print(f"Request failed with status code {response.status_code}")
|
def rendezett_e(lista) :
"""
Fuggveny ami eldonti, hogy a parameterkent kapott listaban
novekvo sorrendben szerepelnek-e az elemek.
Kis-nagybetukre mukodik ekezetesekre nem.
"""
if type(lista[0]) is str :
for i in range(1,len(lista)) :
#if lista[i - 1] > lista[i] : # kis - nagy betukre:
if lista[i - 1].upper() > lista[i].upper() :
return False
else :
for i in range(1,len(lista)) :
if lista[i - 1] > lista[i] :
return False
return True
#
def main() :
lista1 = [10, 28, 30, 41, 57, 68, 72, 81, 97]
lista2 = ["alma", "barack", "cekla", "zeller", "dinnye", "egres", "fuge"]
lista3 = ["alma", "barack", "cekla", "dinnye", "egres", "fuge"]
lista4 = ["alma", "barack", "Cekla", "dinnye", "egres", "fuge"]
lista5 = ["alma", "barack", "cekla", "dinnye", "egres", "fuge"]
print(rendezett_e(lista1))
print(rendezett_e(lista2))
print(rendezett_e(lista3))
print(rendezett_e(lista4))
print(rendezett_e(lista5))
#
# https://stackoverflow.com/questions/6523791/why-is-python-running-my-module-when-i-import-it-and-how-do-i-stop-it/6523852#6523852
if __name__ == "__main__" :
main()
#
|
class Customer:
def __init__(self):
"""constructor to instantiate customer object"""
self.bikes = 0
self.rentalBasis = 0
self.rentalTime = 0
self.bill = 0
def requestBike(self):
"""Customer request bike to rent"""
bikes = input("How many bikes would you like to rent?")
try:
bikes = int(bikes)
except ValueError:
print("Thats not a positive integer")
return -1
if bikes < 1:
print('rent atleast one bike')
else:
self.bikes = bikes
return self.bikes
def returnBike(self):
"""customer return bike to shop"""
if self.rentalBasis and self.rentalTime and self.bikes:
return self.rentalTime, self.rentalBasis, self.bikes
else:
return 0,0,0
|
# First program
number = range(101)#create a list of 100 values
even_list = list()#create list for even values
odd_list = list()#create list for odd values
even = 0#number of even values
odd = 0#number of odd values
for i in number:#count the number of even and odd
if i % 2 == 0:
even += 1
else:
odd += 1
print(even)
print(odd)
for i in number:#select odd values
if i % 2 != 0:
odd_list.append(i)
print(odd_list)
for i in number:#select even values
if i % 2 == 0:
even_list.append(i)
print(even_list)
#Thecond progman
dict_countries = {"Austria": "Vienna",
"Armenia": "Yerevan",
"Belarus": "Minsk",
"Bulgaria": "Sofia",
"Germany": "Berlin",
"France": "Paris",
"Ukraine": "Kiev",
"Sweden": "Stockholm"}#create a dictionary with countries and capitals
list_countries = ("Ukraine", "USA", "Hungary", "England", "Poland", "Romania")#create a list with countries
for i in list_countries:#check the availability of countries from the list in the dictionary
if i in dict_countries:
print(dict_countries [i])#we display the result in case of coincidence in the form of the capital of the country
|
### This is part of Codecademy coding challenge
### Battleship with Python3 (single player version)
import random
## function to create boards for player
def create_board_computer():
board = {
'1A':' ', '2A':' ', '3A':' ', '4A':' ', '5A':' ',
'1B':' ', '2B':' ', '3B':' ', '4B':' ', '5B':' ',
'1C':' ', '2C':' ', '3C':' ', '4C':' ', '5C':' ',
'1D':' ', '2D':' ', '3D':' ', '4D':' ', '5D':' ',
'1E':' ', '2E':' ', '3E':' ', '4E':' ', '5E':' ',
}
ship_locs = random.sample(board.keys(), 6)
for loc in ship_locs:
board[loc] = 'O'
return board
def create_board_player():
board = {
'1A':' ', '2A':' ', '3A':' ', '4A':' ', '5A':' ',
'1B':' ', '2B':' ', '3B':' ', '4B':' ', '5B':' ',
'1C':' ', '2C':' ', '3C':' ', '4C':' ', '5C':' ',
'1D':' ', '2D':' ', '3D':' ', '4D':' ', '5D':' ',
'1E':' ', '2E':' ', '3E':' ', '4E':' ', '5E':' ',
}
ships_locs = []
print('Hey Player! Where do you wanna place your ships (enter 6 locations)')
while len(ships_locs) < 6:
loc = input()
if loc not in board.keys():
print('That\'s out of range!')
if loc in ships_locs:
print('The slot is occupied, dude!')
else:
ships_locs.append(loc)
for loc in ships_locs:
board[loc] = 'O'
return board
## function to display board in a readeable format
def display_board(board):
print('----------------------')
print('| ' + board['1A'] + ' | ' + board['2A'] + ' | ' + board['3A'] + ' | ' + board['4A'] + ' | ' + board['5A'] + ' |')
print('----------------------')
print('| ' + board['1B'] + ' | ' + board['2B'] + ' | ' + board['3B'] + ' | ' + board['4B'] + ' | ' + board['5B'] + ' |')
print('----------------------')
print('| ' + board['1C'] + ' | ' + board['2C'] + ' | ' + board['3C'] + ' | ' + board['4C'] + ' | ' + board['5C'] + ' |')
print('----------------------')
print('| ' + board['1D'] + ' | ' + board['2D'] + ' | ' + board['3D'] + ' | ' + board['4D'] + ' | ' + board['5D'] + ' |')
print('----------------------')
print('| ' + board['1E'] + ' | ' + board['2E'] + ' | ' + board['3E'] + ' | ' + board['4E'] + ' | ' + board['5E'] + ' |')
print('----------------------')
## function to play Battleship
def game():
## create boards for NPC and player
pc_board = create_board_computer()
player_board = create_board_player()
## display player's board
display_board(player_board)
## variables to control when the game ends
turn = 'Player'
pc_point = 6
player_point = 6
round = 0
## lists to keep track of player and NPC's moves
pc_moves = []
player_moves = []
for i in range(25):
if turn == 'Player':
print('----------------------')
print('\033[1mPlayer turn:\033[0m')
move = input()
if move not in player_board.keys():
print('You hit a homerun! It\'s just not a good thing in this game.')
elif move in player_moves:
print('C\'mon! You hit it twice! That is cheating.')
else:
if pc_board[move] == 'O':
pc_point -= 1
print(f'Nice shot, Player. {pc_point} to go!')
else:
print('Oh! That was a miss. Try harder next time.')
player_moves.append(move)
if turn == 'Computer':
print('----------------------')
print('\033[1mComputer turn:\033[0m')
move = random.sample(player_board.keys(), 1)
print(move[0])
if player_board[move[0]] == 'O':
player_point -= 1
print(f'Nice shot, Computer. {player_point} to go!')
elif move in pc_moves:
print('C\'mon! You hit it twice! That is cheating.')
else:
print('Oh! That was a miss. Try harder next time.')
pc_moves.append(move)
## check if the ships are all destroyed or no more turns
if pc_point == 0:
print('Congrats, Player! You destroyed all the NPC ships.')
break
if player_point == 0:
print('Game over! Your ships were all destroyed. See you at the bottom!')
break
if round == 24:
if pc_point == player_point:
print('No more turns and it\'s a tie.')
elif pc_point > player_point:
print('No more turns and you LOST.')
else:
print('No more turns and you WON. Congrats!')
## change player after each turn
if turn == 'Player':
turn = 'Computer'
else:
turn = 'Player'
print(f'\n\033[1mPlayer\'s point:\033[0m {player_point} | \033[1mComputer\'s point:\033[0m {pc_point}')
round += 1
restart = input('Do you want to play again? (Y/N)')
if restart == 'Y':
game()
else:
print('Good bye! See you next time.')
print("""
****** ** ********** ********** ** ******** ******** ** ** ** *******
/*////** **** /////**/// /////**/// /** /**///// **////// /** /**/**/**////**
/* /** **//** /** /** /** /** /** /** /**/**/** /**
/****** ** //** /** /** /** /******* /*********/**********/**/*******
/*//// ** ********** /** /** /** /**//// ////////**/**//////**/**/**////
/* /**/**//////** /** /** /** /** /**/** /**/**/**
/******* /** /** /** /** /********/******** ******** /** /**/**/**
/////// // // // // //////// //////// //////// // // // //
_ _
| |__ _ _ _ __ ___ __ _ _ __ __ _____ ___ ___ _ __ ___ _ __ _ _| |_ ___ _ __
| '_ \| | | | '_ ` _ \ / _` | '_ \ \ \ / / __| / __/ _ \| '_ ` _ \| '_ \| | | | __/ _ \ '__|
| | | | |_| | | | | | | (_| | | | | \ V /\__ \_ | (_| (_) | | | | | | |_) | |_| | || __/ |
|_| |_|\__,_|_| |_| |_|\__,_|_| |_| \_/ |___(_) \___\___/|_| |_| |_| .__/ \__,_|\__\___|_|
|_|
"""
)
game()
|
def bubble_sort(nums):
for i in range(len(nums)-1):
for j in range(len(nums) -1 -i):
if nums[j] > nums[j+1]:
temp = nums[j]
nums[j] = nums[j+1]
nums[j+1] = temp
return nums
nums = [6,5,4,3,2,1]
print(bubble_sort(nums))
nums = [-1, -2 ,-3, -4, -5, -6]
print(bubble_sort(nums)) |
def merge_sort(nums):
if len(nums) ==1:
return 1
middle = int(len(nums)/2)
left_half = nums[:middle]
right_half = nums[middle:]
merge_sort(left_half)
merge_sort(right_half)
i = 0
j = 0
k = 0
#merge the left and right subarrays based on values
while i<len(left_half) and j<len(right_half):
if left_half[i] < right_half[j]:
nums[k] = left_half[i]
i = i+1
else:
nums[k] = right_half[j]
j=j+1
k=k+1
#copy the rest of the remaining left out values from the left/right subarrays
while i<len(left_half):
nums[k] = left_half[i]
i=i+1
k=k+1
while j<len(right_half):
nums[k] = right_half[j]
j=j+1
k=k+1
nums = [5,4,3,2,1]
merge_sort(nums)
print(nums) |
class Counter():
def __init__(self, low, high):
self.low = low
self.current = low
self.high = high
def __iter__(self):
return self
def __next__(self):
if self.current <= self.high:
value = self.current
self.current +=1
return value
raise StopIteration
c = Counter(0, 5)
iter(c)
for x in Counter(0, 2):
print(x)
for y in c:
print(y) |
class Person:
def __init__(self):
self.name = "Default"
self.age = 0
self.skin_color = "Default"
a = 100
b = 3
c = a + b
print(c)
p = Person()
import pdb ; pdb.set_trace()
print(p.name) |
import unittest
def is_anagram(s1, s2):
if len(s1) != len(s2):
return False
if sorted(s1.replace(" ", "").lower()) != sorted(s2.replace(" ", "").lower()):
return False
return True
def is_anagram2(s1, s2):
if len(s1) != len(s2):
return False
storage = {}
for i in range(len(s1)):
char1 = s1[i].lower()
if char1 not in storage and char1 != " ":
storage[char1] = 1
else:
storage[char1] += 1
char2 = s2[i].lower()
if char2 not in storage and char2 != " ":
storage[char2] = -1
else:
storage[char2] -= 1
for k,v in storage.items():
if v != 0: return False
return True
class TestAnagram(unittest.TestCase):
def test_simple_anagram(self):
self.assertTrue(is_anagram("Debit card", "Bad credit"))
def test_simple_anagram2(self):
self.assertTrue(is_anagram2("Debit card", "Bad credit"))
if __name__ == "__main__":
unittest.main()
|
from Card import Card
import unittest
class CardTests(unittest.TestCase):
def test_create_card_with_correct_suite_and_value(self):
"""testing if card can be created"""
c1 = Card("Hearts", "A")
c2 = Card("Diamonds", "10")
self.assertIsInstance(c1,Card)
self.assertEqual(c1.suit, "Hearts")
self.assertEqual(c1.value, "A")
self.assertIsInstance(c2,Card)
self.assertEqual(c2.suit, "Diamonds")
self.assertEqual(c2.value, "10")
def test_create_card_with_incorrect_suite(self):
"""testing if exception raised when suit is incorrect"""
with self.assertRaises(ValueError):
c1 = Card("A","A")
def test_create_card_with_incorrect_value(self):
"""testing if exception raised when value is incorrect"""
with self.assertRaises(ValueError):
c1 = Card("Hearts","11")
def test_create_card_with_incorrect_suite_and_value(self):
"""testing if exception raised when suite and value is incorrect"""
with self.assertRaises(ValueError):
c1 = Card("B","11")
with self.assertRaises(ValueError):
c2 = Card(None, None)
if __name__ == "__main__":
unittest.main()
|
#tuples
x=1,2,3
xx=(1,2,3)
y=[1,2,3]
z='hello'
w=()
a=(1,)
b=(2)
c=2,
d=2
e=tuple(y)
print(x,type(x),y,type(y),z,type(z),w,type(w),a,type(a),b,type(b),c, type(c),d,type(d),e,type(e))
# , is the tuple indicator
print(e[0]) |
import math
def get_prime():
print "Enter a prime number"
p = int(raw_input())
for i in xrange(2, int(math.sqrt(p))):
if p % i == 0:
return 0
return p
def calc_pub_key(root, priv, prime):
return root ** priv % prime
def calc_priv_key(pub, priv, prime):
return pub ** priv % prime
prime = 0
while(prime == 0):
prime = get_prime()
print "Enter a number"
root = int(raw_input())
print "Enter Alice's private key"
a_priv = int(raw_input())
print "Enter Bob's private key"
b_priv = int(raw_input())
a_pub = calc_pub_key(root, a_priv, prime)
b_pub = calc_pub_key(root, b_priv, prime)
if(calc_priv_key(b_pub, a_priv, prime) == calc_priv_key(a_pub, b_priv, prime)):
print "Success!\tKey ==", calc_priv_key(b_pub, a_priv, prime)
else:
print calc_priv_key(b_pub, a_priv, prime), calc_priv_key(a_pub, b_priv, prime)
|
def fibb(a):
num = []
b=0
while b<a:
if b==0 or b==1:
num.append(1)
else:
num.append(num[b-2] + num[b-1])
b=b+1
return num
print(fibb(15)) |
# -*- coding: utf-8 -*-
"""
Created on Wed Dec 5 16:54:10 2018
@author: thais
"""
#Transposição de matriz
def transpor(A):
#print(len(A))
B=[]
for i in range(len(A)):
B.append(A[i])
for i in range(len(A)):
#print(i)
k = A[i]
for j in range(len(k)):
B[i][j]=A[j][i]
print(A)
transpor([[2,1,3],[4,5,6],[7,8,9]])
|
import pathlib
def create_file():
"""create a new file after first making sure the filename does not
already exist in the current working directory
"""
proposed_filename = input("\nWhat filename would you like? ")
while True:
path = pathlib.Path(proposed_filename)
# check for a previously existing file with that name
if ( path.exists() ):
print("\nThat filename already exists.")
# ask user for a new filename
proposed_filename = input("\nWhat should the filename be? ")
else:
newfile = open(proposed_filename, 'w')
newfile.close()
print("\nThe file " + proposed_filename + " has been created.\n")
# quit the while-loop
break
# call the function
create_file()
|
"""Scrape info about the five top-grossing movies for each year,
for 10 years. Get the title and rank of the movie, the year, and
how much money it grossed at the box office. Put the scraped data
into a CSV file.
"""
from bs4 import BeautifulSoup
import requests
import csv
def build_years_list(start):
"""create a list of 10 years counting backward from the start year"""
years = []
for i in range(0, 10):
years.append(start - i)
return years
years = build_years_list(2019)
# create a base url
base_url = 'https://www.boxofficemojo.com/year/'
# open new file for writing - this creates the file
csvfile = open("movies.csv", 'w', newline='', encoding='utf-8')
# make a new variable, c, for Python's CSV writer object -
c = csv.writer(csvfile)
# write a header row to the csv
c.writerow( ['year', 'rank', 'title', 'gross'] )
# scraper code for top five movies, 10 years
for year in years:
url = base_url + str(year) + "/"
page = requests.get(url)
soup = BeautifulSoup(page.text, 'html.parser')
table = soup.find( 'table' )
rows = table.find_all('tr')
# for each row that was read, write one row to the CSV file
for i in range(1, 6):
cells = rows[i].find_all('td')
gross = cells[7].text.strip('$').replace(',', '')
c.writerow( [year, cells[0].text, cells[1].text, gross] )
# close the file
csvfile.close()
print("The CSV is done!")
|
# a simple example of a "black box" function
# put in two words, and a string is returned
# a and b are parameters
# "love" and "Gators" are the arguments passed to the function
# the value of result is returned
def add_things(a, b):
result = (a * 3) + (b * 3)
return result
# the data returned by the function is stored in a new variable, output
output = add_things("love", "Gators")
# we can print the value of output, or we could send it to a database, etc.
print(output)
|
"""A first simple test-run of the BeautifulSoup module, using
a simple web page created just for this purpose.
"""
from urllib.request import urlopen
from bs4 import BeautifulSoup
# open a web page file
page = urlopen("https://weimergeeks.com/examples/scraping/example1.html")
# parse that to create a BeautifulSoup object
soup = BeautifulSoup(page, "html.parser")
# print the first H1 element in the file
print(soup.h1)
# print ONLY THE TEXT in the first H1 element in the file
print(soup.h1.text)
# get all the TD elements that have the class 'city'
city_list = soup.find_all( "td", class_="city" )
# print only the text from each of those TD elements
for city in city_list:
print( city.text )
# using find() gets only ONE element
# here we assign that element to a new variable, phone_number
phone_number = soup.find( id="call" )
# print only the text from the element with the id 'call'
print( phone_number.text )
# get the values of all the src attributes for all the IMG elements
# on the web page, and print them, one per line
image_list = soup.find_all('img')
for image in image_list:
print( image.attrs['src'] )
|
# tested March 2023
# run Selenium without seeing the browser
from selenium import webdriver
# new headless stuff
from selenium.webdriver.chrome.options import Options
chrome_options = Options()
chrome_options.add_argument("--headless=new")
driver = webdriver.Chrome(options=chrome_options)
from bs4 import BeautifulSoup
# fill in URL for page you want to scrape
driver.get('https://en.wikipedia.org/wiki/Antarctica');
page = driver.page_source
soup = BeautifulSoup(page, 'html.parser')
# example of scraping from one page
heds = soup.find_all('span', class_="mw-headline")
for hed in heds:
print( hed.text )
print("There are " + str( len(heds) ) + " headings in the list.")
driver.quit()
|
print("What is your name?")
name = input()
print("How old are you?")
age = input()
if name == 'Alice' and int(age) < 13:
print("How's Wonderland?")
elif name == 'Alice':
print("You are too old to enter through the looking glass, Alice.")
elif int(age) < 13:
print('This is only for Alice, kiddo.')
else:
print('You are not Alice, and you are 13 or older.')
|
# -*- coding: utf-8 -*-
import random
from collections import defaultdict
class GuessCityGameException(Exception):
def __init__(self, msg):
self.msg = msg
class GuessCity(object):
def __init__(self):
self.__allowed_cities = defaultdict(list)
self.__guessed_cities = set()
self.__asked_cities = set()
self.__city_name = "Unknown"
self.__whole_moves_count = 0
self.__attempts = 0
self.__ind = 1
with open("../resources/ru_cities.txt", "r", encoding='utf-8') as f:
for city in f:
city = city.strip()
if city:
self.__allowed_cities[city[0]].append(city)
@staticmethod
def get_city_name(city_name):
if '-' in city_name:
return "-".join([w.title() for w in city_name.split("-")])
elif ' ' in city_name:
return " ".join([w.title() for w in city_name.split()])
else:
return city_name.title()
def print_final_text(self):
if self.__whole_moves_count <= 5:
print("WOW! You are lucky!")
elif 5 < self.__whole_moves_count <= 8:
print("You have a great intuition!")
elif 8 < self.__whole_moves_count <= 12:
print("Very nice work!")
elif 12 < self.__whole_moves_count <= 18:
print("Not bad...")
else:
print("How long you have to solve puzzles!.. But not upset! :) Get ready for the next time!")
def choose_city(self):
self.move()
return input("Your answer: ").lower()
def __get_hint(self):
self.__ind += 1
self.__attempts = 0
if self.__ind == len(self.__city_name):
self.__ind = 1
self.choose_city()
else:
print("Well, I shall prompt you another letter!")
self.__shift_letter(self.__ind)
def get_guessed_city(self):
return self.__city_name
def __make_city_used(self):
self.__guessed_cities.add(self.__city_name)
self.__city_name = ""
def __make_city_asked(self, city_name):
self.__asked_cities.add(city_name)
def reset_current_params(self):
self.__make_city_used()
self.__clear_asked_cities()
self.__whole_moves_count = 0
self.__attempts = 0
self.__ind = 1
def __clear_asked_cities(self):
self.__asked_cities.clear()
def __was_city_asked(self, city_name):
return city_name in self.__asked_cities
def __was_city_guessed(self, city_name):
return city_name in self.__guessed_cities
def __is_city_exists(self, city_name):
return city_name in self.__allowed_cities[city_name[0]]
def __shift_letter(self, index):
if index == len(self.__city_name):
print(f"The guessed city was {self.__city_name}. This game was over :(")
else:
print(self.__city_name[:index] + "...")
def check_city(self, city_name):
if self.__was_city_asked(city_name):
raise GuessCityGameException("You have already asked this city!")
elif self.__was_city_guessed(city_name):
raise GuessCityGameException("This city has already guessed!")
elif not self.__is_city_exists(city_name):
raise GuessCityGameException("This city was not exists!")
def move(self):
random_letter = random.choice(list(self.__allowed_cities.keys()))
city_names = [word for word in self.__allowed_cities[random_letter] if word not in self.__guessed_cities]
self.__city_name = self.get_city_name(random.choice(city_names))
print(f"My guessed city is {self.__city_name[0]}...")
def generate_fail_answer(self, city=None, catched_ex=None):
if self.__attempts == 2:
self.__get_hint()
elif catched_ex:
self.__attempts += 1
print(e)
print("Try to guess my city again!")
else:
self.__make_city_asked(city)
self.__attempts += 1
print(f"No... It isn't {self.get_city_name(city)} :( Try to guess my city again!")
if __name__ == "__main__":
gc = GuessCity()
print("By welcome! Let's guess cities!")
s = gc.choose_city()
while True:
if s == "the end":
print("Bye-bye! I hope to see you soon :)")
break
try:
gc.check_city(s)
if gc.get_city_name(s) == gc.get_guessed_city():
print(f"Yes! The guessed city was {gc.get_guessed_city()}!")
gc.print_final_text()
gc.reset_current_params()
s = gc.choose_city()
else:
gc.generate_fail_answer(s)
s = input("And your answer is: ").lower()
except Exception as e:
gc.generate_fail_answer(catched_ex=e)
s = input("And your answer is: ").lower()
|
from typing import List, Tuple
class SpellingHammingDictionary:
def __init__(self):
"""
Initialize your data structure here.
"""
self.root = {}
def add(self, word: str) -> None:
node = self.root
for l in word:
if l not in node:
node[l] = {}
node = node[l]
node['is_leaf'] = True
def build_dict(self, words: List[str]) -> None:
"""
Build a dictionary through a list of words
"""
for word in words:
self.add(word)
def __search_dfs(self, node, word, dist, candidates, prefix, cost, start):
if start == len(word) and 'is_leaf' in node and cost <= dist:
candidates.append((''.join(prefix), cost))
return
if start >= len(word):
return
letter = word[start]
for ll, children in node.items():
if ll != 'is_leaf':
self.__search_dfs(children, word, dist, candidates,
prefix + [ll], cost + int(letter != ll), start + 1)
def find_longest_prefix(self, word):
i, node, word_len = 0, self.root, len(word)
while i < word_len and word[i] in node:
node = node[word[i]]
i += 1
return word[:i]
def search(self, word: str, distance=0) -> List[Tuple[str, int]]:
"""
Returns candidates list with words that equal to the given word after modifying exactly distance characters
"""
candidates = []
self.__search_dfs(self.root, word, distance, candidates, [], 0, 0)
return candidates
if __name__ == '__main__':
dictionary = SpellingHammingDictionary()
dictionary.build_dict(['hello', 'hallo', 'leetcode', 'hell'])
assert dictionary.search('hello') == [('hello', 0)]
assert dictionary.search('hhllo', 1) == [('hello', 1), ('hallo', 1)]
assert dictionary.search('hhllo', 2) == [('hello', 1), ('hallo', 1)]
assert dictionary.search('hkelo', 2) == [('hello', 2), ('hallo', 2)]
assert not dictionary.search('hklo')
assert dictionary.search('hklo', 2) == [('hell', 2)]
assert dictionary.search('lettcode', 2) == [('leetcode', 1)]
assert dictionary.search('hkloo', 2) == [('hello', 2), ('hallo', 2)]
assert not dictionary.search('elloo', 2)
assert dictionary.search('elloo', 3) == [('hello', 3), ('hallo', 3)]
assert dictionary.find_longest_prefix('elloo') == ''
assert dictionary.find_longest_prefix('hkloo') == 'h'
assert dictionary.find_longest_prefix('lettcode') == 'le'
assert dictionary.find_longest_prefix('hello') == 'hello'
|
# -*- coding: utf-8 -*-
class SwedenNounLemmatizer:
ARTICLE = {
'n': 'en', 't': 'ett'
}
def __init__(self):
self.irregular_nouns = {}
with open("resources/irregular_nouns.txt", "r") as f:
for line in f:
norm, plural = line.strip().split()
self.irregular_nouns[plural] = norm
def get_lemma(self, word, is_plural=False):
word = word.lower()
if not is_plural:
last = word[-1]
before = word[-2]
if before == 'e':
if (word[:-2].endswith('nn') or word[:-2].endswith('mm')) and word not in ('kranen', 'sonen'):
return f'{self.ARTICLE[last]} {word[:-3]}'
elif word[-3] in 'fk' or word[-4:-2] == 'pl':
return f'{self.ARTICLE[last]} {word[:-1]}'
else:
return f'{self.ARTICLE[last]} {word[:-2]}'
lemma = word[:-2] if before == 'e' and last == 'n' else word[:-1]
return f'{self.ARTICLE[last]} {lemma}'
else:
if word in self.irregular_nouns:
return self.irregular_nouns[word]
elif word.endswith('ena') or word.endswith('en'):
return f'ett {word[:-2]}'
elif word.endswith('erna'):
return word[:-4]
elif word.endswith('larna'):
return word[:-5] + 'el'
return word[:-2] + 'a' if word.endswith('or') else word[:-4]
if __name__ == "__main__":
q = SwedenNounLemmatizer()
assert q.get_lemma("mödrar", is_plural=True) == "mor"
assert q.get_lemma("skolan") == "en skola"
assert q.get_lemma("katterna", is_plural=True) == "katt"
assert q.get_lemma("katten") == "en katt"
assert q.get_lemma("kaffet") == "ett kaffe"
assert q.get_lemma("systern") == "en syster"
assert q.get_lemma("pojken") == "en pojke"
assert q.get_lemma("sängen") == "en säng"
assert q.get_lemma("sockeret") == "ett socker"
assert q.get_lemma("tomaten") == "en tomat"
assert q.get_lemma("gaffeln") == "en gaffel"
assert q.get_lemma("faglarna", is_plural=True) == "fagel"
assert q.get_lemma("barnen", is_plural=True) == "ett barn"
assert q.get_lemma("äpplet") == "ett äpple"
assert q.get_lemma("äpplena", is_plural=True) == "ett äpple"
assert q.get_lemma("barnet") == "ett barn"
assert q.get_lemma("älgen") == "en älg"
assert q.get_lemma("rummet") == "ett rum"
|
from typing import List
class WordFilterTrie:
def __init__(self, words: List[str]):
self.suff = '#'
self.word = '~'
self.root = {}
for word in words:
self.insert(word)
def insert(self, word: str) -> None:
for i in range(len(word), -1, -1):
self.__insert_partition_word(word[i:] + self.suff + word)
def __insert_partition_word(self, word) -> None:
node = self.root
for letter in word:
if letter not in node:
node[letter] = {}
node = node[letter]
node[self.word] = word
def f(self, prefix: str, suffix: str) -> List[str]:
word = suffix + self.suff + prefix
return self.find(word)
def find(self, word: str):
answer = []
prefix = ''
node = self.root
for letter in word:
if letter not in node:
return []
node = node[letter]
prefix += letter
stack = [node]
while stack:
curr = stack.pop()
if self.word in curr:
answer.append(self.word)
for letter in curr:
if letter != self.word:
stack.append(curr[letter])
return answer
|
import operator
import re
import collections
charfrequency = {}
charfrequencysorted = {}
alphabet = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']
def decrypt(shift, path):
finput = open (path, "r")
inputstr = finput.read()
outputstr = ''
for i in range(len(inputstr)):
char = inputstr[i]
if (char.isupper()):
outputstr += chr((ord(char) + shift-65) % 26 +65)
elif (char.isspace()):
outputstr += " "
elif (char.islower()):
outputstr += chr((ord(char) + shift -97) % 26 +97)
foutput = open("output.txt","a")
foutput.write("%s %s" % ("Shift :",shift))
foutput.write('\n')
foutput.write(outputstr)
foutput.write('\n')
print("\nFor Shift : ",shift)
print(outputstr)
return
def freqDictionary(charfrequency):
total=0
for i in charfrequency:
total += charfrequency[i]
for j in charfrequency:
charfrequency[j] = (float)((charfrequency[j]/total)*100)
charfrequencysorted = dict(sorted(charfrequency.items(), key=operator.itemgetter(1), reverse=True))
return charfrequencysorted
def readfile(path):
fileObj = open(path, "r")
charStream = fileObj.read()
charStream = charStream.lower()
charStream = re.sub("[^a-z]","",charStream,0, re.MULTILINE )
for char in charStream:
if char in charfrequency:
charfrequency[char] += 1
else:
charfrequency[char] = 1
charfrequencysorted = freqDictionary(charfrequency)
foutput = open("output.txt", "r+")
foutput.truncate(0)
foutput.close()
for i in range(0, 5):
testchar = list(charfrequencysorted.keys())[i]
shift = alphabet.index('e') - alphabet.index(str(testchar))
decrypt(shift, path)
|
#Знайти всі чотирьохзначні числа, сума цифер яких дорівнює заданому числу
#Задане число. перевірити чи дане число є простим
number = int(input("Input number" + "\n"))
if number <=0:
print ("Incorrect number")
elif number ==1:
print ("1 is prime")
else:
for i in range(2,number):
if number%i == 0:
print(number, "is not prime, divided by", i)
break
else:
print(number, "is prime")
|
#contol led with button press and count how many time button is pressed
#importing gpio library
import RPi.GPIO as gpio
gpio.setmode(gpio.BOARD) #to use physical pin numbers on board
gpio.setup(11, gpio.OUT) #set pin 11 as output
gpio.setup(12, gpio.IN, pull_up_down = gpio.PUD_DOWN) #set pin 12 as input with pull down resistor enabled
counter = 0 #variable to keep track of button pressed
#call back function when button is pressed
def incrementcounter(channel):
"keep track of how many time button is pressed"
global counter
counter += 1
print (counter)
return
#event handler setup to count number of button pressed
gpio.add_event_detect(12, gpio.RISING, callback = incrementcounter)
while 1:
input = gpio.input(12)
if input == 1 :
gpio.output(11, 1) #led will glow until the button is pressed
else :
gpio.output(11, 0) #otherwise it will be off
GPIO.cleanup()
|
import random
def sort_012(input_list):
"""
The idea is to put 0 and 2 in their correct positions, which will make sure
all the 1s are automatically placed in their right positions
"""
# initialize pointers for next positions of 0 and 2
next_pos_0 = 0
next_pos_2 = len(input_list) - 1
front_index = 0
while front_index <= next_pos_2:
if input_list[front_index] == 0:
input_list[front_index] = input_list[next_pos_0]
input_list[next_pos_0] = 0
next_pos_0 += 1
front_index += 1
elif input_list[front_index] == 2:
input_list[front_index] = input_list[next_pos_2]
input_list[next_pos_2] = 2
next_pos_2 -= 1
else:
front_index += 1
return input_list
def test_function(test_case):
sorted_array = sort_012(test_case)
print(sorted_array)
if sorted_array == sorted(test_case):
print("Pass")
else:
print("Fail")
# Test case 1 - unsorted array
test_function([0, 0, 2, 2, 2, 1, 1, 1, 2, 0, 2])
test_function([2, 1, 2, 0, 0, 2, 1, 0, 1, 0, 0, 2, 2,
2, 1, 2, 0, 0, 0, 2, 1, 0, 2, 0, 0, 1])
# Test case 2 - sorted array
test_function([0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2])
# Test case 3 - array with only a single element
test_function([0])
# Test case 4 - array with empty array
test_function([])
for _ in range(30):
input_list = [random.randint(0,2) for _ in range(random.randint(1,100))]
test_function(input_list) |
from priority_queue import PriorityQueue
import sys
class Node:
def __init__(self, frequency=None, character=None):
self.frequency = frequency
self.character = character
self.left_child: Node = None
self.right_child: Node = None
@property
def has_left_child(self):
return self.left_child != None
@property
def has_right_child(self):
return self.right_child != None
@property
def is_leaf(self):
has_child = self.has_left_child or self.has_right_child
return not has_child
def __lt__(self, other):
if (self.frequency == other.frequency):
return self.character and other.character and self.character < other.character
return self.frequency < other.frequency
def __eq__(self, other):
return isinstance(other, self.__class__) and self.frequency == other.frequency and self.character == other.character
def __gt__(self, other):
return other.frequency < self.frequency
def __repr__(self):
return f"Node(freq={self.frequency}, char={self.character})"
def frequency_of_each_character(string):
result = {}
for bit in string:
result[bit] = result.get(bit, 0) + 1
return result
def build_a_priority_queue(data: dict) -> PriorityQueue:
priorityQueue = PriorityQueue()
for character, frequency in data.items():
priorityQueue.enqueue(Node(frequency, character))
return priorityQueue
def pop_out_two_nodes(queue: PriorityQueue):
left = queue.dequeue()
right = queue.dequeue()
return left, right
def merge_nodes(left: Node, right: Node):
newNode = Node(left.frequency + right.frequency)
newNode.left_child = left
newNode.right_child = right
return newNode
class HuffmanTree:
def __init__(self, root: Node) -> None:
self.root = root
self.generate_huffman_code()
def generate_huffman_code(self):
if(self.root.is_leaf):
self.encoding = {self.root.character: "0"}
return
self.encoding = {}
def traverse(node, code=""):
if node:
traverse(node.left_child, code + "0")
traverse(node.right_child, code + "1")
char = node.character
if(char != None):
self.encoding[char] = code
traverse(self.root)
def encode(self, data):
return "".join([self.encoding[char] for char in data])
def decode(self, data):
decoded = ""
node = self.root
if(node.is_leaf):
return node.character * len(data)
for bit in data:
if(bit == "0"):
node = node.left_child
else:
node = node.right_child
if(node.is_leaf):
decoded += node.character
node = self.root
return decoded
def huffman_encoding(data):
# O(n)
if(not data):
return None, None
frequency = frequency_of_each_character(data)
#O(n * log(n))
queue = build_a_priority_queue(frequency)
#O(n * log(n))
while queue.size > 1:
#O(2 * log(n))
left, rigth = pop_out_two_nodes(queue)
# O(1)
newNode = merge_nodes(left, rigth)
# O(log(n))
queue.enqueue(newNode)
# O(n)
tree = HuffmanTree(queue.dequeue())
# O(n)
return tree.encode(data), tree
def huffman_decoding(data, tree):
# O(n)
return tree.decode(data)
if __name__ == "__main__":
codes = {}
a_great_sentence = "The bird is the word"
print("The size of the data is: {}\n".format(
sys.getsizeof(a_great_sentence)))
print("The content of the data is: {}\n".format(a_great_sentence))
encoded_data, tree = huffman_encoding(a_great_sentence)
print("The size of the encoded data is: {}\n".format(
sys.getsizeof(int(encoded_data, base=2))))
print("The content of the encoded data is: {}\n".format(encoded_data))
decoded_data = huffman_decoding(encoded_data, tree)
print("The size of the decoded data is: {}\n".format(
sys.getsizeof(decoded_data)))
print("The content of the encoded data is: {}\n".format(decoded_data))
|
from union_and_intersection import intersection, union, LinkedList
def make_linked_list(elements):
linked_list = LinkedList()
for i in elements:
linked_list.append(i)
return linked_list
def helper(element_1, element_2, expected_union, expected_intersection):
linked_list_1 = make_linked_list(element_1)
linked_list_2 = make_linked_list(element_2)
result_union = union(linked_list_1, linked_list_2)
assert len(expected_union) == result_union.size()
for expected in expected_union:
assert str(expected) in str(union(linked_list_1, linked_list_2))
result_intersection = intersection(linked_list_1, linked_list_2)
assert len(expected_intersection) == result_intersection.size()
for expected in expected_intersection:
assert str(expected) in str(intersection(linked_list_1, linked_list_2))
def test_union_and_intersection():
helper([1, 2, 3, 4, 5, 6], [6, 7, 8], [
1, 2, 3, 4, 5, 6, 7, 8, ], [6])
# one list is empty
helper([], [1, 2, 3], [1, 2, 3], [])
# both lists are empty
helper([], [], [], [])
# list equals
helper([1, 2, 3], [1, 2, 3], [1, 2, 3], [1, 2, 3])
# list without equal elements
helper([1, 2, 3], [4, 5, 6], [1, 2, 3, 4, 5, 6], [])
|
import time
import random
import sys
item = []
def roomkey_1():
print_pause("You took the stairs for the sixth room.")
print_pause("After a few moments, you find "
"yourself in the staff survey room.")
print_pause("you reached the sixth room ")
if "key_1" in item:
print_pause("congrats you already have the first key!")
print_pause("best wishes, go for the second key!")
print_pause("you reached the staircases, "
"now time to make a choice!")
room_choose()
else:
print_pause("congrats you found the first key!")
item.append("key_1")
print_pause("now seek for the second key!")
print_pause("be aware! the zombies are very dangerous,"
" one wrong choice! you are dead!")
print_pause("you reached the staircases, "
"now time to make a choice!")
room_choose()
def roomkey_2():
print_pause("You choose the stairs for the fifth room")
print_pause("After a few moments, you find yourself "
"in the peon room.")
print_pause("finally! you reached the peon room")
if "key_2" in item:
print_pause("you have nothing to doo here, "
"you already have the second key!")
print_pause("go ahead for your last choose!")
print_pause("one right choose will save the earth from corona virus!")
print_pause("and one wrong choose will "
"lead to the death of all hopes!")
room_choose()
else:
if "key_1" in item:
print_pause("you can easily see the second key, grab it!")
item.append("key_21")
print_pause("congrats for your second success!")
print_pause("go ahead for your last choose!")
print_pause("one right choose will"
" save the earth from corona virus!")
print_pause("and one wrong choose will "
"lead to the death of all hopes!")
room_choose()
else:
print_pause("nice luck!")
print_pause("you are not killed, it means,"
"you dont't have the first key")
print_pause("go and search for the first key")
print_pause("you reached the stairs, now make your choice,"
"that leads you to the first key")
room_choose()
def room_boss():
print_pause("You push the button for the third room.")
print_pause("After a few moments, you find yourself "
"in the engineering department.")
print_pause(" you reached the third room")
if "key_1" in item:
print_pause("you can enter the office with the help of key_1")
print_pause("the manager greets you and asks your key_2")
if "key_2" in item:
print_pause("you can have your meeting with your boss")
print_pause("congrats you compleated the game")
else:
print_pause("go and collect your key_2")
room_choose()
else:
print_pause("go and collect your key_1")
print_pause("you reached the lift, which room you want to go?")
room_choose()
def info():
print_pause("This is the life saving mission!")
print_pause("if you succeed in this mission, "
"you can irradicate corona virus from this world")
print_pause("rules for the game:")
print_pause("1. There are total 6 rooms in this business building")
print_pause("2. Only 2 of which contains the key for the 3rd room"
" containing vaccine")
print_pause("3. If you catch a wrong staircase, it will"
" lead to your death,as zombies are waiting for you inside")
print_pause("4. The numbers on the staircases are jumbled,so be careful")
print_pause("and if you managed to get to the vaccine chamber,"
" you will eventually win")
print_pause("5. The vaccine is mounted on a movable robot"
"which is on move, in every new game its position changes!")
print_pause("6. You can only see the second key"
" if you have the first one with you!\n")
print_pause('''1. Stairs to Lobby
2. Stairs to Human resources
3. Stairs to Engineering department
4. Stairs to mechanical department
5. Stairs to peon room
6. Staff survey room
7. Exit Game\n''')
print_pause("now make a choice! and save the world")
room_choose()
def print_pause(data):
print(data)
time.sleep(2)
def input_check(prompt, option1, option2, option3, option4, option5, option6, option7="exit"):
while True:
res = input(prompt)
if res == option7:
exit_game()
elif res == option1:
break
elif res == option2:
break
elif res == option3:
break
elif res == option4:
break
elif res == option5:
break
elif res == option6:
break
else:
print_pause("sorry,i didn't understand,"
"please give a proper room number")
return res
def input_check1(prompt):
while True:
response = input(prompt)
if response == "exit":
exit_game()
elif response == "yes":
break
elif response == "no":
break
else:
print_pause("sorry, i didn't understand")
return response
def room_choose():
room = input_check("which room you want to go? ",
"1", "2", "3", "4", "5", "6", "exit")
if room == "exit":
exit_game()
elif room == "6":
roomkey_1()
elif room == "5":
roomkey_2()
elif room == random.randint(1, 5):
room_boss()
else:
print_pause("you were killed! The " + choose() + " zombie killed you!")
print_pause("better luck next time!")
reply = input_check1("do you want to try again,reply in yes or no\n")
if reply == "yes":
print_pause("so here we are:")
global item # emptying the list for the new game
item.clear()
print_pause("now make your choice for the stairs again!")
room_choose()
elif reply == "no":
print_pause("Thank you for playing the game with us")
print_pause("we welcome you anytime you want to play!")
def choose():
z_list = ["zombo", "curley", "frgo", "drako"]
return random.choice(z_list)
def start_game():
info()
def exit_game():
sys.exit()
start_game()
|
#boj4233 가짜소수
def PrimeChk(num):
for i in range(2,num+1):
if i*i>num:break
if num%i==0:return False
return num!=1
def Fermat(num,Prime,mod):
x=num;p=Prime
result=1
while p:
if p%2==1:
result=result*x%mod
x=x*x%mod
p>>=1
return result
while 1:
p,a=map(int,input().split())
if p==0 and a==0:break
if PrimeChk(p):print('no')
else:
if Fermat(a,p,p)==a:
print('yes')
else:
print('no')
|
#boj11729 하노이 탑 이동 순서
def hanoi(n,beg,aux,end,l):
if n==1:
l.append([beg,end])
else:
hanoi(n-1,beg,end,aux,l)
hanoi(1,beg,aux,end,l)
hanoi(n-1,aux,beg,end,l)
n=int(input());l=[]
hanoi(n,1,2,3,l)
print(len(l))
for _ in l:
print(*_)
|
#boj16649 Building a Stair
def stair(cube):
cnt=cube
row=(cube+1)//2
print(row+1)
pic='.'*(row+1)+'\n'
for i in range(row):
for j in range(row):
if j==0 or i==row-1:
pic+='o';cnt-=1
elif cube%2==0 and i==row-2 and j==1:
pic+='o';cnt-=1;
else:
pic+='.'
pic+='.\n'
print(pic.strip())
#print(cnt)
n=int(input())
if n==2:print(-1)
else:stair(n)
|
from GraphAPI import Graph
from networkx.algorithms.shortest_paths import *
import networkx as nx
import time
'''Bellman_Ford solution of shortest path'''
class Bellman_Ford(object):
def __init__(self, graph):
#initialized graph input
self.graph = graph
def solver(self, source):
dist = {}#create distance list
path = {}#create path tree
for node in self.graph.bag:
#set all the distance to source to be infinity
#for each u in set V do: d(u) <- infinity
dist[node] = float("inf")
#set all the nodes' parent to be None
path[node] = None
#set diatance to the source to 0
#d(s)<-0
dist[source] = 0
#iterating |V| -1 times to relax
#for k = 1 to n-1 do
for i in range(1, len(self.graph.bag)):
#for each v in set V do
#for each edge (u,v) in set ln(v) do
for u, v, weight in self.graph.edges:
if dist[v] > dist[u] + weight:
#d(v) = min{d(v), d(u)+l(u,v)}
dist[v] = dist[u] + weight
path[v] = u
#detecting negative cycle
#for each v in set V do
#for each edge (u,v) in set ln(v) do
for u, v, weight in self.graph.edges:
#if (d(v) > d(u) + l(u,v))
if dist[v] > dist[u] + weight:
#if the edge is still failed to be relaxed, there is a negative cycle
#Output ``Negative Cycle''
print "Graph has negative cycle"
return None, None
return dist, path
'''testing
if __name__ == "__main__":
graph = Graph()
graph.addNode(1)
graph.addNode(2)
graph.addNode(3)
graph.addWeightedEdge(1, 2, 5)
graph.addWeightedEdge(2, 3, -10)
graph.addWeightedEdge(1, 3, 2)
solution = Bellman_Ford(graph)
dist, path =solution.solver(1)
print dist
print path
'''
|
from collections import defaultdict
def max_equal_sum(E):
D=defaultdict(int) # Map from abs difference to largest sum
D[0]=0 # Start with a sum and difference of 0
print(D)
for a in E: # Iterate over each element in the array
D2=D.copy() # Can keep current sum and diff if element is skipped
for d,s in D.items(): # d is difference, s is sum
s2 = s+a # s2 is new sum
for d2 in [d-a,d+a]: # d2 is new difference
D2[abs(d2)] = max(D2[abs(d2)],s2) # Update with largest sum
D=D2
print(D)
return D[0]/2 # Answer is half the sum of A+B for a difference of 0
l = [int(x) for x in input().split()]
print(max_equal_sum(l))
|
s = set(['aa','bb','cc'])
l = ['bb','dd','aa','ee']
for name in l
if name in set:
s.remove(name)
else:
s.add(name)
print s
|
def towers(n,frompeg,topeg,auxpeg):
#if only 1 disk, make the move and return
if n==1:
print "\nMove disk 1 from peg %c to peg %c"%(frompeg,topeg)
return
# Move top n-1 disks from A to B, using C as auxiliary
towers(n-1,frompeg,auxpeg,topeg)
#Move remaining disks from A to C
print "\nMove disk %d from peg %c to peg %c"%(n,frompeg,topeg)
#Move n-1 disks from B to C using A as auxiliary
towers(n-1,auxpeg,topeg,frompeg)
n = input("Enter No. of disks:")
print "The Tower of Hanoi involves the moves :\n"
towers(n,'A','C','B')
|
from sys import argv #import of system statement
script, input_file = argv # unpacking
def print_all(f): #definition
print f.read() # read the content of the file and print d same
def rewind(f): # redefining seek function
f.seek(0) # set the cursor position to the starting of the file
def print_a_line(line_count, f):
print line_count, f.readline()# prints the line number and the line
current_file = open(input_file) #opening a file to read the contents
print "First let's print the whole file:\n"
print_all(current_file) # f=current_file , print_All(f) prints the content of the file
print "Now let's rewind, kind of like a tape."
rewind(current_file) # move to the starting of the file
print "Let's print three lines:"
current_line = 1
print_a_line(current_line, current_file) # prints the current line number and the contents of the line
current_line += 1
print_a_line(current_line, current_file)
current_line += 1
print_a_line(current_line, current_file) |
import datetime
sundays=0
for year in range(1901,2001,1):
for month in range(1,13,1):
if datetime.date(year,month,1).weekday()==0: sundays+=1
print "number of sundays on which 1st of a month falls are",sundays |
the_count = [1,2,3,4,5]
fruits = ['apples', 'oranges','pears', 'apricots']
change = [1, 'pennies', 2, 'dimes', 3, 'quarters']
#the first kind of for loop goes through a list
for number in the_count:
print "This is count %d" %number
#same as above
for fruit in fruits:
print "A fruit of type %s" %fruit
#also we can go through mixed lists too
#notice we have to use %r since we don't know what's in it
for i in change:
print "I got %r" %i
#we can also build lists, first start with an empty one
elements= []
# then use range function to do 0 to 5 counts
for i in range(0,6):
print "Adding %d to the list." %i
#append is a function that lists understand
elements.append(i)
#now we can print them too
for i in elements:
print "The elements was %d" %i
#extra credit
for i in range(1,3):
print "The elements are: %d" %i
for i in range(2,4):
print "The element: %d" %i
a = ['kiran', 'sri', 'friends']
for j in a:
print "The names are %s " %j
print "Lengths are %d " %(len(j))
print "Names and its length: %s %d " %(j, len(j))
for j in range(len(a)):
print j,a[j] |
#!/usr/bin/env python
#-----------------------------------------------------------------------------
#joins IP Ranges to Locations and converts IP from an Int to Octets.
import json
import csv
# converts Integer to binary (http://stackoverflow.com/questions/699866/python-int-to-binary)
# ex: toBinary(3640355304) = '11011000111110110110100111101000'
def IntToBinary(n):
return ''.join(str(1 & int(n) >> i) for i in range(32)[::-1])
# converts binary to integer
# binary is a 32 character string such as '11011000111110110110100111101000'
# each 8 bytes represents each octet in the IP address
# '11011000111110110110100111101000' becomes ['01001010', '01111101', '00101011', '01100011']
# then convert each string to an integer int(n,2)
def BinaryToIP(b):
return '.'.join(map(lambda i: str(int(b[i*8:(i*8)+8],2)), range(4)))
def IntToIP(int):
return IntToBinary(BinaryToIP(int))
locationsFile = open('../IPGeolocation/GeoLiteCity-Location.csv','r')
# read past copywrite
locationsFile.readline()
locationsReader = csv.DictReader(locationsFile)
locations={}
for location in locationsReader:
if location['city'] == 'Seattle':
locations[location['locId']] = location
blocksFile = open('../IPGeolocation/GeoLiteCity-Blocks.csv','r')
# read past copywrite
blocksFile.readline()
blocksReader = csv.DictReader(blocksFile)
blocks=[]
for block in blocksReader:
if block['locId'] in locations.keys():
newBlock=block
newBlock['startIp']=BinaryToIP(IntToBinary(block['startIpNum']))
newBlock['endIp']=BinaryToIP(IntToBinary(block['endIpNum']))
newBlock['location']=locations[block['locId']]
blocks.append(block)
outputFile = open('seattleCIDRBlocksAndLocations.json','w')
outputFile.write(json.dumps(blocks))
outputFile.close()
|
from functools import *;
def Acceptdata():
size=int(input("enter the no of elements"));
arr=list();
print("enter the element in list");
for i in range(0,size,1):
print("enter element ",i+1);
a=int(input())
arr.append(a)
return arr;
def Evenno(no1):
return (no1%2==0);
def Square(no1):
return no1*no1;
def Add(no1,no2):
return no1+no2;
def main():
iret=Acceptdata();
print("the Accepted data is");
print(iret);
Filterdata=list(filter(Evenno,iret))
print("the filterd data is ");
print(Filterdata);
Mapdata=list(map(Square,Filterdata))
print("the map data is");
print(Mapdata);
result = reduce(Add,Mapdata);
print("the final result is");
print(result);
if __name__ == "__main__":
main()
|
def Countdigit(ino):
icnt=0
while (ino>0):
ino = ino // 10
icnt=icnt+1
return icnt
print("enter the no")
a=int(input())
iret=Countdigit(a)
print("the no of digit is",iret)
|
class Circle:
PI=3.14;
def __init__(self):
self.Radius=0.0;
self.Area=0.0;
self.Circumference=0.0;
def Accept(self):
self.Radius=int(input("enter the radius"));
def CalculateArea(self):
self.Area = Circle.PI*self.Radius*self.Radius;
def CalculateCircumference(self):
self.Circumference = 2*Circle.PI*self.Radius;
def Display(self):
print("Radius of cirlce is",self.Radius);
print("Area of cirlce is",self.Area);
print("Circumference of circle is",self.Circumference);
def main():
obj1 = Circle()
obj2 = Circle()
obj3 = Circle()
obj1.Accept()
obj1.CalculateArea()
obj1.CalculateCircumference()
obj1.Display()
obj2.Accept()
obj2.CalculateArea()
obj2.CalculateCircumference()
obj2.Display()
obj3.Accept()
obj3.CalculateArea()
obj3.CalculateCircumference()
obj3.Display()
if __name__=="__main__":
main() |
def Prime(ino):
isum=0;
if ino<0:
ino=-ino;
for i in range(1,ino):
if ino%i==0:
isum=isum+i;
if isum==1:
return True
else:
return False
print("enter the number")
a=int(input())
bret=Prime(a)
if bret==1:
print("it is prime number")
else:
print("it is not prime number") |
def Pattern1(ino):
for i in range(0,ino):
print("\n");
for j in range(0,ino):
print("*",end =' ');
#print("\n");
print("enter the number")
n=int(input())
Pattern1(n) |
from functools import *;
def Acceptlist():
size=int(input("enter the no of element"))
ab=list();
print("enter the number in list ");
for i in range(0,size,1):
print("enter number", i+1);
n=int(input())
ab.append(n)
return ab;
def grtles(no):
if ((no>=70)&(no<=90)):
return no;
def modify(no):
return no+10;
def product(no1,no2):
return no1*no2;
def main():
iret=Acceptlist();
print("accepted list is");
print(iret);
FilterList= list(filter(grtles,iret));
print("filter list is");
print(FilterList);
ModifiedList = list(map(modify,FilterList));
print("modified list is");
print(ModifiedList);
result = reduce(product,ModifiedList);
print("final result is",result);
if __name__ == "__main__":
main()
|
def Minno(ele):
min=ele[0];
for i in ele:
if i<min:
min=i
return min;
def main():
size=int(input("enter the no of elements "))
a= list();
print("Insert the Element in list");
for i in range(0,size,1):
print("Enter element ",i+1)
no=int(input());
a.append(no)
print("the list is",a);
iret=Minno(a);
print(" the minimum element in list is",iret);
if __name__== "__main__":
main()
|
"""
This function, combinations(iterable, r), takes an iterable and an integer
and returns subsequences of elements with a length of r.
These subsequences of elements are in the form of tuples.
One thing to note that the order of the elements
in these tuples will reflect their original order in the initial iterable.
Suppose that we have some coins of different denominations, and we want to find out all possible combinations
using a certain number of coins. Look familiar?
You’re right — I got the idea from my 8-year-old daughter’s math homework.
Feel free to use the code for your in-house tutoring work.
"""
from itertools import combinations
def combine_coins(coins, number):
possible_sums = set()
for selected_coins in combinations(coins, number):
print(selected_coins)
possible_sums.add(sum(selected_coins))
return sorted(possible_sums)
print(combine_coins([5, 5, 1, 1, 25, 10, 25], 3))
print(combine_coins([1, 1, 10, 5, 25, 25], 2))
|
#this program will inform users if they can or cannot enter the casino
#ask user for their age
age = int(input("How old are you? "))
#tell user if they are allowed in the casino or not
if age >= 21:
print("Welcome to Cassie's Casino")
else:
print("Sorry you cannot enter")
#quit program
input("press any key to quit")
|
#the purpose of this program is to convert a dogs age to human years
#if the user enters a non-numeric value, the error will be handled with a Try Except
#ask user to enter dogs age and convert age to an integer
try:
dog_age = int(input("Enter your dogs age: "))
human_age = dog_age * 7
print(f"Your dog is {human_age} years old")
#if the conversion to float fails, print out error message
except:
print("Sorry age must be a number.")
#the finally clause is optional. This will run regardless of whether an error occured or not
finally:
input("press any key to exit")
#try typing a string "five" or "no" instead of a number to ensure the error is handled
#additional Resources
#https://www.programiz.com/python-programming/exception-handling
#https://www.youtube.com/watch?v=nlCKrKGHSSk
|
#challenge 1
#create a loop that prints the numbers 1 through 100
i = 0
while i < 101:
print(i)
i = i+1
|
#creating a dictionary to store information about our yoga classes
yoga = {'Instructor' : 'Jane',
'Location': 'Plum Center',
'Price': 199,
'Students' : ['Alex', 'Carl', 'Connie']
}
#print dictionary
print(yoga)
#Iterating over dictionaries like iterating over lists will output only key
for key in yoga:
print(key)
#iterating over dictionary using for loop
for key, value in yoga.items():
print(key,value)
#using in and not in to know if a key is defined
if 'Location' in yoga:
print('Location Known')
else:
print('Location Unknown')
#You can access values in dictionary in two ways
print(yoga['Price']) #will return key error if key does not exist
print(yoga.get('Price')) #will return none if key does not exist
#Nesting dictionaries (dictionaries inside of dictionaries)
my_family = {
"child1" : {
"name" : "Emily",
"year" : 2004
},
"child2" : {
"name" : "Sam",
"year" : 2007
},
"child3" : {
"name" : "Pat",
"year" : 2011
}
}
#accessing values in nested dictionaries
print(my_family["child1"]['name'])
#additional resources
#https://www.tutorialspoint.com/python/python_dictionary.htm
#https://www.programiz.com/python-programming/dictionary
|
#asks user to enter a number and print if the number is odd or even
x = int(input("Enter a number: "))
if x<0:
print("That is negative number")
elif x ==0:
print("This number is neither postive or negative")
else:
print("That is a positive number")
input('Press any key to quit')
|
#comparison operators check
age = 18
#each of these operators return a True or False value
#True or False are known as Boolean values
#Is age greater than 30?
age > 30
#Is age less than 30?
age < 30
#Is greater than or equal 30?
age >=30
#Is age less than or equal 30
age <=30
#Is age exactly 30
age == 30
#Is age not equal 30
age !=30
#additional resources https://www.tutorialspoint.com/python/python_basic_operators.htm
|
class Room:
def __init__(self, room_id):
self.room_id = room_id
self.title = None
self.description = None
self.elevation = None
self.terrain = None
self.available_directions = []
self.traveled_directions = []
self.n_to = None
self.s_to = None
self.e_to = None
self.w_to = None
self.x = None
self.y = None
def __str__(self):
return f"\n-----------------\n\n{self.title}, id num: {self.room_id}" \
f"\n\n {self.description}\n\n {self.get_exits_str}"
def get_exits(self):
exits = []
if self.n_to is not None:
exits.append('n')
if self.s_to is not None:
exits.append('s')
if self.e_to is not None:
exits.append('e')
if self.w_to is not None:
exits.append('w')
return exits
def get_exits_str(self):
return f"Exits in directions: [{' ,'.join(self.get_exits())}]"
def connect_rooms(self, direction, room):
if direction == 'n':
self.n_to = room
room.s_to = self
elif direction == 's':
self.s_to = room
room.n_to = self
elif direction == 'e':
self.e_to = room
room.w_to = self
elif direction == 'w':
self.w_to = room
room.e_to = self
else:
print("Invalid Connection")
return None
def getRoomInDirection(self, direction):
ddict = {'n': 'n_to', 's': 's_to', 'e': 'e_to', 'w': 'w_to'}
if getattr(self, ddict[direction]) is not None:
return getattr(self, ddict[direction])
else:
if direction in self.available_directions:
#traverse
print('add functionality')
return 'add functionality'
else:
return None
def get_xy(self):
return [self.x, self.y]
class World:
def __init__(self, start_room):
self.start_room = start_room
self.rooms = {}
self.room_grid = []
self.grid_size = 0
def add_room(self, room_id, title, description, elevation, terrain, available_directions, x, y):
room = Room(room_id=room_id)
room.title = title
room.description = description
room.elevation = elevation
room.terrain = terrain
room.available_directions = available_directions
room.x = x
room.y = y
def generate_grid(self):
return 'add functionality' |
#More prints with escape characters to practice
print "Let's practice everything."
print 'You\'d need to know \'bout escapes with \\ that do \n newlines and \t tabs.'
#Printing string : A poem to print later. Just a variable holding set of lines
poem="""
\tThe lovely world
with logic so firmly planted
cannot discern \n the needs of love
nor comprehend passion from intuition
and requires an explanation
\n\t\t where there is none.
"""
#print poem
print "---------------------"
print poem
print "---------------------"
#Printing integer : Do some math, assign to a variable and print
five = 10 - 2 + 3 - 6
print "This should be five: %s" % five
#Writing a funcition to return multiple values
def secret_formula(started):
jelly_beans = started * 500
jars = jelly_beans / 1000
crates = jars / 100
return jelly_beans, jars, crates
#Call the function and collect multiple values
start_point = 10000
beans, jars, crates = secret_formula(start_point)
print "With a starting point of: %d" % start_point
print "We'd have %d beans, %d jars, and %d crates." % (beans, jars, crates)
#Print floating point values
start_point = start_point / 10
#call the same function
print "We can also do that this way:"
print "We'd have %d beans , %d jars, and %d crates." % secret_formula(start_point)
|
from sys import argv
#Take input file
script, input_file = argv
#function to print input file contents
def print_all(f):
print f.read()
#function to rewind the file
def rewind(f):
f.seek(0)
#function to print a line
def print_a_line(line_count, f):
print line_count, f.readline()
#Open the input file
current_file = open(input_file)
#Print file contents first
print "First let's print the whole file:\n"
print_all(current_file)
#Rewind to beginning of the file
print "Now let's rewind, kind of like a tape."
rewind(current_file)
#Print line by line. Firs three lines
print "Let's print three lines:"
current_line = 1
print_a_line(current_line, current_file)
current_line = current_line + 1
print_a_line(current_line, current_file)
current_line = current_line + 1
print_a_line(current_line, current_file)
|
str1 = input("Enter the first string: ")
str2 = input("Enter the second string: ")
len1 = len(str1)
len2 = len(str2)
count = 0
max_count = 0
i = i1 = i2 = 0
subseq = []
while i < len1:
i1 = i
i2 = 0
while i1 < len1 and i2 < len2:
if str1[i1] == str2[i2]:
count += 1
i1 += 1
i2 += 1
if count > max_count:
max_count = count
t = 0
while t < max_count:
if t >= len(subseq):
subseq.insert(t, str2[i2 - max_count + t])
elif t < len(subseq):
subseq[t] = str2[i2 - max_count + t]
t += 1
else:
count = 0
i1 = i
i2 += 1
i += 1
print("The longest common subsequence of the two given strings is: ", end = '')
print(*subseq, sep = '')
|
import functools
class Employee:
def __init__(self,id,name,des,sal):
self.id=id
self.name=name
self.des=des
self.sal=sal
def printemp(self):
print("name=",self.name)
print("designation=",self.des)
print("sal",self.sal)
def __str__(self):
#return self.name+self.id+self.sal+self.des
return self.name+self.sal
f=open("edetails","r")
lst=[]
for lines in f:
data=lines.rstrip("\n").split(",")
id=data[0]
name=data[1]
des=data[2]
sal=data[3]
obj=Employee(id,name,des,sal)
#obj.printemp()
lst.append(obj)
#for emp in lst:
#print(emp)
#print(emp.name.upper())
s2= list(map(lambda emp: emp.name.upper(),lst))
print(s2)
# if(int(emp.sal)>25000):
# print(emp)
#ss= filter(lambda emp: (int(emp.sal)>20000), lst)
#print(ss)
mm = list(filter(lambda empp: int(empp.sal) > 20000, lst))
#print(mm)
for lss in mm:
print(lss)
sss= list(map(lambda d: int(d.sal)+5000,lst))
print(sss)
highestsal=functools.reduce(lambda sal1,sal2:sal1 if sal1>sal2 else sal2,list(map(lambda empp:empp.sal,lst)))
print(highestsal)
maxsalem=list(filter(lambda em:em.sal==highestsal,lst))
for emm in maxsalem:
print(emm)
|
num1=int(input("enter num"))
num2=int(input("enter num"))
if(num1>num2):
print("num1 max")
elif(num1<num2):
print("num2 max")
else:
print("equal")
|
list=[10,11,12,13,14,15,2,3,4]
list.sort()
print(list)
low=0
upp=len(list)-1
ele=int(input("enter ele"))
flag=0
while(low<=upp):
mid=(low+upp)//2
if(ele>list[mid]):
low=mid+1
elif(ele<list[mid]):
upp=mid-1
elif(ele==list[mid]):
flag=1
break
if(flag>0):
print("ele found")
else:
print("not found")
|
num1=int(input("enter num"))
num2=int(input("enter num2"))
num3=int(input("enter num3"))
if((num1>=num2)&(num1>=num3)):
t=num1
if((num2>=num3)):
tt=num2
ttt=num3
print(ttt,tt,t)
else:
f=num3
ff=num2
print(ff,f,t)
elif((num2>=num1)&(num2>=num3)):
s=num2
if(num1>=num3):
ss=num1
sss=num3
print(sss,ss,s)
else:
k=num3
kk=num1
print(kk,k,s)
elif((num3>=num1)&(num3>=num2)):
j=num3
if(num1>=num2):
jj=num1
jjj=num2
print(jjj,jj,j)
else:
ll=num2
l=num1
print(l,ll,j)
#else:
# print("equal no")
|
n = int(input("Enter the number: "))
a=0
b=1
print(a, b,end=' ')
for i in range(2,n):
c=a+b
print(c,end=' ')
a=b
b=c
|
class Employee:
def __init__(self, id, name, desig, salary):
self.id = id
self.name = name
self.designation = desig
self.salary = salary
def printValues(self):
print(self.id)
print(self.name)
print(self.designation)
print(self.salary)
def __str__(self):
return self.name
obj1 = Employee(1001,"rahul","tester",10000)
obj2= Employee(1001,"aju","tester",20000)
obj3 = Employee(1001,"manu","tester",30000)
#obj.printValues()
#print(obj.name)
#ls=[]
3ls.append(obj1)
#ls.append(obj2)
#ls.append(obj3)
#for emp in ls:
#if(emp.salary>22000):
# print(emp)
|
lst=[1,2,3,4]
ele=int(input("enter ur ele"))
for i in lst:
for j in lst:
if(i+j==ele):
print(i,j)
else:
pass |
# -*- coding: utf-8 -*-
"""
logger.py
Manages logging.
:copyright: (c) 2016 by Robert Johansson.
:license: BSD, see LICENSE for more details.
This module can be used to do basic logging and be used instead of
print method. Logging can be done to stdout, a file or a custom logger.
Example:
from logger import Error, Note, Print
Note("hello")
Example if you want to mute output:
import logger
logger.logger = logger.NullLogger()
logger.Note("hello")
If you want to log to a file:
import logger
logger.logger = FileLogger('some_file.txt')
logger.Note("hello")
Or using your own custom logger class, which needs to implement methods
called Error, Note and Print:
import logger
logger.logger = MyCustomLogger()
logger.Note("hello")
"""
import sys
import os
def Error(msg):
global logger
logger.Error(msg)
def Note(msg):
global Note
logger.Note(msg)
def Print(msg):
global logger
logger.Print(msg)
class NullLogger:
def Error(self, msg):
pass
def Note(self, msg):
pass
def Print(self, msg):
pass
class BaseLogger:
def _error(self, msg, f):
f.write("Error: " + str(msg) + os.linesep)
def _note(self, msg, f):
f.write("Note: " + str(msg) + os.linesep)
def _print(self, msg, f):
f.write(str(msg) + os.linesep)
def Error(self, msg):
pass
def Note(self, msg):
pass
def Print(self, msg):
pass
class StdoutLogger(BaseLogger):
def Error(self, msg):
self._error(msg, sys.stdout)
def Note(self, msg):
self._note(msg, sys.stdout)
def Print(self, msg):
self._print(msg, sys.stdout)
class FileLogger(BaseLogger):
def __init__(self, path):
self.File = open(path, 'w')
def __del__(self):
self.File.close()
def Error(self, msg):
self._error(msg, self.File)
def Note(self, msg):
self._error(msg, self.File)
def Print(self, msg):
self._print(msg, self.File)
logger = StdoutLogger()
if __name__ == '__main__':
for logger in [ FileLogger('test.log'), NullLogger(), StdoutLogger() ]:
logger.Error('message')
logger.Note('asdf')
logger.Print('Just print')
|
#Jessica De Mota Munoz
#jessica.demotamunoz86@myhunter.cuny.edu
#September,11,2019
#we need to use a variable to assign our user input
#our user needs to be able to insert any message; think of it like a chatbox
#so in this case we use the variable greeting to make a user input to insert a message
greeting = input("Put a message here to show user: ")
#we want to print our message normally
#and then we want to be able to print our string in upper case and lower case
#.lower and .upper are string handling componets in python
#it basically uses a true- false kind of ideal to be able to convert all characthers
print(greeting)
print(greeting.upper())
print(greeting.lower())
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.