Entry 25752
lab5.py
Submitted by anonymous
on Oct. 17, 2011 at 5:43 a.m.
Language: Python. Code size: 2.4 KB.
# lab5.py # covering Week 2: Functions, Conditionals, Loops #############Week 2: Functions, Conditionals, Loops#################### # 1.) #For a-c, what does each function print? For d, what does the whatIsE do? #a) x = 8 y = 5 z = 1 x += ((y % 2) + (z ** 2)) y -= x print x, y, z #Answer: 10 -5 1 #b) a = 2 b = 9 if (a > b): a += (a * 2) else: a += (b * 2) b += 5 if (b < a): b += (b / 3) else: b -= (a / 2) print a, b #Answer: 20, 18 #c) i = 0 j = 5 for k in xrange(j): i += (j + k) j -= 1 print i #Answer: 25 #d) def whatIsE(num1, num2): c = max(num1, num2) d = min(num1, num2) e = 0 while (c > d): d += 1 e += 1 return e #Answer: WhatIsE finds the difference between num1 and num2. #2.) countOddfactors: Write a function countOddFactors which returns the number #of odd factors a given positive integer has. #Possible solution: def countOddFactors(num): count = 0 for factor in xrange(1, num + 1): if (num % factor == 0 and factor % 2 != 0): count += 1 return count #3.) isAutomorphicNumber: An automorphic number is a number such that when #squared, ends in the same digits as the number itself. For example, 5^2 = 25 #and 76^2 = 5776, so 5 and 76 are automorphic numbers. Write the function #isAutomorphicNumber that returns True if a given number is automorphic and #False otherwise. (No helper functions.) #Possible Solution: def isAutomorphicNumber(number): digits = 0 digitFinder = number while (digitFinder > 0): digitFinder /= 10 digits += 1 return (((number ** 2) % (10 ** digits)) == number) # 4.) isNarcissisticNumber: A narcissistic number is a number that is the sum #of its own digits each raised to the power of the number of digits. For #example, 153 is a narcissistic number since 1^3 + 5^3 + 3^3 = 153. Write a #function isNarcissisticNumber that returns True if the given number is #narcissistic and False otherwise. (No helper functions.) #Possible Solution: def isNarcissisticNumber(number): digits = 0 originalNumber = number digitFinder = number sum = 0 while (digitFinder > 0): digitFinder /= 10 digits += 1 while (number > 0): sum += ((number % 10) ** digits) number /= 10 return (sum == originalNumber)
This snippet took 0.01 seconds to highlight.
Back to the Entry List or Home.