Python Questions Assignment

Assignment Help on Python Questions

Question 1:

  1. a) Write and test a function that counts and returns the number of bits (binary digits) set to 1 in a positive integer:

def countlaits(n).

'Returns the count of bits set to 1 in a positive integer'

For example, countBits(12) should return 2, because 12 = 0...011002. Hints:

  1. Check the digits from right to left.
  2. n % 2 returns the rightmost (least significant) digit in the binary representation of n. (a % b is read "a modulo b" and means the remainder when a is divided by b.)
  3. n //= 2 divides n by 2 and truncates the result to an integer, in effect shifting the binary digits to the right by one and getting rid of the least significant digit.

(8 marks).

Question 2:

  1. a) Let = ) and ji =        y2, y.) be two n-dimensional vectors. Their dot

product, denoted .71 • 3,-is defined as z • ji        +x,y2 +x,y, +... + xj,.. Write a Python

function (call it dotProduct) that will return the dot product of two given vectors (assume the lists of the same length).

(8 marks).

Question 3:

  1. Consider a function:

f(n) (l, if n = I

f (n —1)+1, if n>1

Encode the definition into a recursive Python function (for readability name your function myfunc). (6 marks).

  1. Using the function given in part a) calculate the result of(5)? (2 marks).

Question 4:

  1. a) Credit card numbers have 16 digits. The checksum is calculated as follows. Each digit in an odd position (first, third, etc.) is multiplied by 2. If the result is a two-digit number, its two digits are added together, otherwise it is left alone. The result is added to the sum. Each digit in an even position (second, fourth, etc.) is added to the sum as is. The resulting sum must be 0 modulo 10. For example, 4111111111111111 is a valid credit card number: its checksum is 30. 4111111111111178 is another valid number: its checksum is 40. Write and test a Python function that checks whether a given string of 16 digits represents a valid credit card number. Come up with a few other valid numbers and use a few invalid numbers for testing.

(8 marks).

Expert's Answer

Need Urgent Academic Assistance?

Get Professional Help at Low Prices!

*
*
*


*

TOP
Order Notification

[variable_1] from [variable_2] has just ordered [variable_3] Assignment [amount] minutes ago.