import datetime
import pytz
available_zones ={"1":"African/Tunis",
"2":"Asia/Kolkata",
"3":"Australia/Adelaide",
"4":"Europe/Brussels",
"5":"Europe/London",
"6":"Japan",
"7":"Pacific/Tahiti"
}
print("Please Choose the timezone (or 0 to quit)")
for place in sorted(available_zones):
print("\t {} : {}".format(place,available_zones[place]))
while True:
choice = input()
if choice == 0:
break
if choice in available_zones.keys():
tz_to_display = pytz.timezone(available_zones[choice])
world_time = datetime.datetime.now(tz=tz_to_display)
print ("The time in {} is {} {} ".format(available_zones[choice],
world_time.strftime("%A %x %X %z"),world_time.tzname()))
print("LocalTime is {}".format(datetime.datetime.now().strftime("%A %x %X %z")))
print("UTCTime is {}".format(datetime.datetime.utcnow().strftime("%A %x %X %z")))
Wednesday, 28 February 2018
Python timezone challenge- Day 17
Python timezone - Day 16(1 day later)
import pytz
import datetime
country = "Europe/Moscow" #check for the spelling and case sensitivity
tz_to_display = pytz.timezone(country)
# print(tz_to_display)
# print(country)
print("The time in {} is {}".format(country,datetime.datetime.now(tz=tz_to_display)))
print("UTC is {}".format(datetime.datetime.utcnow()))
print("LocalTime here is {}".format(datetime.datetime.now()))
tz_to_display = pytz.timezone("Singapore")
print("The time in {} is {}".format("Singapore",datetime.datetime.now(tz=tz_to_display)))
#list of all timezones
for x in pytz.all_timezones:
print(x)
print("=="*50)
print(pytz.country_names)
#list of all countries
for x in pytz.country_names:
print(x)
for x in sorted(pytz.country_names):
print(x + ": " + pytz.country_names[x])
#although the below code will run,there will be error ,since the few countries
#like (Bouvet Island ) have not defined the timezones
# for x in sorted(pytz.country_names):
# print("{} : {} : {}".format(x,pytz.country_names[x],pytz.country_timezones(x)))
print("=================="*10)
#we can use the get method to avoid the below issue
for x in sorted(pytz.country_names):
print("{} : {} : {}".format(x,pytz.country_names[x],pytz.country_timezones.get(x)))
print("*************"*10)
#we can also use the below method
for x in sorted(pytz.country_names):
print("{} : {} ".format(x,pytz.country_names[x],end = ' '))
if x in (pytz.country_timezones):
print(pytz.country_timezones[x])
else:
print("TimeZone Not Defined")
Monday, 26 February 2018
Python date time calendar module - Day 15
# import time
# # print(time.gmtime())
# # ##epoch time
# # print(time.gmtime(0))
# # print("="*40)
# # print(time.localtime())
# # print("="*40)
# # ##seconds till now from epoch time
# # print(time.time())
#
# time_here = time.localtime()
# print(time_here)
# #time_here is a tuple ,we can make use of the tuple index or name ,so that
# #we can get the desired part of the date
# print("year:",time_here[0],time_here.tm_year)
# print("Month:",time_here[1],time_here.tm_mon)
# print("Day:",time_here[2],time_here.tm_mday)
#reaction time game
# import time
# from time import time as my_timer
# import random
#
# input("press enter to start")
# wait_time = random.randint(1,6)
# time.sleep(wait_time)
# start_time=my_timer()
# input("press enter to stop")
# end_time=my_timer()
#
# print(start_time,end_time)
# print("started at "+ time.strftime("%X",time.localtime(start_time)))
# print("Ended at "+ time.strftime("%X",time.localtime(end_time)))
# print("Time taken for response was {}".format(end_time-start_time))
#apart from the time method we also have three other methods that we can make use of
#monotonic - this can be used ,so that even if there is daylight saving time,activates
#in the mean time or the user changes the clock in system,always the end time
#will be higher than the
#start time if we use the monotonic
#other 1 is perf_counter
#and the process_time is the elapsed cpu time for the process
#proposal for python - PEP 0418 can read from there
import time
# # from time import perf_counter as my_timer
# # from time import monotonic as my_timer
# from time import process_time as my_timer
# import random
#
#
# input("press enter to start")
# wait_time = random.randint(1,6)
# time.sleep(wait_time)
# start_time=my_timer()
# input("press enter to stop")
# end_time=my_timer()
#
# print(start_time,end_time)
# print("started at "+ time.strftime("%X",time.localtime(start_time)))
# print("Ended at "+ time.strftime("%X",time.localtime(end_time)))
# print("Time taken for response was {}".format(end_time-start_time))
#info about the each clock
print("time():\t\t\t",time.get_clock_info("time"))
print("monotonic():\t",time.get_clock_info("monotonic"))
print("perf_counter():\t",time.get_clock_info("perf_counter"))
print("process_time():\t",time.get_clock_info("process_time"))
Sunday, 25 February 2018
Python Modules - Day 14(day later)
# import turtle
#
#
# turtle.forward(400)
# turtle.circle(250)
# turtle.right(300)
#
# #the done function is used to hold the screen to see the result
# #or else we can use the time module and sleep function
#
#
# for i in range(0,100,10):
# turtle.forward(i)
# turtle.circle(i)
# turtle.right(i)
#
#
# turtle.done()
#if we need only the particular functions we can code like below
# from turtle import circle,done
#
# circle(70)
# done()
#or else we can do use *
# from turtle import *
#
# circle(70)
# done()
#we will get the error if we run the below piece of code
#since the done is common here,we declared as string,but the turtle method
#also has the "done" as function
done = "done with the drawing"
import turtle
turtle.forward(400)
turtle.circle(250)
turtle.right(300)
done()
print(done)
#here we can check the list of objects inside the
#inbuilt modules of the python
#we can also ctrl + click the module name to find the list of objects
print(dir())
#the above line will print
#['__annotations__', '__builtins__', '__cached__', '__doc__',
## '__file__', '__loader__', '__name__', '__package__', '__spec__']
print("="*40)
for i in dir():
print(i)
print(dir('__builtins__'))
#the above line will print
#['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__',
# '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__gt__',
# '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__',
# '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__',
# '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__',
# 'capitalize', 'casefold', 'center', 'count', 'encode', 'endswith', 'expandtabs', 'find',
# 'format', 'format_map', 'index', 'isalnum', 'isalpha', 'isdecimal', 'isdigit', 'isidentifier',
# 'islower', 'isnumeric', 'isprintable', 'isspace', 'istitle', 'isupper', 'join', 'ljust',
# 'lower',
# 'lstrip', 'maketrans', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition',
# 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title',
# 'translate', 'upper', 'zfill']
print("="*40)
for i in dir('__builtins__'):
print(i)
#lets check for the shelve now
import shelve
print(dir())
# ['__annotations__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__',
#'__name__',
# '__package__', '__spec__', 'i', 'shelve']
print(dir(shelve))
# ['BsdDbShelf', 'BytesIO', 'DbfilenameShelf', 'Pickler',
# 'Shelf', 'Unpickler', '_ClosedDict', '__all__', '__builtins__',
# '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__',
# 'collections', 'open']
print(dir(shelve.Shelf))
print('=='*20)
for i in dir(shelve.Shelf):
print(i)
#we can use the help function to know the functionality
help(shelve)
print("*"*20)
help(shelve.Shelf)
import random
help(random)
print("*"*20)
help(random.randint)
Friday, 23 February 2018
Python Shelve eg2....- Day 13
import shelve
# with shelve.open("D:/WORK/2018/February/23-02-2018-Friday/shelveeg3") as fruit:
fruit = shelve.open("D:/WORK/2018/February/23-02-2018-Friday/shelveeg3")
fruit['orange']='citrus fruit'
fruit['apple']='good for health'
fruit['lemon']='small fruit'
fruit['papaya']='good for eye'
print(fruit)
print(fruit['lemon'])
fruit['lemon']='Can Make Juice'
print(fruit)
print(fruit['lemon'])
for i in fruit:
print(i +" - " + fruit[i])
print("="*40)
# while True:
# var1 = input("enter any fruit key - ")
# if var1 =='quit':
# break
# # print(fruit.get(var1,'entered key doent exits'))
# if var1 in fruit:
# print(fruit[var1])
# else:
# print('entered key does not exits')
#to get the shelve in sorted order
shelvesortlist = list(fruit.keys())
shelvesortlist.sort()
print(shelvesortlist)
print(fruit)
for var2 in shelvesortlist:
print(var2+" - "+fruit[var2])
print (fruit.values())
print (fruit.items())
print (fruit.keys())
fruit.close()
#the below example is not prefect,but the thing is there is a concept of writeback and sync
#related to shelve object,which can be used to update the shelve based on memory usage
#the benefits of these will be know later i guess.
import shelve
blt = ["bread","bacon","lettuce"]
egg = ["boiled egg","Milk"]
butter = ["cheese","butter"]
pasta = ["pasta","macroni"]
with shelve.open("D:/WORK/2018/February/23-02-2018-Friday/shelveupdateeg4") as recipes:
recipes["blt"]=blt
recipes["egg"]=egg
recipes["butter"]=butter
recipes["pasta"]=pasta
print(recipes)
for var1 in recipes:
print(var1,recipes[var1])
#in the eg above if we want to update the items against any key in shelve,
#if we use append method ,it wont update the shelve like check using the below code
recipes["egg"].append("omlette")
for var1 in recipes:
print(var1,recipes[var1])
#we can update it correcty by changing the list itself and reassigning to the shelve
templist = ["boiled egg","Milk","omlette"]
recipes["egg"]=templist
for var1 in recipes:
print(var1,recipes[var1])
print("="*40)
with shelve.open("D:/WORK/2018/February/23-02-2018-Friday/shelveupdateeg4") as recipes:
for var1 in recipes:
print(var1,recipes[var1])
print('*'*40)
Thursday, 22 February 2018
Python Shelve- Day 12(1 day later)
import shelve
# with shelve.open("D:/WORK/2018/February/22-02-2018-Thursday/shelvetest1")as fruit:
# fruit = {"orange":"its a fruit which is orange in color",
# "apple":"good for health"}
# print(fruit)
# print(fruit["orange"])
# print("="*40)
# print(fruit["orange"])
# print(fruit)
with shelve.open("D:/WORK/2018/February/22-02-2018-Thursday/shelvetest2")as fruit:
fruit["orange"]="its a fruit which is orange in color"
fruit["apple"]="good for health"
print(fruit)
print("="*40)
#the below peice of code will throw an error
# print(fruit["orange"])
with shelve.open("D:/WORK/2018/February/22-02-2018-Thursday/shelvebike1")as bike:
bike["name"]="tvs"
bike["engine_cc"]="250 cc"
#even if removed and executes the below code it will be saved
#in the first run and remains there,which is not the case if
#it is normal dictionary
# bike["engin_cc"]="250 cc"
bike["model"]="victor"
print(bike)
for i in bike:
print(i)
print(bike[i])
###############################################################################
import shelve
with shelve.open("D:/WORK/2018/February/22-02-2018-Thursday/shelvebike1")as bike:
bike["name"]="tvs"
bike["engine_cc"]="250 cc"
#even if removed and executes the below code it will be saved
#in the first run and remains there,which is not the case if
#it is normal dictionary
# bike["engin_cc"]="250 cc"
#we can delete that key using,it has to be run one time only
# del bike["engin_cc"]
bike["model"]="victor"
print(bike)
for i in bike:
print(i)
print(bike[i])
Python Read Write File,Binary Read Write File - Day 11(2 days later)
# #this shows how to open and read contents from the file
# samplefilevar = open("D:/WORK/2018\February/20-02-2018-Tuesday/pythonsamplereadfile.txt",'r')
# for linevar in samplefilevar:
# print (linevar)
# samplefilevar.close()
#
# print("===="*20)
# #print only the lines containing the specific word
# samplefilevar = open("D:/WORK/2018\February/20-02-2018-Tuesday/pythonsamplereadfile.txt",'r')
# for linevar in samplefilevar:
# if "file" in linevar.lower():
# print (linevar,end = '')
# samplefilevar.close()
# print("===="*20)
# #using with keyword will automatically close the file,we dont need to
# #use the separate close statement
#
# with open("D:/WORK/2018\February/20-02-2018-Tuesday/pythonsamplereadfile.txt",'r')as var2:
# for line in var2:
# #end = '' is used to avoid using the extra empty line
# print(line,end='')
# with open("D:/WORK/2018\February/20-02-2018-Tuesday/pythonsamplereadfile.txt",'r')as var2:
# line =var2.readline()
# print(line)
# with open("D:/WORK/2018\February/20-02-2018-Tuesday/pythonsamplereadfile.txt",'r')as var2:
# #readlines will read all lines and piut it into list,so it is better to use readline,
# #since the readlines will read the entire file in memory,where as readline will
# #go row by row
# lines =var2.readlines()
# print(lines)
#
# for line1 in lines:
# print(line1,end='')
#write contents to a file
# cities = ["Delhi","Bombay","Chennai"]
#
# with open("D:/WORK/2018\February/20-02-2018-Tuesday/pythonsamplewritefile1.txt",'w')as var2:
# for city in cities:
# print(city,file=var2)
#
# with open("D:/WORK/2018\February/20-02-2018-Tuesday/pythonsamplewritefile1.txt",'r')as var3:
# cities = var3.readlines()
# print(cities)
#
# #strip functions strips the character that is present at the end or beginning
#,but not the middle
# for city in cities:
# print(city)
# print(city.strip("\n"))
#
# cityvar1 = []
# with open("D:/WORK/2018\February/20-02-2018-Tuesday/pythonsamplewritefile1.txt",'r')as var3:
# cities = var3.readlines()
# for city in cities:
# cityvar1.append(city)
#
# print(cityvar1)
#
# cityvar2 = []
# with open("D:/WORK/2018\February/20-02-2018-Tuesday/pythonsamplewritefile1.txt",'r')as var3:
# cities = var3.readlines()
# for city in cities:
# cityvar2.append(city.strip("\n"))
#
# print(cityvar2)
#
# strvar1 = "testing"
# print(strvar1.strip("s"))
# print(strvar1.strip("g"))
# #below will remove t at the beginning not the st at the middle
# print(strvar1.strip("st"))
#tuples to file
# albumtuplevar2 = "muthu","rahman",2000,(1,"oruvan oruvan"),(2,"kuluvall"),(3,"vidukathaya")
# print(albumtuplevar2)
# title,composer,year,track1,track2,track3 =albumtuplevar2
# print(title)
# print(composer)
# print(year)
# print(track1)
# print(track2)
# print(track3)
#
# with open("D:/WORK/2018\February/20-02-2018-Tuesday/pythonsamplewritefile2.txt",'w')as var2:
# print(albumtuplevar2,file=var2)
with open("D:/WORK/2018\February/20-02-2018-Tuesday/pythonsamplewritefile2.txt",'r')as var3:
var4 = var3.readlines()
print(var4)
print(var4)
######################################################################
#appending the tables to the existing file
#if we use the mode 'a',it will append it ,if we use the mode 'w',it will overwrite the file
#our challenge is to print like
#1 times 2 is 2
#2 times 2 is 4
#....
#likewise till 13 table
with open("D:/WORK/2018/February/20-02-2018-Tuesday/pythonwritefile3.txt",'w')as tables:
for i in range(1,1000):
for j in range(1,1000):
print("{1} times {0} is {2}".format(i,j,i*j),file=tables)
print("=="*20,file=tables)
#######################################################################
#We can use pickle ,instead of converting the binaty manually and reconverting
#while reading
import pickle
imedla = ('More Mayhem',
'Imelda May',
'2011',
((1,'Pulling the rug'),
(2,'Psycho'),
(3,'Mayhem'),
(4,'Kentish Town Waltz')))
# with open("D:/WORK/2018/February/22-02-2018-Thursday/pythonwritefilebinary.pickle","wb")
as pickle_file:
# pickle.dump(imedla,pickle_file)
with open("D:/WORK/2018/February/22-02-2018-Thursday/pythonwritefilebinary.pickle","rb")
as imelda_pickled:
imelda2 = pickle.load(imelda_pickled)
print(imelda_pickled)
print(imelda2)
album,artist,year,tracklist = imelda2
print (album)
print (artist)
print (year)
for track in tracklist:
trackno,tracktile = track
print("{0} : {1}".format(trackno,tracktile))
#########################################################################################
#storing multiple objects in the binary file and retrieving it in the same order
import pickle
imedla = ('More Mayhem',
'Imelda May',
'2011',
((1,'Pulling the rug'),
(2,'Psycho'),
(3,'Mayhem'),
(4,'Kentish Town Waltz')))
even = list(range(0,10,2))
odd = list(range(1,10,2))
with open("D:/WORK/2018/February/22-02-2018-Thursday/pythonwritefilebinary2.pickle","wb")
as pickle_file:
pickle.dump(imedla,pickle_file,protocol=0)
pickle.dump(even,pickle_file,protocol=0)
pickle.dump(odd,pickle_file,protocol=0)
pickle.dump(12345,pickle_file,protocol=0)
#to read the above objects we need to read it in the same order ie..tuples,list,variable
with open("D:/WORK/2018/February/22-02-2018-Thursday/pythonwritefilebinary2.pickle","rb")
as imelda_pickled:
imelda2 = pickle.load(imelda_pickled)
even_list = pickle.load(imelda_pickled)
odd_list = pickle.load(imelda_pickled)
x = pickle.load(imelda_pickled)
print(imelda_pickled)
print(imelda2)
album,artist,year,tracklist = imelda2
print (album)
print (artist)
print (year)
for track in tracklist:
trackno,tracktile = track
print("{0} : {1}".format(trackno,tracktile))
print("="*40)
for i in even_list:
print(i)
print("="*40)
for i in odd_list:
print(i)
print("="*40)
print(x)
###################################################################################
Monday, 19 February 2018
Python Sets - Day 10(day later)
farm_animals = {"cow","goat"}
print(farm_animals)
wild_animals= set(["Lion","Tiger"])
farm_animals.add("horse")
print(farm_animals)
wild_animals.add("horse")
print(wild_animals)
evennos = set(range(0,50,2))
print(evennos)
evennos = set(range(0,50,2))
print(evennos)
squares = {4,9,16,25,36}
print(squares)
print(sorted(squares))
print (squares.union(evennos))
#both will produce same result
print (evennos.union(squares))
#both will produce same result
print (squares.intersection(evennos))
print (evennos.intersection(squares))
print (evennos & squares)
print (squares & evennos )
#*empty set can not be created by using the curly braces {},since it will be treated as
dictionary when calling the add method
emptyset1 = {}
print(emptyset1)
#the below code will throw error
# emptyset1.add("1")
print(emptyset1)
emptyset2 = set()
print(emptyset2)
#but not the below code
emptyset2.add("1")
print(emptyset2)
#differences/Minus
print(evennos)
print(squares)
print("squares minus evenos")
print(squares.difference((evennos)))
print(squares - evennos)
print("evenos minus squares ")
print(evennos.difference((squares)))
print(evennos - squares)
#update the difference in the set
squaretuple = (4,9,16,25,36)
squarenos = set(squaretuple)
evennos = set(range(0,50,2))
print(sorted(evennos))
print(sorted(squarenos))
print("="*40)
#will update the set after the difference
evennos.difference_update(squarenos)
print(evennos)
#symmetric difference,it is exact opposite of intersection
squarenos1 = {4,9,16,25,36}
evennos1 = set(range(0,50,2))
print(sorted(squarenos1))
print(sorted(evennos1))
print(evennos1.symmetric_difference(squarenos1))
#it will return the same result for both the line of the code
print(squarenos1.symmetric_difference(evennos1))
#discard & Remove,these two will affect the sets directly,
#disacard wont throw an error ,even if the value is not present there in the set,
#where as remove will throw if it does not exits
print(sorted(squarenos1))
print(sorted(evennos1))
squarenos1.discard(4)
squarenos1.remove(16)
print(sorted(squarenos1))
#wont throw error
squarenos1.discard(5)
#will throw error
# squarenos1.remove(5)
evensquarenos2 = {4,16,36}
evennos2 = set(range(0,50,2))
print(sorted(evensquarenos2))
print(sorted(evennos2))
if evennos2.issuperset(evensquarenos2):
print("evennos is the superset of the evensquarenos")
if evensquarenos2.issubset(evennos2):
print("evensquarenos is the subset of the evennos")
#frozenset,we can add,edit,remove the frozen set,but can do other operations
#like union,intersection...
evenfrozen = frozenset({2,4,6})
print(evenfrozen)
#the below line will throw an error,since we are trying
#to modify the frozen set which is not allowed
# evenfrozen.add(8)
#challenge ,remove the vowels from the string
stringval1= set("python is trending language")
stringval2= set("abcdefghijklmnopqrstuvwxyz")
frozensetstring = frozenset("aeiou")
print(stringval1.difference(frozensetstring))
print(sorted(stringval2.difference(frozensetstring)))
Saturday, 17 February 2018
Python Dictionaries CopyUpdate- Day 9(After 6 days)
# filmsvar1 = {"muthu":"one of the movie in which rajini comes in double role",
# "basha":"Don of a don movie,a cult hit",
# "enthiran":"rajini's scifi movie",
# "murattu kalai":"movie taken in paganeri"}
#
# filmsvar2 = {"BLoodStonte":"Rajini's Hollywood Movie",
# "enthiran2":"Upcoming Movie"}
#
# # print(filmsvar1)
# # print(filmsvar2)
# # #this will update the filmsvar1 wont create a separate object
# # filmsvar1.update(filmsvar2)
# # print(filmsvar1)
# # print(filmsvar2)
#
# #to make a copy of dictionary
#
# filmsvar3 = filmsvar2.copy()
# print(filmsvar2)
# print(filmsvar3)
# filmsvar2.update(filmsvar1)
# print(filmsvar2)
# print(filmsvar3)
#
# #Use the old challenge and make it work even if the user types valley,road directly
#
# location = {0:"You are Sitting in front of comp",
# 1:"You are in road",
# 2:"At the top of the hill",
# 3:"Building",
# 4:"You are across Valley",
# 5:"Roaming at forest"}
# exits = {0:{"Q":0},
# 1:{"N":5,"5":5,"S":4,"4":4,"E":3,"3":3,"Q":0},
# 2:{"N":5,"5":5,"Q":0},
# 3:{"W":1,"1":1,"Q":0},
# 4:{"W":2,"2":2,"N":1,"1":1,"Q":0},
# 5:{"S":1,"1":1,"W":2,"2":2,"Q":0}}
#
# vocabularyvar = {"NORTH":"N","SOUTH":"S","EAST":"E","WEST":"W","QUIT":"Q",
# "ROAD":"1","HILL":"2","BUILDING":"3","VALLEY":"4","FOREST":"5"}
#
# loc=1
# while True:
# availablexits = ""
# #we can use join to do the fllowing
# # for direction in exits[loc].keys():
# # availablexits +=direction+ ","
# availablexits = ','.join(exits[loc].keys())
#
# print(location[loc])
#
# if loc == 0:
# break
#
# direction = input("Available Exits are "+ availablexits).upper()
# if len(direction)>0:
# words = direction.split()
# for word in words:
# if word in vocabularyvar:
# direction = vocabularyvar[word]
# print(direction)
# print()
# if direction in exits[loc]:
# loc = exits[loc][direction]
# else:
# print("You cannot go in that direction")
#the above code will work,but it will unnecessarily will show no's 1,2,3,4,5 in the
# available exits,so we can use the copy and update funtions in dictionary to solve those issues
location = {0:"You are Sitting in front of comp",
1:"You are in road",
2:"At the top of the hill",
3:"Building",
4:"You are across Valley",
5:"Roaming at forest"}
exits = {0:{"Q":0},
1:{"N":5,"S":4,"E":3,"Q":0},
2:{"N":5,"Q":0},
3:{"W":1,"Q":0},
4:{"W":2,"N":1,"Q":0},
5:{"S":1,"W":2,"Q":0}}
namedexits = {1:{"5":5,"4":4,"3":3,"Q":0},
2:{"5":5,"Q":0},
3:{"1":1,"Q":0},
4:{"2":2,"1":1,"Q":0},
5:{"1":1,"2":2,"Q":0}}
vocabularyvar = {"NORTH":"N","SOUTH":"S","EAST":"E","WEST":"W","QUIT":"Q",
"ROAD":"1","HILL":"2","BUILDING":"3","VALLEY":"4","FOREST":"5"}
loc=1
while True:
availablexits = ""
#we can use join to do the fllowing
# for direction in exits[loc].keys():
# availablexits +=direction+ ","
availablexits = ','.join(exits[loc].keys())
print(location[loc])
if loc == 0:
break
else:
allexits = exits[loc].copy()
allexits.update(namedexits[loc])
direction = input("Available Exits are "+ availablexits).upper()
if len(direction)>0:
words = direction.split()
for word in words:
if word in vocabularyvar:
direction = vocabularyvar[word]
print(direction)
print()
#previously we used index ,since it it dictionary under dictionary
if direction in allexits:
loc = allexits[direction]
else:
print("You cannot go in that direction")
Python Dictionaries Challenge - Day 8(After 1 Week)
# location = {0:"You are Sitting in front of comp",
# 1:"You are in road",
# 2:"At the top of the hill",
# 3:"Building",
# 4:"You are across Valley",
# 5:"Roaming at forest"}
# exits = [{"Q":0},{"N":5,"S":4,"E":3,"Q":0},{"N":5,"Q":0},{"W":1,"Q":0},
{"W":2,"N":1,"Q":0},{"S":1,"W":2,"Q":0}]
# loc=1
# while True:
# availablexits = ""
# #we can use join to do the fllowing
# # for direction in exits[loc].keys():
# # availablexits +=direction+ ","
# availablexits = ','.join(exits[loc].keys())
#
# print(location[loc])
#
# if loc == 0:
# break
#
# direction = input("Available Exits are "+ availablexits).upper()
# print()
# if direction in exits[loc]:
# loc = exits[loc][direction]
# else:
# print("You cannot go in that direction")
#the 1st challenge here is to convert the exit list to dictionary,
#list index can be converted to dictionary ,by making the list index no
# to corresponding dictionary key in this case
#
#
# location = {0:"You are Sitting in front of comp",
# 1:"You are in road",
# 2:"At the top of the hill",
# 3:"Building",
# 4:"You are across Valley",
# 5:"Roaming at forest"}
# exits = {0:{"Q":0},
# 1:{"N":5,"S":4,"E":3,"Q":0},
# 2:{"N":5,"Q":0},
# 3:{"W":1,"Q":0},
# 4:{"W":2,"N":1,"Q":0},
# 5:{"S":1,"W":2,"Q":0}}
# loc=1
# while True:
# availablexits = ""
# #we can use join to do the fllowing
# # for direction in exits[loc].keys():
# # availablexits +=direction+ ","
# availablexits = ','.join(exits[loc].keys())
#
# print(location[loc])
#
# if loc == 0:
# break
#
# direction = input("Available Exits are "+ availablexits).upper()
# print()
# if direction in exits[loc]:
# loc = exits[loc][direction]
# else:
# print("You cannot go in that direction")
#the 2nd challenge is to make use of the vocabulary,
#ie user may not type in the exact letters like N,S,W,E,
#user can type north,south as well
#
# location = {0:"You are Sitting in front of comp",
# 1:"You are in road",
# 2:"At the top of the hill",
# 3:"Building",
# 4:"You are across Valley",
# 5:"Roaming at forest"}
# exits = {0:{"Q":0},
# 1:{"N":5,"S":4,"E":3,"Q":0},
# 2:{"N":5,"Q":0},
# 3:{"W":1,"Q":0},
# 4:{"W":2,"N":1,"Q":0},
# 5:{"S":1,"W":2,"Q":0}}
#
# vocabularyvar = {"North":"N","South":"S","East":"E","WEST":"W","QUIT":"Q"}
#
# loc=1
# while True:
# availablexits = ""
# #we can use join to do the fllowing
# # for direction in exits[loc].keys():
# # availablexits +=direction+ ","
# availablexits = ','.join(exits[loc].keys())
#
# print(location[loc])
#
# if loc == 0:
# break
#
# direction = input("Available Exits are "+ availablexits)
# if len(direction)>0:
# if direction in vocabularyvar:
# direction = vocabularyvar[direction].upper()
# print(direction)
# print()
# if direction in exits[loc]:
# loc = exits[loc][direction]
# else:
# print("You cannot go in that direction")
#
# split command,will split the string by default by space,the result will be of list type
# location = {0:"You are Sitting in front of comp",
# 1:"You are in road",
# 2:"At the top of the hill",
# 3:"Building",
# 4:"You are across Valley",
# 5:"Roaming at forest,which is wild"}
#
# print(location[0])
# print(location[0].split())
# print(location[5].split(","))
# print(" ".join(location[0].split()))
#using the split command in the above example and checking whether one of the user entered words,
#matches with the exits,like if the user enters "I Prefer South"/"I want to go north"
location = {0:"You are Sitting in front of comp",
1:"You are in road",
2:"At the top of the hill",
3:"Building",
4:"You are across Valley",
5:"Roaming at forest"}
exits = {0:{"Q":0},
1:{"N":5,"S":4,"E":3,"Q":0},
2:{"N":5,"Q":0},
3:{"W":1,"Q":0},
4:{"W":2,"N":1,"Q":0},
5:{"S":1,"W":2,"Q":0}}
vocabularyvar = {"NORTH":"N","SOUTH":"S","EAST":"E","WEST":"W","QUIT":"Q"}
loc=1
while True:
availablexits = ""
#we can use join to do the fllowing
# for direction in exits[loc].keys():
# availablexits +=direction+ ","
availablexits = ','.join(exits[loc].keys())
print(location[loc])
if loc == 0:
break
direction = input("Available Exits are "+ availablexits).upper()
if len(direction)>0:
words = direction.split()
for word in words:
if word in vocabularyvar:
direction = vocabularyvar[word]
print(direction)
print()
if direction in exits[loc]:
loc = exits[loc][direction]
else:
print("You cannot go in that direction")
Saturday, 10 February 2018
Python Dictionaries part1 - Day 7
#dictionary can not be accessed vy index,but through key value
films = {"muthu":"one of the movie in which rajini comes in double role",
"basha":"Don of a don movie,a cult hit",
"enthiran":"rajini's scifi movie",
"murattu kalai":"movie taken in paganeri"}
print(films)
print(films["murattu kalai"])
#to add a new value to dictionay we dont have a method or function,but we can assign like the below one
films["kaala"]="more like a basha 2,april 27th - 2018 release"
print(films)
#if we use the same key and assign it will update instead of creating new element
films["kaala"]="probably thalaivars gonna be biggest hit"
print(films)
#similarly it will take the last set of key,value combination if there is any duplicate
films = {"muthu":"one of the movie in which rajini comes in double role",
"basha":"Don of a don movie,a cult hit",
"enthiran":"rajini's scifi movie",
"murattu kalai":"movie taken in paganeri",
"muthu":"one of the thalaivar & sarath babu combination movie"}
print (films["muthu"])
bike = {"make":"royal enfiled","model":"himalayan","cc":400,"review":"mostly avg or bad"}
print (bike["model"])
print (bike["cc"])
#delete a element or delete a entire dictonary or cleare the elements in the dictionary
del(bike["review"])
# del(bike)
# bike.clear()
print (bike)
#getting the unpresent key value will result in error,in that case we can use get function
# print (bike["color"])
print(bike.get("color"))
#while True is used to make the user keep qasking the questions,unless he types quit
# while True:
# x = input("enter any thalaivar's film name: ")
# if x == "quit":
# break
# description = films.get(x)
# print(description)
# #the below piece of code will return error if we enter any unknown key value
# print(films[x])
#same code is rewritten to print the custom message if the value doesnot exists in dictory
while True:
x = input("enter any thalaivar's film name: ")
if x == "quit":
break
if x in films:
description = films.get(x)
print(description)
print(films[x])
else:
print ("{} - doesnot exists in dictionaryy".format(x))
Python Handling Binary ,Hex and octal Numbers - Day 6(posted next day)
# #decimal numbers in binary
# for i in range(10):
# print("{0:>2} in binary is {0:>8b}".format(i))
#
# print(0b1011)
# #hex decimal
# for i in range(257):
# print("{0:>2} in hex is {0:>02x}".format(i))
#
# #hex multipliation
# x = 0x20
# y = 0x0a
# print(x*y)
# #operations like or,and,xor,add,subtract refreshed
#converting decimal to binary through program
# print(10//2)
# print(10%3)
# powers = []
# for power in range(15,-1,-1):
# powers.append(2**power)
# # print(powers)
# print(powers)
# x = int(input("enter any number less than 65535 to convert to binary \n"))
# for i in powers:
# # print(i)
# print(x//i,end ='')
# x%=i
#the above program will work ,but to avoid the trialing 0's can use the below code
powers = []
for power in range(15,-1,-1):
powers.append(2**power)
# print(powers)
print(powers)
printing = False
x = int(input("enter any number less than 65535 to convert to binary \n"))
for i in powers:
# print(i)
bit = x//i
if bit!=0 or i ==1:
printing =True
if printing==True:
print(bit,end ='')
x%=i
Wednesday, 7 February 2018
Python Tuples - Day 5(posted next day)
# tuplevar1 = ("a","b","c")
# tuplevar2 = "a","b","c"
# print(tuplevar1)
# print(tuplevar2)
# print(("a","b","c"))
# print("a","b","c")
#
# #tuples are immutable objects,meaning they cannot be changed/altered ,
#they can only be assigned
# welcome = "hi","hello",2018
# print(welcome)
# print(welcome[0])
# #the below line of code will give an error ,since we are trying to alter the tuple
# # welcome[0]="hii"
# print(welcome)
#
# tupvar1 = "hi","ji"
# print(tupvar1)
# tupvar2 = welcome[1],tupvar1[0],2019
# print(tupvar2)
#
# #where as the list object can be altered like below
# listvar1 = ["hi","hello",2020]
# print(listvar1)
# listvar1[0]="Hii"
# print(listvar1)
#right side expression is evaluated first
# a , b = 1,2
# print(a,b)
# c=d=e=f=2
# print(c,d,e)
# a,b =b,a
# print(a,b)
#
# albumtuplevar1 = "muthu","rahman",2000
# print(albumtuplevar1)
# title,composer,year =albumtuplevar1
# print(title)
# print(composer)
# print(year)
#the below piece of code will throw an error like ValueError: not enough values
#to unpack (expected 4, got 3)
# var1,var2,var3,var4=albumtuplevar1
# print(var1)
# print(var2)
# print(var3)
# print(var4)
#the below piece of code will throw an error likeValueError:
#too many values to unpack (expected 2
# var1,var2=albumtuplevar1
# print(var1)
# print(var2)
#append work in tuple
# albumtuplevar1.append("Action")
#tuple inside tuple
# albumtuplevar1 = "muthu","rahman",2000,((1,"oruvan oruvan"),(2,"kuluvall"),(3,"vidukathaya"))
# print(albumtuplevar1)
# title,composer,year,tracks =albumtuplevar1
# print(title)
# print(composer)
# print(year)
# print(tracks)
# albumtuplevar2 = "muthu","rahman",2000,(1,"oruvan oruvan"),(2,"kuluvall"),(3,"vidukathaya")
# print(albumtuplevar2)
# title,composer,year,track1,track2,track3 =albumtuplevar2
# print(title)
# print(composer)
# print(year)
# print(track1)
# print(track2)
# print(track3)
#
# #printing the tracks w/o knowing the count
# title,composer,year,tracks =albumtuplevar1
# print(title)
# print(composer)
# print(year)
# for song in tracks:
# no,songtitle = song
# print("songno-{},songtitle-{}".format(no,songtitle))
# print(song)
#mutable object inside a tuple can be altered,like the below example the list
#inside the tuple can be changed
albumtuplevar3 = "muthu","rahman",2000,[(1,"oruvan oruvan"),(2,"kuluvall"),(3,"vidukathaya")]
print(albumtuplevar3)
print(albumtuplevar3[3])
albumtuplevar3[3].append((4,"thillana thillana"))
print(albumtuplevar3)
for song in albumtuplevar3[3]:
no,songtitle = song
print("songno-{},songtitle-{}".format(no,songtitle))
title,composer,year,tracks =albumtuplevar3
tracks.append((5,"kokku seva kokku"))
print(albumtuplevar3)
for song in tracks:
no,songtitle = song
print("songno-{},songtitle-{}".format(no,songtitle))
Python List part2 and range part1 - Day3(posted next day)
#list inside a list
# menu = [];
# menu.append(["egg","milk","spam"])
# menu.append(["egg","milk","spam","bacon"])
# menu.append(["egg","milk"])
#
# for menuilist in menu:
# if "spam" not in menuilist:
# print(menuilist)
# for menuitem in menuilist:
# print(menuitem)
#few examples of iterables are String,List
#iterator,for loop already handles this function automatically
stringvar = "12345asd"
my_iterator = iter(stringvar)
print(my_iterator)
print(next(my_iterator))
print(next(my_iterator))
print(next(my_iterator))
print(next(my_iterator))
print(next(my_iterator))
print(next(my_iterator))
print(next(my_iterator))
print(next(my_iterator))
#will print an error if it exceeds the last iterable
# print(next(my_iterator))
daysinweekvar = ["Sun","Mon","Tue","Wed","Thurs","Fri","Sat",]
# for i in daysinweekvar:
# print(i)
print(len(daysinweekvar))
daysinweekitervar = iter(daysinweekvar)
for i in range(0,len(daysinweekvar)):
print(next(daysinweekitervar))
print (range(0,100))
print (range(100))
print (list(range(0,100)))
print (list(range(100)))
print (list(range(0,100,2)))
oddvar1 = range(1,100,2)
oddlistvar1 = list(range(1,100,2))
print(oddvar1)
print(oddlistvar1)
print(oddvar1.index(9))
print(oddlistvar1.index(9))
print(oddvar1[2])
print(oddlistvar1[2])
sevens = range(7,10000,7)
var2 = int(input("enter any no less than 10k"))
for var3 in sevens:
if var2 == var3:
print("{} is divisble by 7".format(var2))
Monday, 5 February 2018
Python List part1 - Day2
# ipaddress = input("enter a ip address \n")
# print (ipaddress.count("."))
#
# parrot_list = ["no more","a stiff"]
# print (parrot_list)
# parrot_list.append("green")
# print (parrot_list)
#
# for var in parrot_list:
# print (var)
#
# evenno = [2,4,4,6,8]
# odd = [1,3,5,7]
#
# print (evenno + odd)
# print (sorted(evenno + odd))
# numbers = evenno + odd
# #if u try the below code it wont return the sorted values,
# #because it will update the list and returns none as result
# #you can use sorted function if it has to be sorted at the time,but not
# #the original list itself
# # print (numbers.sort())
# numbers.sort()
# print (numbers)
# unsortednos = evenno + odd
# sortednos = (sorted(evenno + odd))
#
# #comparison wont be equal even if we have the same list items but in different order
# if sortednos == unsortednos:
# print ("equal")
# else:
# print ("not equal")
#
#
# if sortednos == sorted(unsortednos):
# print ("equal")
# else:
# print ("not equal")
# list_1= []
# list_2 = list()
# print ("list1 : {}".format(list_1))
# print ("list2 : {}".format(list_2))
#
# if list_1 == list_2:
# print ("equal")
# else:
# print ("not equal")
#
# print (list("welcome to the world of lists"))
#list is a constructor
# evenno = [2,4,6]
# anotherevenno = evenno
# print(anotherevenno is evenno)
# anotherevenno.sort(reverse=True)
# #below will print the same ,although we changed the different list,because
# #they are same
# print(evenno)
#
#
# evenno1= [2,4,6]
# anotherevenno1 = list(evenno1)
# print(anotherevenno1 is evenno1)
# print(anotherevenno1 == evenno1)
# anotherevenno.sort(reverse=True)
# #below will print different ,since they are 2 different list
# print(evenno1)
even1= [2,4,6,8,10]
odd1= [1,3,5,7,9]
allnos = [even1,odd1]
print(allnos)
for numberset in allnos:
print(numberset)
for val in numberset:
print(val)
Sunday, 4 February 2018
Started Python and Continued - Day1
# for i in [10]:
# print ("now the value of i is {}".format(i))
# i = 0
# while i <10:
# print ("now the value of i is {}".format(i))
# i = i+1
#
# #good example for while loop is below
# exitoptions = ["east","northeast"]
# youroption = ""
# while youroption not in exitoptions:
# youroption = input("please enter your exit direction \n")
# if youroption =="quit":
# print("game over")
# break
# else:
# print("aren't you glad that you are out from there")
# Guess number game using if
# import random
# highest = 10
# random = random.randint(1,highest)
# # print(random)
# answer = 1
# answer = int(input ("Guess any number between 1 and {} \n".format(highest)))
# if (answer==random):
# print("you guessed it corectly \n")
# elif (answer>random):
# answer = int(input("guess lesser no \n"))
# if (answer==random):
# print("you guessed it corectly \n")
# elif (answer<random):
# answer = int(input("guess higher no \n"))
# if (answer==random):
# print("you guessed it corectly \n")
# Guess number game using whileloop
import random
# highest = 10
# random = random.randint(1,highest)
# print(random)
# guessallowed = 5
# guesstime = 1
# guessedno = int(input("guess a no between 1 and {}\n".format(highest)))
# while guesstime <guessallowed and random!=guessedno:
# guessedno = int(input("guess one more time\n"))
# guesstime = guesstime + 1
# if (random == guessedno):
# print("you guessed it at {}- guess".format(guesstime))
# else:
# print("sorry")
Saturday, 3 February 2018
Power Of Consistency
IF YOU WANT TO BE TAKEN SERIOUSLY BE CONSISTENT
Subscribe to:
Posts (Atom)