Advertisement
Guest User

CS1026 - Lab Solutions

a guest
Dec 15th, 2015
360
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 12.79 KB | None | 0 0
  1. # Lab 1:
  2. # Task 1  
  3. # TODO: type solution here
  4. print("I am learning Python")
  5.  
  6. # Task 2
  7. # TODO: type solution here
  8. answer = 3 + 5
  9. print(answer)
  10.  
  11. # Task 3
  12. # TODO: type solution here
  13. print("My first python code")
  14. variable1 = 46*2
  15. variable2 = 3+5
  16.  
  17. print(variable1)
  18. print(variable2)
  19.  
  20. print("everything works")
  21.  
  22. # Lab 2:
  23. # Task 1
  24. # TODO: type solution here
  25. x=7
  26. print(x+5)
  27. print((x+5)*3)
  28. print(x+5*3)
  29. # why are the last two different?
  30. # because of order of operations
  31. #add your own!
  32.  
  33. # Task 2
  34. # TODO: type solution here
  35. print(2<5)
  36. print(2<=2)
  37. print(2!=5)
  38. print(2==2)# 2 equals signs checks equality of something one equals sign is an assignment operator
  39. #try printing 2=2
  40. #delete the #   to uncomment and test it
  41. #print(2=2)
  42. #add your own!
  43.  
  44. print(5>2)
  45.  
  46. # Task 3
  47. # TODO: type solution here
  48. print("CS" + "1026")
  49. print("CS" + " "+ "1026")
  50. print("CS "+"1026")
  51. #notice the space differences
  52. #add your own!
  53.  
  54. print("hi " + "there")
  55.  
  56. # Task 4
  57. # TODO: type solution here
  58. #lets try some simple formatting
  59. name= "Sterling Archer"
  60. age = 36
  61.  
  62. #two ways of formatting strings
  63. # the first is called interpolation in this case %s represents a string and is the first element
  64. # %d represents an integer and is the second element in the list
  65. print("%s %d" % (name, age))
  66. # the second calls a format function it replaces the {} with the variables in the format function in order
  67.  
  68. print("{} {}".format(name,age))
  69. #add your own!
  70.  
  71.  
  72. day = "Friday"
  73. month = "November"
  74. year = 2015
  75.  
  76. print("{}, {}, {}".format(day, month, year))
  77.  
  78. # Task 5
  79. # TODO: type solution here
  80. x =7
  81. print(x)
  82. y =x+5
  83. print("x is {} and y is {}".format(x,y))
  84. x=x+5
  85. #note the value changes when we do the statement above
  86. print("x is now {}".format(x))
  87. y= x+5
  88. # if we repeat the second print what will we get?
  89. print("x is {} and y is {}".format(x,y))
  90. #add your own!
  91.  
  92. a = 10
  93. b = a + 5
  94. print("a is {} and b is {}".format(a, b))
  95.  
  96. a = a + 10
  97. b = a + 5
  98.  
  99. print("a is {} and b is {}".format(a, b))
  100.  
  101. # Task 6
  102. # TODO: type solution here
  103. #we assign some variables and check an expression note how we checked the expression with format
  104. x = -1
  105. y =0
  106. print("is it true that x<= y?")
  107. print("It's {} !".format((x<=y)))
  108.  
  109. a= 2.5
  110. b=5
  111. # notice how these two print statements give different results why is that?
  112. print(a*b)
  113. print(int(a *b))
  114.  
  115. print("She said, hey there")
  116. #note how you can use escape sequences to format your strings as well
  117. print("She said,\n hey there")
  118. #add your own!
  119.  
  120. c = 3.3
  121. d = 2
  122. print("The answer is \n{}".format(int(c * d)))
  123.  
  124. # Task 7
  125. # TODO: type solution here
  126. #note how to get input from the keyboard
  127. celsius = float(input("Please type the Celsius value in"))
  128. # notice how we had to cast celsius to float try removing the float cast and seeing what happens
  129.  
  130. #note 1.8 is 9/5
  131. #fDegrees stores the Fahrenheit value
  132. fDegrees= (celsius * 1.8 )+ 32
  133. print(fDegrees)
  134. # when you take a value from input it is a string value by default therefore you must convert it to whatever
  135. # other value you may use if need be
  136.  
  137. # Task 8
  138. # TODO: type solution here
  139. fahrenheit = float(input("Please enter the temperature in fahrenheit - "))
  140.  
  141. celsius = (fahrenheit - 32) * 5/9
  142.  
  143. print(celsius)
  144.  
  145. # Lab 3:
  146. # Task 1
  147. # TODO: type solution here
  148. x=5
  149.  
  150. #is x > 5?
  151.  
  152. if x > 5:
  153.     print("X is larger than 5")
  154. else:
  155.     print("X is smaller than or equal to 5")
  156.  
  157. # Task 2
  158. # TODO: type solution here
  159. a=12
  160. b=7
  161. t =True
  162. c='e'
  163.  
  164. print((a > 0) ==  (b > 0))
  165.  
  166. print(('a' > c)  != ('E' != c))
  167.  
  168. print((a % b != 0) and (b * 2 > a))
  169.  
  170. print((t or not(a > b)) and t)
  171.  
  172. # Task 3
  173. # TODO: type solution here
  174. from datetime import datetime
  175. hour = datetime.now().hour
  176.  
  177. if hour == 12:
  178.     timeOfDay = "Morning"
  179. elif hour > 12 and hour <= 18:
  180.     timeOfDay = "Afternoon"
  181. else:
  182.     timeOfDay = " Evening"
  183.  
  184. print("Good {}, world".format(timeOfDay))
  185.  
  186. # Lab 4:
  187. # Task 1
  188. # TODO: type solution here
  189. count = 1
  190. while count <= 10:
  191.     print(count)
  192.     count = count + 1
  193.     #two statements in the loop
  194.  
  195. # Task 2
  196. # TODO: type solution here
  197. #place your code here
  198. for i in range (1, 11, 2):
  199.     print(i)
  200.  
  201. # Task 3
  202. # TODO: type solution here
  203. #place outer loop here
  204. for i in range (5):
  205.     for x in range(1,11):
  206.         print(x)
  207.  
  208. # Task 4 *May not be right*
  209. # TODO: type solution here
  210. from random import randint
  211. name = input("please enter your name")
  212.  
  213. # place your code here
  214. i = 0
  215. while i in range (20):
  216.     print("test")
  217.     i = i + 1
  218.     if i % 2:
  219.         rando = randint(1,10)
  220.         print(rando)
  221.     if i % 3:
  222.         print(name)
  223.  
  224. # Lab 5:
  225. # Task 1
  226. # TODO: type solution here
  227. def addNumbers(a,b):
  228.     add = a + b
  229.     return add
  230.  
  231. print(addNumbers(3,5))
  232.  
  233. # Task 2
  234. # TODO: type solution here
  235. #write your function here
  236.  
  237. def factorial(a):
  238.    if a == 0:
  239.        return 1
  240.    else:
  241.        return a * factorial(a - 1)
  242.  
  243. print(factorial(5))
  244. print(factorial(7))
  245. print(factorial(9))
  246.  
  247. # Task 3
  248. # TODO: type solution here
  249.  
  250. # place helloWorld() here
  251. def helloWorld():
  252.     print("Hello World")
  253.  
  254. # place helloWorldNTimes here
  255. def helloWorldNTimes(n):
  256.     while n != 0:
  257.         helloWorld()
  258.         n = n - 1
  259.  
  260.  
  261. def main():
  262.     helloWorldNTimes(7)
  263.  
  264.  
  265. main()
  266.  
  267. # Task 4
  268. # TODO: type solution here
  269. #place your function here
  270. def isMultiple(i):
  271.     if not i % 7:
  272.        return i
  273.     else:
  274.         return -1
  275.  
  276.  
  277. def checkMultiples():
  278.     for i in range(1,100):
  279.         cur = isMultiple(i)
  280.         if cur != -1:
  281.             print(cur)
  282.  
  283.  
  284. checkMultiples()
  285.  
  286. print(7 % (7 * 15))
  287.  
  288. # Lab 6
  289. # Task 1, 2, 3 are giving errors so are not included.
  290. # Task 4
  291. # TODO: type solution here
  292. def zFirst(words):
  293.     result =[]
  294.     result2 =[]
  295.     for word in words:
  296.         if word.lower()[0] == 'z':
  297.             result.append(word)
  298.         else:
  299.             result2.append(word)
  300.  
  301.     result.sort()
  302.     result2.sort()
  303.     return result + result2
  304.  
  305.  
  306.  
  307. words=["hello","good","nice","as","at","baseball","absorb","sword","a","tall","so","bored","silver","hi"
  308. ,"pool","we","I","am","seven","Do","you","want","ants","because","that's","how","you","get","zebra","zealot","Zaire"]
  309. print(zFirst(words))
  310.  
  311. # Lab 7:
  312. # Guess I dont have this on either sorry.
  313.  
  314. # Lab 8:
  315. # Task 1
  316. # TODO: type solution here
  317.  
  318. try:
  319.     f=open("thefile.file","r")
  320.     line in f.readline()
  321.  
  322. except IOError:
  323.     print("Error, file not found.")
  324.  
  325. # Task 2
  326. # Not checking *
  327. # TODO: type solution here
  328. count = 0
  329. for i in range(10):
  330.     #  count += 1
  331.     try:
  332.         try:
  333.             print(7/i)
  334.         finally:
  335.            if i == 9:
  336.                 print(i)
  337.  
  338.     except ZeroDivisionError as exception:
  339.             print("Error, ", str(exception))
  340.  
  341. # Task 3
  342. # TODO: type solution here
  343. values =[1,2,3,4,5,"hello",6,7,8,9,"10"]
  344.  
  345. for cur in values:
  346.     if type(cur) == str:
  347.         raise TypeError("This is a string!")
  348.     else:
  349.         print("the value is :", (cur))
  350.  
  351.  
  352. # Lab 9:
  353. # Task 1
  354. episode4 = {"Luke","Leia","Han","Chewie","C3PO","R2-D2","Vader","Greedo","Kenobi"}
  355. episode5 = {"Luke","Leia","Han","Chewie","C3PO","R2-D2","Vader","Tauntaun","Yoda","Lando"}
  356. episode6 = {"Luke","Leia","Han","Chewie","C3PO","R2-D2","Vader","Palpatine","Ackbar","Jabba","Rancor","Boba"}
  357.  
  358. # code for union under here call your set unEps
  359. unEps = episode4.union(episode5, episode6)
  360. print(len(unEps))
  361.  
  362. # Task 2
  363. episode4 = {"Luke","Leia","Han","Chewie","C3PO","R2-D2","Vader","Greedo","Kenobi"}
  364. episode5={"Luke","Leia","Han","Chewie","C3PO","R2-D2","Vader","Tauntaun","Yoda","Lando"}
  365. episode6={"Luke","Leia","Han","Chewie","C3PO","R2-D2","Vader","Palpatine","Ackbar","Jabba","Rancor","Boba","Yoda"}
  366.  
  367. #code to create intersection of 4 and 5 then take episode 6 and difference that with the intersection of 4 and 5
  368. episode45 = episode4.intersection(episode5)
  369.  
  370. final = episode6.difference(episode45)
  371.  
  372. print(len(final))
  373.  
  374. # Task 3
  375. sentence ="I had such a horrible day. It was awful so bad sigh. It could not have been worse but actually though "\
  376.           +"such a terrible horrible awful bad day."
  377.  
  378. makeItHappy ={"horrible":"amazing","bad":"good","awful":"awesome","worse":"better","terrible":"great"}
  379.  
  380. sentence = sentence.split()
  381.  
  382. print(sentence)
  383.  
  384.  
  385. for i in range(len(sentence)):
  386.     if sentence[i] in makeItHappy:
  387.         sentence[i]=makeItHappy[sentence[i]]
  388.  
  389. newString = ""
  390. for word in sentence:
  391.     newString = newString+" "+word
  392. print(newString)
  393.  
  394.  
  395. # Task 4
  396. # name = ["Stirling","Lana","Cyril","Pam","Ray","Cheryl"]
  397. alias = ["Duchess","Truckasaurus","Chet","Cookie Monster","Gilles de Rais","Cherlene"]
  398.  
  399. newdict = {}
  400.  
  401. for i in range(len(name)):
  402.     newdict[name[i]] = alias[i]
  403.  
  404. for bbhbh in sorted(newdict):
  405.     print(bbhbh,":", newdict[bbhbh])
  406.  
  407. # Task 5
  408.  
  409. import math
  410. #check if number is prime not overly efficient
  411. def prime(n):
  412.     if n==1 or n==0:
  413.         return False
  414.     for x in range(2,int(math.sqrt(n)+1)):
  415.         if n%x == 0:
  416.             return False
  417.     return True
  418.  
  419. #place your code here
  420.  
  421. import math
  422. #check if number is prime not overly efficient
  423. def prime(n):
  424.     if n==1 or n==0:
  425.         return False
  426.     for x in range(2,int(math.sqrt(n)+1)):
  427.         if n%x == 0:
  428.             return False
  429.     return True
  430.  
  431. dict ={}
  432. dict['even']={x for x in range(0,100) if x %2 ==0}
  433. dict['odd']={x for x in range(0,100) if x %2 ==1}
  434. dict['three']={x for x in range(0,100) if x %3 ==0}
  435. dict['five']= {x for x in range(0,100) if x %5 ==0}
  436. dict['prime']={x for x in range(0,100) if prime(x)}
  437.  
  438. print(dict)
  439.  
  440. # Lab 10:
  441. # Task 1
  442. # TODO: type solution here
  443. class Banana:
  444.     bananaID =0
  445.     def __init__(self):
  446.         Banana.bananaID+=1
  447.         self._ID = Banana.bananaID
  448.     def __str__(self):
  449.         return "This banana has an id of "+ str(self._ID)
  450.  
  451.  
  452. b1 = Banana()
  453. b2 = Banana()
  454.  
  455.  
  456. print(b1)
  457. print(b2)
  458.  
  459. # Task 2
  460. # TODO: type solution here
  461. class Dinosaur:
  462.  
  463.     def __init__(self):
  464.         self._type = ""
  465.  
  466.     def setType(self, type):
  467.         self._type = type
  468.  
  469.     def getType(self):
  470.         return self._type
  471.  
  472.  
  473. d1= Dinosaur()
  474. d2= Dinosaur()
  475. d3 = Dinosaur()
  476.  
  477. d1.setType("T-Rex")
  478. d2.setType("Velociraptor")
  479. d3.setType("Stegosaurus")
  480.  
  481. print(d1.getType(),d2.getType(),d3.getType())
  482.  
  483.  
  484. # Task 3
  485. # TODO: type solution here
  486. class Coffee:
  487.  
  488.     def __init__(self):
  489.         self._coffee = ""
  490.  
  491.     def __add__(self, other):
  492.         if isinstance(other,Cream):
  493.             return "Yum"
  494.  
  495.  
  496. class Cream:
  497.  
  498.     def __init__(self):
  499.         self._cream = ""
  500.  
  501.  
  502. coffee = Coffee()
  503. cream= Cream()
  504.  
  505. print(coffee+cream)
  506.  
  507. # Lab 11:
  508. # Task 1
  509. # TODO: type solution here
  510. class Fruit:
  511.  
  512.     def __init__(self):
  513.         self.shape = ""
  514.         self.colour = ""
  515.  
  516.     def canBePhone(self):
  517.         return "fruits can't be phones..."
  518.  
  519. class Banana(Fruit):
  520.     def __init__(self):
  521.         super().__init__()
  522.  
  523.     def canBePhone(self):
  524.         return "Ring ring ring ring ring ring ring banana phone\nBeep-boo-ba-boo-doo-ba-doop"
  525.  
  526. banana = Banana()
  527. strawberry = Fruit()
  528.  
  529. print(banana.canBePhone())
  530. print(strawberry.canBePhone())
  531.  
  532.  
  533. # Task 2
  534. # TODO: type solution here
  535. class Bicycle:
  536.     def __init__(self):
  537.         self._gear = 0
  538.         self._cadence = 0
  539.         self._speed = 0
  540.  
  541.     def setGear(self, gear):
  542.         self._gear = gear
  543.  
  544.     def setCadence(self, cadence):
  545.         self._cadence = cadence
  546.  
  547.     def setSpeed(self, speed):
  548.         self._speed = speed
  549.  
  550.     def getGear(self):
  551.         return self._gear
  552.  
  553.     def getCadence(self):
  554.         return self._cadence
  555.  
  556.     def getSpeed(self):
  557.         return self._speed
  558.  
  559.     def applyBrake(self, brake):
  560.         self._speed = self._speed - brake
  561.         return self._speed
  562.  
  563.     def speedUp(self, acceleration):
  564.         self._speed = self._speed + acceleration
  565.         return self._speed
  566.  
  567. class MountainBike(Bicycle):
  568.     def __init__(self):
  569.         super().__init__()
  570.         self._height = 0
  571.  
  572.     def setHeight(self):
  573.         self._height = height
  574.  
  575.     def getHeight(self):
  576.         return self._height
  577.  
  578.  
  579.  
  580. b1 = Bicycle()
  581. b1.setSpeed(100)
  582. b1.applyBrake(8)
  583.  
  584. mb1 = MountainBike()
  585. mb1.setSpeed(100)
  586. mb1.speedUp(20)
  587.  
  588.  
  589. print(b1.getSpeed())
  590. print(mb1.getSpeed())
  591.  
  592.  
  593. # Task 3
  594. # TODO: type solution here
  595. class Pet:
  596.     def __init__(self):
  597.         self.name = ""
  598.         self.species = ""
  599.  
  600. class Dog(Pet):
  601.     def __init__(self):
  602.         super().__init__()
  603.         self.doesDogChaseCats = False
  604.  
  605.     def setChaseCats(self,chase):
  606.         self.doesDogChaseCats=chase
  607.  
  608.     def chaseCats(self):
  609.         return self.doesDogChaseCats
  610.  
  611. class Cat(Pet):
  612.     def __init__(self):
  613.         super().__init__()
  614.         self.doesCatHateDog = False
  615.  
  616.     def setHatesDogs(self, hate):
  617.         self.doesCatHateDog = hate
  618.  
  619.     def hatesDogs(self):
  620.         return self.doesCatHateDog
  621.  
  622. dog=Dog()
  623. dog.setChaseCats(False)
  624.  
  625. cat = Cat()
  626. cat.setHatesDogs(True)
  627.  
  628. print(cat.doesCatHateDog)
  629. print(dog.doesDogChaseCats)
  630.  
  631. # Task 4
  632. # Don't have task 4
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement