Code Developed in CSCI-1010 Fall 2019

Lecture 3

Module: Calculator — Use Python as a Calculator

Code:

# -*- coding: utf-8 -*-
"""
Created on Tue Sep 10 09:31:32 2019

@author: mushtu
"""
print('Hello World!')
print('This is Python')

print(3+4)
print(5-4)
print(4*5)
type(10/5)

type(4)
type(4.0)

#Integer division: Quotient

print(11/3)
print(-11//3)

#Modulus Operator:Remainder
print(11%3)

##Expressions: PEMDAS
print(2+5-6)
#(F-32)*5/9
##Covert farenheit to celcius
print((45-32)*5/9)

print(2**3)

























Lecture 4

Module: Variables — Variables,Input and Expressions

Code:

# -*- coding: utf-8 -*-
"""
Created on Tue Sep 10 10:33:37 2019

@author: mushtu
"""

#Variables
#A=pi*r**2
pi=3.14159
alpha=1
Alpha=10

#Dynamic typing
Alpha=20

x=10
print(x)

#Assignment
x=x+10
x=10
#Alternate
x-=10
print(x)


#Find volume of a cylinder
r=float(input('Please enter the number for radius '))
h=float(input('Please enter the number for height '))
V=3.14*(r**2)*h
print(V)








# -*- coding: utf-8 -*-
"""
Created on Fri Sep 13 11:04:46 2019

@author: mushtu
"""
#Problem 1
name=input("What is your name? ")
print("Hello", name)

#Problem 2
name=input("What is your name? ")
age=int(input("How old are you? "))
year=2019+100-age
print(name, 'You will be 100 years old in the year',year)

##Problem 3
x=2
y=5
z=6
print('Average of the 3 numbers are', round((x+y+z)/3,2))

##Problem 4
x=int(input('Enter the first number '))
y=int(input('Enter the second number '))
#Part a
x!=y
#Part b
x==y

#Problem 5
name=input("What is your name?")
if (name=='Alice'or name=='Bob'):
    print("Hello", name)
else:
    print('Hello')
    
#Problem 6
n=int(input("Enter the number "))
b=input("Enter A for addition,M for Multiplication")
if (b=='A'):
    print('Result of addition is',n+(n-1))
elif (b=='M'):
    print('Result of multiplication is',n*(n-1))
else:
    print('Invalid input')
    
#Problem 7
n=int(input("Enter the number "))
if (n%2==0):
    print('This number is even')
else:
    print('This number is not even')

#Problem 8
n=int(input('Number of friends?'))
m=int(input('Number of chocolates in the packet?'))
if (m<n):
    print('Number of chocolates insufficient')
elif (m%n)==0:
    print('Each friend gets', int(m/n),'chocolates')
else:
    print('There is a surplus of ',m%n, 'chocolates')
    












Lecture 5

Module: Strings — String Manipulation

Code:

# -*- coding: utf-8 -*-
"""
Created on Mon Sep 16 12:02:35 2019

@author: mushtu
"""

"Rensselaer"
s='Rensselaer'
print(s)
'4 5 67 8'
'   '
type('xyz')
str(5)
#Functions in strings
len(s)
t='He said, "Hello World"'
print(t)
s1="C''''''''mon"
print(s1)

t= """This extends in
multiple lines"""

#Escape characters \
t= "This extends in \n multiple lines"
print(t)
u='column1\tcolumn2\tcolumn3'
print(u)
print('You can \\ do this')
print('\\')
##Accessing the elements: Indexing
s[0]
s[2]
s[9]
s[len(s)-1]
s[-1]
#Slicing [begin:stop:step]
s='Rensselaer'
s[1:5]
s
#Concatenation
'Hello '+'World'+'!'
s1='Hello'
s2='World'
s1+s2
'Hello''World'
print(s1+s2)
#Replication
'lol'*10
##Methods: variable.method(argument)
s='Good Morning'
s.find('o',3)
s.replace('o','@')
s
#More methods on output
t='Uzma Mushtaque'
t=t.lower()
t
t.upper()
t.title()
t.capitalize()
t.count('m','M')
##Print formatting
print('The value of variable'+'13'+'')
#.format method
x=12/11
y=13/7
print('The value of y is {0:.2f} and x is {1:.2f}'.format(x,y))





























Code:

# -*- coding: utf-8 -*-
"""
Created on Tue Sep 17 11:25:00 2019

@author: mushtu
"""

#Problem 1
#Method1
s='I am at work'
s=s.replace('k','@')
s=s.replace('I','k')
s=s.replace('@','I')
#Method 2
s='I am at work'
print(s[-1]+s[1:-1]+s[0])
#Problem 2
B='Hello World'
x=B[0]
if x in B[1:]:
    print('True')
else:
    print('False')
    
#Problem 3
str1=str(input("Input first string"))
str2=str(input("Input second string"))
if len(str1)!=len(str2):
    if len(str1)>len(str2):
        print(str1.replace(str2[-1],'$'))
    else:
        print(str2.replace(str1[-1],'$'))
else:
    print('Both are equal')



















Lecture 7

Module: Functions — Functions

Code:

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Jan 26 12:02:57 2019

@author: uzma
"""
##Define our first function
def getGroceries():
    print('milk')
    print('flour')
    print('sugar')
    print('butter')
    print()   #blank line
    
# Main code starts here
getGroceries()













##Modify
def getGroceries(item1):    # uses one parameter variable
    print(item1)  # prints the contents of the item1 variable
    print('flour')
    print('sugar')
    print('butter')
    print()
 
    
    
    
    
    
    
    
    
    
    
#Make it more generic
def getGroceries(item1, item2, item3, item4):
    print(item1)
    print(item2)
    print(item3)
    print(item4)
    print()
 
    
 
    
    
    
    
    
    
    
##Main code
# Now call the function with four arguments
getGroceries('eggs', 'soap', 'lettuce','cat food')
getGroceries('beer', 'milk', 'soda', 'peas')








##Addition function
def addTwo(startingValue):
    endingValue = startingValue + 2
    print('The sum of', startingValue, 'and 2 is:', endingValue)




# Call the function twice with different arguments
addTwo(5)
addTwo(10)











##Keywords

##Function to add two numbers
##Introducing keyword return
def sum_two_numbers(a, b):
    return a + b

##Keyword argv in python
def myFun(*argv):   
        print (argv) 


        
 






       
##Math class
import math

math.floor(15.25)
math.factorial(5)
math.exp(2)



##Strings class
s='Apple'
s.lower()
s.capitalize()
s.upper()





Lecture 8

Module: Functions — Functions

Code:

# -*- coding: utf-8 -*-
"""
Created on Fri Sep 27 10:35:22 2019

@author: mushtu
"""

def isright(a,b,c):
    if ((a**2)+(b**2))==(c**2):
        return True
    else:
        return False

print(isright(3,4,5))
print(isright(3,4,6))



Lecture 9

Module: Tuples — Tuples, Modules, Images

Code:

# -*- coding: utf-8 -*-
"""
Created on Fri Feb  8 13:11:02 2019

@author: mushtu
"""


# An empty tuple 
empty_tuple = () 
print (empty_tuple) 


# Creating non-empty tuples   
# One way of creation 
tup = 'python', 'rpics'
print(tup) 
  
# Another way for doing the same 
tup = ('python', 'rpics') 
print(tup) 


# Code for concatenating 2 tuples 
  
tuple1 = (0, 1, 2, 3) 
tuple2 = ('python', 'rpics') 
  
# Concatenating above two 
print(tuple1 + tuple2) 


# Creating nested tuples   
tuple1 = (0, 1, 2, 3) 
tuple2 = ('python', 'rpics') 
tuple3 = (tuple1, tuple2) 
print(tuple3) 



# Create a tuple with repetition 
  
tuple4 = ('rpics',)*3
print(tuple4) 



#code to test that tuples are immutable   
tuple1 = (0, 1, 2, 3) 
tuple4=(4,1,2,3)
tuple1[0] = 4
print(tuple1) 


# code to test slicing 
  
tuple1 = (0 ,1, 2, 3) 
print(tuple1[1:]) 
print(tuple1[::-1]) 
print(tuple1[2:4]) 



# Printing the length of a tuple   
tuple2 = ('python', 'rpics') 
print(len(tuple2)) 

#Some methods in tuples
tup1=('a','b','a')
tup1.count('a')
##index shows the first time index appears in the tuple
tup1.index('a')
tup1.index('b')
##Booloean output with in as keyword
'a' in tup1
1 in tup1










##Multiple assignments
t1=(1,2,3)
t1
a,b,c=t1
a
b
c






# Split a two-digit number into its tens and ones digit
def divprob(n):
    tens = n // 10 ##returns the quotient
    ones = n % 10 ##returns the remainder
    return (tens, ones)

y = 57
ten, one = divprob(y)
print(y, "has tens digit = ", ten, "and ones digit = ", one)









##Pass a tuple to a function
def hello(str1):
    return str1[0]+str1[2]+str1[3]

d=('h','e','l','l','o')
print(hello(d))















##Call module
import Area

r = 6
h = 10
a1 = Area.circle(r)        #  Call a module function
a2 = Area.cylinder(r, h)   #  Call a module function
a3 = Area.sphere(r)        #  Call a module function
a4= Area.cone(r,h)

#path to a module
import Area
Area.__file__


##Another way of calling a module
from Area import circle


















##Images
    
from PIL import Image
filename="Bloom.jpg"
im = Image.open(filename)
im.show()
im.size

print("Here's the information about", im)
print(im.format, im.size, im.mode)









##Crop
im2 = im.crop((0, 0, 600, 600))
im2.show()

##Rotate
im3=im.rotate(180)
im3.show()

##Convert to grayscale
gray_im = im.convert('L')
gray_im.show()
#Resize the image
scaled = gray_im.resize((128, 128))
#Check the attributes
print(scaled.format, scaled.size, scaled.mode)
#Show the new image
scaled.show()
##Save the new file
scaled.save(filename + "_scaled.jpg")













##Copy and paste
from PIL import Image
filename1="sheep.jfif"
im4 = Image.open(filename1)
im4.show()
im4.size






#New blank image
im5 = Image.new('RGB', (500, 375*2))
im5.show()
im5.paste( im4, (0,0))   ##not assigning the result of paste to a new variable
im5.show()
im5.paste( im4, (0, 380))
im5.show()













##Paste Images
from PIL import Image

im6 = Image.open("lego.jfif")
im6.show()
w,h = im6.size

## Crop out three columns from the image
## Note: the crop function returns a new image
part1 = im6.crop((0,0,w//3,h))
part2 = im6.crop((w//3,0,2*w//3,h))
part3 = im6.crop((2*w//3,0,w,h))

## Create a new image
newim = Image.new("RGB",(w,h))
newim.show()
## Paste the image in different order
## Note: the paste function changes the image it is applied to
newim.paste(part3, (0,0))
newim.paste(part1, (w//3,0))
newim.paste(part2, (2*w//3,0))
newim.show()
##Original image was:
im6.show()
# -*- coding: utf-8 -*-
"""
Created on Sat Feb  9 10:24:05 2019

@author: mushtu
"""

import math
#Area of a circle
def circle(radius):
    return math.pi * radius**2

#Area of cylinder
def cylinder(radius,height):
    circle_area = circle(radius)
    height_area = 2 * radius * math.pi * height
    return 2 * circle_area + height_area

#Area of sphere
def sphere(radius):
    return 4 * math.pi * radius**2

#Area of cone
def cone(radius, height):
    slant_area=math.pi*radius*(math.sqrt(height^2+radius^2))
    return circle(radius)+slant_area



Lecture 11

Module: Lists — Lists

Code:

# -*- coding: utf-8 -*-
"""
Created on Thu Feb 14 14:06:17 2019

@author: mushtu
"""
# Assign a list to an variable named new_list
new_list = [1,2,3]
##Assign different objects
new_list = ['New string',53,'z',200.324]
##Length of the list
len(new_list)
##List with same elements repeated
new_list=[1]*6
new_list


##Indexing and Slicing
new_list = ['one','two','three',4,5,6]
# Grab element at index 0
new_list[0]
# Grab index 1 and everything past it
new_list[1:]
# Grab everything UP TO index 3
new_list[:3]
##Indexing beyond len-1 will give error
new_list[7]
##Concatenate Lists
new_list + ['new object']
##Original List stays the same
new_list
##Can re-assign
new_list=new_list+['new element']
##Can multiply the list
new_list*3


##Methods
# Create a new list
ls1 = [5,1,2,4,3]
# Append
ls1.append('add me to list')
ls1
##Insert -- insert (at position, 'insert this')
ls1.insert(5,'insert this')
# Show
ls1
# Assign the popped element, 
#remember default popped index is -1
popped_item = ls1.pop()
popped_item
##Removing element-- what element you want to remove
ls1.remove(3)
ls1
##Reversing
mynew_list = ['a','m','x','b','c','f']
# Use reverse to reverse order (this is permanent!)
mynew_list.reverse()
mynew_list
##Sorting
# Use sort to sort the list (in this case alphabetical order,
# but for numbers it will go ascending)
mynew_list.sort()
mynew_list
ls1.sort()
ls1
List_of_Integers = [1,5,0,2,6,8,10]
List_of_Integers.append(12)
List_of_Integers
List_of_Integers.sort()
List_of_Integers.remove(0)
sorted(List_of_Integers)


##Nesting
# Let's make three lists
list1=[1,2,3]
list2=[4,5,6]
list3=[7,8,9]
# Make a list of lists to form a matrix
my_matrix = [list1,list2,list3]
my_matrix
# Grab first item in matrix object
my_matrix[0]
# Grab first item of the first item in the matrix object
my_matrix[2][0]














##Built in functions
test_list=[1.6,2.5,3.8,4.1]
sum(test_list)
##Compare
lst1=[1,2,3,4]
lst2=[2,3]
max(lst1)
max(lst2)
min(lst1)
len(lst2)

Lecture 12

Module: Lists — In Lecture Problems

Code:

# -*- coding: utf-8 -*-
"""
Created on Tue Oct 15 11:26:41 2019

@author: mushtu
"""
#Problem 1
def first_last6(x):
    if x[0]==6 or x[-1]==6:
        return True
    return False

print(first_last6([6,2,8]))

#Problem 2
def common_end(x,y):
    if x[0]==y[0] or x[-1]==y[-1]:
        return True
    return False

print(common_end([6,2,8],[1,8]))

#Problem 3
def big_diff(x):
    x=sorted(x)
    return x[-1]-x[0]

print(big_diff([6,0,3,10]))

#Problem 4
def rotate_left3(x):
    a=x[0]
    b=x[1]
    c=x[2]
    return [b,c,a]

print(rotate_left3([3,4,5]))





Lecture 13

Module: Lists and Strings — Methods

Code:

# -*- coding: utf-8 -*-
"""
Created on Thu Oct 17 14:49:06 2019

@author: mushtu
"""
#Strip
x = "blue! Sky is blue! Sky is blue! Sky is blue!"
#strip method
x.strip('lbue!')
print(x)
x.lstrip('blue!')
x.rstrip('blue')
x='\n    Hello World    \t'
x.strip(" ")
#Split
y='Hello|World|Hello|Python'
y.split("l")
#Find method
x = "blue! Sky is blue! Sky is blue! Sky is blue!"
x.find('Sky',7,15)
##converting strings to list
s='Hello'
s=list(s)
str(s)
#.join method
''.join(s)
l=['Hello','Python','RPI']
' '.join(l)
# -*- coding: utf-8 -*-
"""
Created on Thu Oct 17 19:46:58 2019

@author: mushtu
"""

#problem 1
def same_first_last(x):
    if len(x)>1:
        if x[0]==x[-1]:
            return True
    return False

print(same_first_last([1,2,3,1]))

#problem 3
def max_end3(l):
    s=max(l[0],l[-1])
    return [s]*len(l)

print(max_end3([1,2,4,3]))

#problem 4
def middle_way(a,b):
    return [a[1],b[1]]

print(middle_way([1,2,3],[4,5,6]))

#Problem 5
X = [[1,2,3],[4 ,5,6], [7 ,8,9]] 
Y = [[9,8,7],[6,5,4],[3,2,1]] 
print([X[0][0]+Y[0][0],X[0][1]+Y[1][0],X[0][2]+Y[2][0]])

#Problem 6
sub_list=[1,10]
List=[1,2,3,4]
sub_list[0] in List

#Problem 7
List=[20,5,4,21]
Value=22
max(List)>=Value
List=[35,42,68,10]
Value = 68 



Lecture 14

Module: Loops — While Loop

Code:

# -*- coding: utf-8 -*-
"""
Created on Wed Feb 20 12:17:59 2019

@author: mushtu
"""
#Initialization of a counter variable
count = 0
#Specify Condition
while (count < 5): 
##Do something: Action
    print("Hello World") 
#Increment the counter
    count = count + 1

    
 ##Another example with else
y = 0
while y < 10:
    print('y is currently: ',y)
    print(' y is still less than 10, adding 1 to y')
#Alternate method of incrementing
    y+=1    
else:
    print('All Done!')  

    
##Bacteria Growth Rate
#Initialization
time=0
#Given
population = 1000
growth_rate= 0.21
while population < 2000:
    population = population + growth_rate*population
    print(population)
    time=time+1
print('For the population to double it takes ',time, 'minutes')
print('Final population is ', population)


##Continue statement
y = 0
while y < 5:
    print('y is currently: ',y)
    print(' y is still less than 5, adding 1 to y')
    y+=1
    if y==3:
        print('y==3')
    else:
        print('continuing...')
        continue    

    
##Break statement    
y = 0
while y < 5:
    print('y is currently: ',y)
    print(' y is still less than 5, adding 1 to y')
    y+=1
    if y==3:
        print('Breaking because y==3')
        break
    else:
        print('continuing...')
        continue    
       

##More examples
##Problem 1a
count=0
while True:
    count+=1
    if count>5:
        break
    print (count)
    


##Problem 1b    
count=0 
while count<10:
    count+=1
    if count%2 ==0:
        continue
    print (count)

##Census
census = [ 340, 589, 959, 1372, 1918, 2428, 3097, 3880, 4382, 5082, \
               5997, 7268, 9113, 10385, 12588, 13479, 14830, 16782, \
               8236, 17558, 17990, 18976, 19378 ]
sum_change = 0
i = 1
while i<len(census):
    pct = (census[i] - census[i-1]) / census[i-1] * 100
    sum_change += pct
    i += 1
print("Average = {:.1f}%".format( sum_change/(len(census)-1))) 


##Nested While
L = [2, 21, 12, 8, 5, 31]
i = 0
while i < len(L):
    j = 0
    while j < len(L):
        print(L[i], L[j])
        j += 1
    i += 1




##Problem 1
l=[1,2,3,4,5,6,7,8,9,10,13,17]
i=0
even=0
odd=0
while i<len(l):
    if l[i] %2==0:
        even+=1
    else:
        odd+=1
    i+=1
print ('Even = ', even)
print ('Odd = ', odd)

##Problem 2
n1=[]
x=1500
while x in range(1500,2700):
    if (x%7==0) and (x%5==0):
        n1.append(str(x))
    x+=1
print (n1)





##Prime or not
num = 12 
# If given number is greater than 1 
if num > 1: 
#Initialize
   i=2      
   # Condition:Iterate from 2 to n / 2  
   while i <= num//2:          
       # If num is divisible by any number between  
       # 2 and n / 2, it is not prime  
       if (num % i) == 0: 
           print(num, "is not a prime number") 
           break
       else:
#Increment
           i+=1
   else: 
       print(num, "is a prime number") 
else: 
   print(num, "is not a prime number") 


##Demonstrate end
print('My ')
print('Name ')
print('My ', end="")
print('Name ', end="")



##The star problem
##First Half
i=0
while i<5:
    j=0
    while j<=i:
      j+=1
##Don't let the line end until all stars printed
      print ('* ', end="")
    i+=1
    print('')  
       
    
#Second Half
i=i-1
while i>0:
    j=0
    while j<i:
        print ('* ', end="")
        j+=1
    i-=1
    print('')





















Lecture 15

Module: Loops — For Loop

Code:

# -*- coding: utf-8 -*-
"""
Created on Tue Oct 29 10:04:35 2019

@author: mushtu
"""

for i in range(10):
    print(i)
    
values=['a','b','c']
for i in range(len(values)):
    print(i,values[i])
    
for j in values:
    print(j)
    
values=[100,200,300]
for i in range(len(values)):
    values[i]=values[i]*2
#    print(i)
print(values)

for v in enumerate(values):
    i=v[0]
    values[i]=v[1]*2
print(values)
 
samplstr='Hello world'
for v in samplstr[::2]:
    print(v)
    
for x in range(2000, 2050, 4):
       print(x, end=" ") 

#Nested Lopps
        
fruits=['apple','mango','durian','kiwi']
adj=['red','orange','green','brown']

for i in range(len(adj)):
    for j in range(len(fruits)):
        if i==j:
            print(adj[i],fruits[j])
            
L=[['first',1,2,3],['second',3,4,5,0],['third',6,7]]
final=[]
for i in L:
    name=i[0]
    avg=sum(i[1:])/(len(i)-1)
    final.append([name,avg])
print(final)

[['first',2.0],['second',3.0],['third',6.5]]

#facorial problem
def factorial(n):
    final=1
    for i in range(n,0,-1):
        final=final*i
    return final

print(factorial(5))

#sequence problem
def count(sequence,item):
    total=0
    for i in sequence:
        if i ==item:
            total+=1
    return total

print(count([1,1,2,3],2))

#starproblem
n=5
for i in range(n):
    for j in range(i):
        print('*',end=' ')
    print()
    
    
for i in range(n,0,-1):
    for j in range(i):
        print('*', end= ' ')
    print()

#fibonacci
fib=[0,1]
n=10
for i in range(2,n+1):
    x=fib[i-1]+fib[i-2]
    fib.append(x)
print(fib)
    

































        




























   
    
    
    
    
    
    
    
    

Lecture 16

Module: Loops — For Loop Problems

Code:

# -*- coding: utf-8 -*-
"""
Created on Fri Nov  1 10:01:26 2019

@author: mushtu
"""

#10 is the number to print
for num in range(4):
    for i in range(num):
        print(num,end=" ")
    print()
    
#Substring problem
    
def fun1(str1,sub):
    if sub in str1:
        return True
    return False

str1='Hello World'
sub='ell'

print(fun1(str1,sub))

##Problem 1b
l1=[' a','b','c','d','r']
s1='c1tdoorrbin'
count=0
for i in range(len(l1)):
    if l1[i] in s1:
        count+=1
print(count)

#Problem 3    
word='abcdef'
for char in range(len(word)-1,-1,-1):
    print(word[char],end='')
    
#Problem 4
count=0
string1 ='catdogelephantdogeleph'
sub = 'eleph'
sub_len=len(sub)
for i in range(len(string1)):
    if string1[i:i+sub_len]==sub:
        count+=1
print(count)
    
#Problem 5
def has22(a):
    for i in range(len(a)):
        if a[i]!=2:
            continue
        elif a[i]==2 and (len(a)-i)>1:
            if a[i+1]==2:
                return True
    return False
print(has22([1,3,0,0,2]))

#Problem 6
def end_others(a,b):
    a=a.lower()
    b=b.lower()
    if len(a)>=len(b):
        if a.endswith(b):
            return True
        return False
    else:
        if b.endswith(a):
            return True
        return False
    
end_others('Hiabc', 'abc')

#Problem 8
s=input('Enter the string ')        
d=0
l=0
for i in s:
    if i.isdigit():
        d+=1
    elif i.isalpha():
        l+=1

print("Letters",l)
print("Digits",d)
        
        
        
        
        
        
        

















Lecture 17

Module: Files — text files

Code:

# -*- coding: utf-8 -*-
"""
Created on Fri Nov  8 11:08:43 2019

@author: mushtu
"""
'''Working with .txt files in Python'''
#Reading files
my_file=open('Test.txt','r')
my_file.read()
my_file.seek(0)
my_file.readline()
my_file.readlines()
my_file.close()

#Writing into files
final_file=open('Newoutfile.txt','w')
final_file.write('My name is Uzma')
final_file.close()

##Parsing files code
f=open('abc.txt')
for line in f:
    print(line)
    
#OR
for line in open('abc.txt'):
    print(line)

'''The grades problem'''

file_name=input('Enter the name of the file')
file_name=file_name.strip()
print(file_name)
count=0
sum_grade=0
for s in open(file_name):
    sum_grade+= int(s)
    count+=1
print('Average grade is ', sum_grade/count)


'''This code shows 3 different variations of working with the yelp.txt file'''
#Get all the data into Python
yelp_file=input('Please enter the yelp data file==>').strip()
yelp_data=[]
for line in open(yelp_file,encoding="utf-8"):
    words=line.strip().split('|')
    yelp_data.append(words)
print(yelp_data)
    

#Get names of restaurants
yelp_file=input('Please enter the yelp data file==>').strip()
names_list=[]
for line in open(yelp_file,encoding="utf-8"):
    words=line.strip().split('|')
    name=words[0].strip()
    names_list.append(name)
print(names_list)

#Names and averages
def yelp_averages(yelp_file):
    averages=[]
    for line in open(yelp_file):
        words=line.strip().split('|')
        name=words[0].strip()
        scores=words[6:]
        if len(scores)==0:
            averages.append([name,-1])
        else:
            sum_scores=0
        for s in scores:
            sum_scores+=int(s)
        avg=round(sum_scores/len(scores),2)
        averages.append([name,avg])
    return averages

file=input('Please enter the yelp data file==>').strip()
print(yelp_averages(file))

Lecture 18

Module: Problem Solving — Problem solving and design

Code:

# -*- coding: utf-8 -*-
"""
Created on Sun Apr 21 18:01:19 2019

@author: mushtu
"""
##Find the minimum first and then its index
ls= [809,834,477,478,307,122,96,102,324,476]
#min(ls) 
low = min(ls)
min_index = ls.index(low)
print (min_index) 


##Find Remove Find
def find_two_smallest(L): 
    'Return a tuple of the indices of the two smallest values in list L.'
    smallest = min(L) 
    min1 = L.index(smallest) 
    L.remove(smallest) 
    next_smallest = min(L) 
    min2 = L.index(next_smallest)
##Insert at index min1     
    L.insert(min1, smallest) 
    if min1 <= min2: 
        min2 += 1
    return (min1, min2)

L=[809,834,477,478,307,122,96,102,324,476]
find_two_smallest(L)



##Sort, Identify Mins, Get Indices
def find_two_smallest(L):
    temp_list = L[:] 
    temp_list.sort() 
    smallest = temp_list[0] 
    next_smallest = temp_list[1] 
    min1 = L.index(smallest) 
    min2 = L.index(next_smallest) 
    return (min1, min2)
find_two_smallest(L)


#Walk through the List
def find_two_smallest(L): 
# set min1 and min2 to the indices of the smallest and next-smallest 
# values at the beginning of L 
    if L[0] < L[1]: 
        min1, min2 = 0, 1 
    else: 
        min2, min1 = 1, 0
# examine each value in the list in order 
    for i in range(2, len(L)):
        if L[i] < L[min1]: 
            min2 = min1 
            min1 = i
# New second smallest? 
        elif L[i] < L[min2]: 
            min2 = i
    return (min1, min2)
find_two_smallest(L)

Lecture 19

Module: List Comprehensions — List generation

Code:

# -*- coding: utf-8 -*-
"""
Created on Fri Nov 15 10:00:20 2019

@author: mushtu
"""

h_letters = [ letter for letter in 'human' ]
print(h_letters)
#Problem 1
wood='How much wood would a woodchuck chuck if a woodchuck could chuck wood?'
wood=wood.split()
woolist=[]
for x in wood:
    if 'woo' in x:
        woolist.append(x)
print(woolist)

#method 2
[x for x in wood if 'woo' in x]
#Generate evem numbers
[ x for x in range(20) if x % 2 == 0]
#Problem 2
[x for x in wood if len(x) >=5]
#Problem 3
[x.upper() for x in wood if 'wo' in x]
#Problem 4
[x+'-away' for x in wood if len(x)<=4]
#Problem 5
[(x, len(x)) for x in wood if len(x)>=5]
#problem 6
lista=[1,2,3,4,5]
listb=[3,4,5,6,7]
common_num=[]
for a in lista:
    for b in listb:
        if a==b:
            common_num.append(a)
print(common_num)
#Method 2
common_num=[a for a in lista for b in listb if a==b]
print(common_num)
            















Lecture 20

Module: Sets — Set Methods and Operations

Code:

# -*- coding: utf-8 -*-
"""
Created on Mon Nov 18 22:05:52 2019

@author: mushtu
"""
set1=set()
set2={3,8,0,4,'Hello',3.7}
dir(set2)
#Methods
set2.add(10)
print(set2)
help(set2.add)
set1.add(6)
print(set1)
#Remove
set2.remove(8)
print(set2)
set2.remove(100)
if 100 in set2:
    set2.remove(100)

help(set2.discard)
set2.discard(4)     
set1.add(3)   
print(set1)    
set1.clear()    
#Functions on sets
set3={3,5,6,7,1,0}
#Cardinality of a set
len(set3)
#Cpnvert other object types to sets
v1=[4,5,6,4,1,2,6,8,0,1]
len(v1)
set4=set(v1)
len(set4)
print(set4)
set5={9,3,6,1,0,8}
sorted(set5)
#Set Operations
s1={2,3,4,5,6}
s2={4,5,6,8,0,1}
#Difference
s1-s2
s1.difference(s2)
s2.difference(s1)
#Union
s1.union(s2)
s1|s2
#Intersection
s1.intersection(s2)
s1 & s2
#Symmetric difference
s1.symmetric_difference(s2)
s1^s2
s3={0,1}
s2.issuperset(s3)
s2>=s3
s3.issubset(s2)
s3<=s2
#True copy or deep copy
first={'a','b','c','d'}
second=first.copy()
print(second)
second.remove('d')
print(first)
#Alias or a shallow copy
#Different names but pointing to the same object
third=first
print(third)
third.remove('d')
print(first)
#Explore .update() and .intersection_update() methods
































    
    
    
    
    
    
    
    
    
    
# -*- coding: utf-8 -*-
"""
Created on Tue Nov 19 10:48:29 2019

@author: mushtu
"""

Customer=input('Enter the name of the file==>').strip()
print(Customer)
'''Question 1: How many (which) unique customers are there?
   Solution 1: List Based'''
   
Id_list=[]
for line in open(Customer):
    words=line.strip().split('|')
    Id=words[0].strip()
    if Id not in Id_list:
        Id_list.append(Id)
print('Number of unique customers',len(Id_list))

'''Solution 2: Sets based'''

Id_set=set()
for line in open(Customer):
    words=line.strip().split('|')
    Id=words[0].strip()
    Id_set.add(Id)
print('Number of unique customers',len(Id_set))


'''Create sets of customers that bought from a given category'''
Electronics=set()
Furniture=set()
Kitchen=set()
for line in open(Customer):
    words=line.strip().split('|')
    Id=words[0].strip()
    category=words[2].strip()
    if category=='Electronics':
        Electronics.add(Id)
    elif category=='Furniture':
        Furniture.add(Id)
    else:
        Kitchen.add(Id)
        
print(Electronics)
print(Furniture)
print(Kitchen)
'''How many customers bought from both Electronics and Kitchen'''
len(Electronics & Kitchen)
'''How many bought from all 3 categories'''
len(Electronics & Kitchen & Furniture)
'''Did all people who bought from Kitchen also bought from furniture?'''
Kitchen <= Furniture
'''How many people bought from Kitchen or Electronics'''
len(Kitchen|Electronics)
'''How many people bought from Electronics and Furniture'''
len(Electronics & Furniture)
'''How many people bought from Electronics but not from Furniture'''
len(Electronics-Furniture)
'''How many people bought from Furniture or Kitchen but not from both'''
len(Furniture^Kitchen)
'''How many customers bought from at most 2 categories'''
len(Furniture^Kitchen^Electronics)
'''How many customers bought from at most 1 category'''
(Furniture^Kitchen^Electronics-(Electronics & Kitchen & Furniture))






    
    




Lecture 21

Module: Sets — Set Methods and Operations

# -*- coding: utf-8 -*-
"""
Created on Thu Nov 21 13:38:12 2019

@author: mushtu
"""

s1={3,4,5,6}
s1.update({7,8,9})
s1
s2={9,10,11}
s1|s2
s3={8,9,10,11,12,13}
s1.intersection_update(s3)
s3
s3.remove(16)
s3.discard(15)
#Problem 1
vowels={'a','e','i','o','u'}
s='Happy Thanksgiving'
s=list(s)
count=0
for i in s:
    if i in vowels:
        count+=1
print(count)
    
s='Happy Thanksgiving'  
t='Happy Birthday' 
s=s.lower()
s=s.replace(" ",'')
t=t.lower()
t=t.replace(" ",'')
s=set(s)
t=set(t)    
s & t  
s ^ t
#Problem 6
L=[1,3,4,4,4,2,2,2,3,3]    
L=set(L)    
print(sum(L)/len(L))
  
E= {1,2,3,9,10,11,12}
F= {4,5,6,8,9,10,11,12,13}
E|F   
male_names = { 'John', 'Bailey', 'Charlie', 'Chuck', 'Michael', 'Samuel', 'Jayden', 'Aiden', 'Henry', 'Lucas' }
female_names = { 'Elizabeth', 'Meghan', 'Kim', 'Khloe', 'Bailey', 'Jayden', 'Aiden', 'Britney', 'Veronica', 'Maria' }
male_names|female_names    
neutral_names=male_names&female_names 
specific_names=male_names^female_names 
 

s={3,5,6}   
s[1]
for i in s:
    print(i)    

Lecture 22

Module: Dictionaries — Creating Dictionaries,Methods on Dictionaries

Code:

# -*- coding: utf-8 -*-
"""
Created on Tue Nov 26 09:42:06 2019

@author: mushtu
"""

children=dict()
children={}
children['Sam']=12
children['Peter']=11
children['Alice']=9
children['Jon']=13
print(children)
len(children)
New={'Hello':'Yes','World':'No'}
print(New)
'''Keys can be strings and Numbers(integers)'''
'''Access the elements'''
'Sam' in children # Key in dictionary
'Luke' in children
'''Output values in the dictionary'''
children['Sam']
list(children.keys())
list(children.values())
sorted(children.keys())
print(children['Alice'])
'''Values can be any object type in Python'''
Students=dict()
Students['Sam']=set()
print(Students)
Students['Sam'].add(12)
Students['Sam'].add('NY')
Students['Alice']=[]
Students['Alice'].append(13)
Students['Alice'].extend(['NY',12180])
Students['Jon']=12
Students['Jon']+=5
'''Methods in Dictionaries'''
children.get('Jake','Not Found')
children.pop('Sam')
children['Sam']=12
children.update(Luke=15)
children.update({'Dan':10,'Val':13})
del(children['Val'])
'''example : create dictionaries using lists'''
Names=['Sam','Alice','Jon']
Info=[[12,'NY'],[13,'PA'],[9,'DE']]
dict1=dict()
for i in range(len(Names)):
    dict1[Names[i]]=Info[i][0]
print(dict1)




















# -*- coding: utf-8 -*-
"""
Created on Tue Nov 26 10:57:38 2019

@author: mushtu
"""
'''Find the number of items in each category'''
Customer=input('Enter the name of the file').strip()
print(Customer)

'''List based solution: [[Electronics,11]]'''
Count_lists=[]
for line in open(Customer,encoding="utf-8"):
    words=line.strip().split('|')
    name=words[2].strip()
    found=False
    for pair in Count_lists:
        if pair[0]==name:
            pair[1]+=1
            found=True
            break   
    if not found:
        new_pair=[name,1]
        Count_lists.append(new_pair)
        
print(Count_lists)      
'''Dictionary based solution'''
counts=dict()
for line in open(Customer,encoding="utf-8"):
    words=line.strip().split('|')
    name=words[2].strip()
    if name in counts:
        counts[name]+=1
    else:
        counts[name]=1
        
print(counts)










Lecture 23

Module: Dictionaries — Iterating over and nesting Dictionaries,Key-Value conversion

Code:

# -*- coding: utf-8 -*-
"""
Created on Tue Dec  3 08:02:47 2019

@author: mushtu
"""
list1=['a','b','c']
dict1={0:'a',1:'b',2:'c'}
#Access the elements
list1[2]
dict1[2]
#Add elements
list1[0]='z'
dict1[0]='z'
list1[10]='x'
dict1[10]='x'
dict1[1]
#Looping over dictionaies
students=dict()
students['Sam']=3.5
students['Alice']=3.8
students['Jon']=3.6
students['Luke']=3.3
print(students)
#keys is the default
for i in students:
    print(students[i])
    
for j in students.keys():
    print(j)
    
for k in students.values():
    print(k)

for x in students.items():
    print(x)

'''Aliasing: Shallow copy and Copying: Deep Copy'''

d=dict()
d[15]='hi'
L=[]
d[20]='bye'
L.append(d)
L.append(d.copy())
d[15]='World'
print(L)
del d[20]
print(L)
'''Keys can be anything hashable: strings,integers,floats,
   boolean,tuples.'''
   
#Problem 1
d1 = {'a': 100, 'b': 200}
d2 = {'x': 300, 'y': 200}
d1.update(d2)   

d3={'a':100,'b':20, 'c':50} 
   
sum(list(d3.values()))
   
   
   
   
   
   
   








Houses= { "House1": {
        "id": "01",
        "address": "XYZ Street 12180 Troy NY",
        "Bedrooms": 2,
        "Pool": "No",
        "Style": "Ranch",
        "Price": 120000
},
         "House2": {
                 "id": "02",
                 "address": "ABC Street 12180 Troy NY",
                 "Bedrooms": 3,
                 "Pool": "No",
                 "Style": "Colonial",
                 "Price": 150000
         },
         "House3": {
                 "id": "03",
                 "address": "ABCD Street 12180 Troy NY",
                 "Bedrooms": 5,
                 "Pool": "Above G",
                 "Style": "Colonial",
                 "Price": 200000
         }  ,
         "House4": {
                 "id": "04",
                 "address": "ABC1 Street 12180 Troy NY",
                 "Bedrooms": 5,
                 "Pool": "No",
                 "Style": "Colonial",
                 "Price": 320000
         },
         "House5": {
                 "id": "04",
                 "address": "ABCXYZ Street 12180 Troy NY",
                 "Bedrooms": 4,
                 "Pool": "Below G",
                 "Style": "Colonial",
                 "Price": 320000
         }         
                    
    }
         
# -*- coding: utf-8 -*-
"""
Created on Tue Dec  3 10:55:07 2019

@author: mushtu
"""
imdb_file=input('Enter the file name').strip()
print(imdb_file)
'''Create a dictionary with key as actor names and
   movies as sets'''
movies=dict()
for line in open(imdb_file,encoding='utf-8'):
    words=line.strip().split('|')
    name=words[0].strip()
    movie=words[1].strip()
    if name in movies:
        movies[name].add(movie)
    else:
        movies[name]=set()
        movies[name].add(movie)
        
print(movies)

'''How many actors appeared in a single movie
   Who is the busiest actor'''
   
singlets=0
most=0
for name in movies:
    movie_ct=len(movies[name])
    if movie_ct==1:
        singlets+=1
    if movie_ct > most:
        most=movie_ct
        person=name

print("{} appears most often : {} times".format(person,most))
print("{} people appeared once".format(singlets))
    
   
   
   
   
   
   
   
   
   


        
    
# -*- coding: utf-8 -*-
"""
Created on Mon Dec  2 14:26:32 2019

@author: mushtu
"""
'''Problem: Convert keys to values and values to keys'''
states = {'New Hampshire': ['Concord', 'Hanover'],\
          'Massachusetts': ['Boston', 'Concord', 'Springfield'],\
          'Illinois': ['Chicago', 'Springfield', 'Peoria']}

'''
Create this dictionary using states as input
cities = {'Hanover': ['New Hampshire'], 
          'Chicago': ['Illinois'],\
          'Boston': ['Massachusetts'], 'Peoria': ['Illinois'],\
          'Concord': ['New Hampshire', 'Massachusetts'],\
          'Springfield': ['Massachusetts', 'Illinois']}'''

cities=dict()
for i in states:
    for c in states[i]:
        if c in cities:
            cities[c].append(i)
        else:
            cities[c]=[i]
        
print(cities)        
        
''' output in lexicographical(alphabetical) order'''  
sorted(cities)[:4]
sorted(states)
'''Find 4 unique cities and output in 
lexicographical(alphabetical) order'''
for c in sorted(cities):
    if len(cities[c])==1:
        print(c)





  

Lecture 24

Module: Dictionaries — In Class Problems

Code:

# -*- coding: utf-8 -*-
"""
Created on Fri Dec  6 07:56:04 2019

@author: mushtu
"""

dic1={1:10, 2:20}
dic2={3:30, 4:40}
dic3={5:50,6:60}
d=dict()
for i in (dic1,dic2,dic3):
    d.update(i)
print(d)

'''Problem 2: Unique means - anhkt'''
def unique(s):
    dict1=dict()
    for i in s:
        if i not in dict1:
            dict1[i]=1
        else:
            dict1[i]+=1
    flag=True
    for j in dict1:
        if dict1[j]!=1:
            flag=False
            break
    return flag

 
unique('asdfghj')           
            
'''Problem 3'''  
my_dict = {'data1':100,'data2':-54,'data3':247}
result=1
for key in my_dict:
    result=result*my_dict[key]
print(result)
    
'''Problem 4'''
d={'a':12,'d':10,'p':8}
sorted(d.keys())
#Problem 5

rest_reviews = {"DeFazio's":["Great pizza", "Best in upstate"], \
"I Love NY Pizza":["Great delivery service"], \
"Greasy Cheese": [ "Awful stuff", "Everything was terrible" ] }
#set(['awful' , 'terrible', 'dump'])

for key in rest_reviews:
    num=0
    for phrase in rest_reviews[key]:
        s=set(phrase.lower().split()) & set(['awful' , 'terrible', 'dump'])
    if len(s)>0:
        num+=1
    if num>0:
        print(key,num)
        
#Part b
max_reviews = 0
for name in rest_reviews.keys():
    if len(rest_reviews[name]) > max_reviews:
        max_reviews = len(rest_reviews[name])
for name in rest_reviews.keys():
    if len(rest_reviews[name]) == max_reviews:
        print(name)

#Problem 6
hobby = {'Green': set (['Gardening', 'Hiking']),\
                     'Elan': set (['Hiking','Board Games'])}

name=set()
for i in hobby.values():
    name=name|i
print(name)  
f_hobby=list(name)   
d1=dict()
for i in range(len(f_hobby)):
    d2=set()
    if f_hobby[i] not in d1:
        d1[f_hobby[i]]=d2
    for key, value in hobby.items():
        if f_hobby[i]in value:
            d2.add(key)
print(d1)