Saturday, August 6, 2011

Python Interview Questions And Answers

Python logoImage via WikipediaHow can my code discover the name of an object?

Generally speaking, it can't, because objects don't really have names. Essentially, assignment always binds a name to a value; The same is true of def and class statements, but in that case the value is a callable. Consider the following code:



class A:

pass



B = A



a = B()

b = a

print b

<__main__.A instance at 016D07CC>

print a

<__main__.A instance at 016D07CC>



Arguably the class has a name: even though it is bound to two names and invoked through the name B the created instance is still reported as an instance of class A. However, it is impossible to say whether the instance's name is a or b, since both names are bound to the same value.



Generally speaking it should not be necessary for your code to "know the names" of particular values. Unless you are deliberately writing introspective programs, this is usually an indication that a change of approach might be beneficial.



In comp.lang.python, Fredrik Lundh once gave an excellent analogy in answer to this question:



The same way as you get the name of that cat you found on your porch: the cat (object) itself cannot tell you its name, and it doesn't really care -- so the only way to find out what it's called is to ask all your neighbours (namespaces) if it's their cat (object)...



....and don't be surprised if you'll find that it's known by many names, or no name at all!

Is there an equivalent of C's "?:" ternary operator?

No.

How do I convert a number to a string?

To convert, e.g., the number 144 to the string '144', use the built-in function str(). If you want a hexadecimal or octal representation, use the built-in functions hex() or oct(). For fancy formatting, use the % operator on strings, e.g. "%04d" % 144 yields '0144' and "%.3f" % (1/3.0) yields '0.333'. See the library reference manual for details.

How do I modify a string in place?

You can't, because strings are immutable. If you need an object with this ability, try converting the string to a list or use the array module:



>>> s = "Hello, world"

>>> a = list(s)

>>>print a

['H', 'e', 'l', 'l', 'o', ',', ' ', 'w', 'o', 'r', 'l', 'd']

>>> a[7:] = list("there!")

>>>''.join(a)

'Hello, there!'





>>> import array

>>> a = array.array('c', s)

>>> print a

array('c', 'Hello, world')

>>> a[0] = 'y' ; print a

array('c', 'yello world')

>>> a.tostring()

'yello, world'

How do I use strings to call functions/methods?

There are various techniques.



* The best is to use a dictionary that maps strings to functions. The primary advantage of this technique is that the strings do not need to match the names of the functions. This is also the primary technique used to emulate a case construct:



def a():

pass



def b():

pass



dispatch = {'go': a, 'stop': b} # Note lack of parens for funcs



dispatch[get_input()]() # Note trailing parens to call function

*

Use the built-in function getattr():



import foo

getattr(foo, 'bar')()



Note that getattr() works on any object, including classes, class instances, modules, and so on.



This is used in several places in the standard library, like this:



class Foo:

def do_foo(self):

...

def do_bar(self):

...



f = getattr(foo_instance, 'do_' + opname)

f()



*

Use locals() or eval() to resolve the function name:



def myFunc():

print "hello"



fname = "myFunc"



f = locals()[fname]

f()



f = eval(fname)

f()



Note: Using eval() is slow and dangerous. If you don't have absolute control over the contents of the string, someone could pass a string that resulted in an arbitrary function being executed.

Is there an equivalent to Perl's chomp() for removing trailing newlines from strings?

Starting with Python 2.2, you can use S.rstrip("\r\n") to remove all occurences of any line terminator from the end of the string S without removing other trailing whitespace. If the string S represents more than one line, with several empty lines at the end, the line terminators for all the blank lines will be removed:



>>> lines = ("line 1 \r\n"

... "\r\n"

... "\r\n")

>>> lines.rstrip("\n\r")

"line 1 "



Since this is typically only desired when reading text one line at a time, using S.rstrip() this way works well.



For older versions of Python, There are two partial substitutes:



* If you want to remove all trailing whitespace, use the rstrip() method of string objects. This removes all trailing whitespace, not just a single newline.

* Otherwise, if there is only one line in the string S, use S.splitlines()[0].

Is there a scanf() or sscanf() equivalent?

Not as such.



For simple input parsing, the easiest approach is usually to split the line into whitespace-delimited words using the split() method of string objects and then convert decimal strings to numeric values using int() or float(). split() supports an optional "sep" parameter which is useful if the line uses something other than whitespace as a separator.



For more complicated input parsing, regular expressions more powerful than C's sscanf() and better suited for the task.

Is there a scanf() or sscanf() equivalent?



Not as such.



For simple input parsing, the easiest approach is usually to split the line into whitespace-delimited words using the split() method of string objects and then convert decimal strings to numeric values using int() or float(). split() supports an optional "sep" parameter which is useful if the line uses something other than whitespace as a separator.



For more complicated input parsing, regular expressions more powerful than C's sscanf() and better suited for the task. 1.3.9 What does 'UnicodeError: ASCII [decoding,encoding] error: ordinal not in range(128)' mean?



This error indicates that your Python installation can handle only 7-bit ASCII strings. There are a couple ways to fix or work around the problem.



If your programs must handle data in arbitrary character set encodings, the environment the application runs in will generally identify the encoding of the data it is handing you. You need to convert the input to Unicode data using that encoding. For example, a program that handles email or web input will typically find character set encoding information in Content-Type headers. This can then be used to properly convert input data to Unicode. Assuming the string referred to by value is encoded as UTF-8:



value = unicode(value, "utf-8")



will return a Unicode object. If the data is not correctly encoded as UTF-8, the above call will raise a UnicodeError exception.



If you only want strings converted to Unicode which have non-ASCII data, you can try converting them first assuming an ASCII encoding, and then generate Unicode objects if that fails:



try:

x = unicode(value, "ascii")

except UnicodeError:

value = unicode(value, "utf-8")

else:

# value was valid ASCII data

pass



It's possible to set a default encoding in a file called sitecustomize.py that's part of the Python library. However, this isn't recommended because changing the Python-wide default encoding may cause third-party extension modules to fail.



Note that on Windows, there is an encoding known as "mbcs", which uses an encoding specific to your current locale. In many cases, and particularly when working with COM, this may be an appropriate default encoding to use.

How do I convert between tuples and lists?

The function tuple(seq) converts any sequence (actually, any iterable) into a tuple with the same items in the same order.



For example, tuple([1, 2, 3]) yields (1, 2, 3) and tuple('abc') yields ('a', 'b', 'c'). If the argument is a tuple, it does not make a copy but returns the same object, so it is cheap to call tuple() when you aren't sure that an object is already a tuple.



The function list(seq) converts any sequence or iterable into a list with the same items in the same order. For example, list((1, 2, 3)) yields [1, 2, 3] and list('abc') yields ['a', 'b', 'c']. If the argument is a list, it makes a copy just like seq[:] would.

What's a negative index?

Python sequences are indexed with positive numbers and negative numbers. For positive numbers 0 is the first index 1 is the second index and so forth. For negative indices -1 is the last index and -2 is the penultimate (next to last) index and so forth. Think of seq[-n] as the same as seq[len(seq)-n].



Using negative indices can be very convenient. For example S[:-1] is all of the string except for its last character, which is useful for removing the trailing newline from a string.

How do I iterate over a sequence in reverse order?

If it is a list, the fastest solution is



list.reverse()

try:

for x in list:

"do something with x"

finally:

list.reverse()



This has the disadvantage that while you are in the loop, the list is temporarily reversed. If you don't like this, you can make a copy. This appears expensive but is actually faster than other solutions:



rev = list[:]

rev.reverse()

for x in rev:





If it's not a list, a more general but slower solution is:



for i in range(len(sequence)-1, -1, -1):

x = sequence[i]





A more elegant solution, is to define a class which acts as a sequence and yields the elements in reverse order (solution due to Steve Majewski):



class Rev:

def __init__(self, seq):

self.forw = seq

def __len__(self):

return len(self.forw)

def __getitem__(self, i):

return self.forw[-(i + 1)]



You can now simply write:



for x in Rev(list):





Unfortunately, this solution is slowest of all, due to the method call overhead.



With Python 2.3, you can use an extended slice syntax:



for x in sequence[::-1]:



Enhanced by Zemanta

WIPRO Aptitude Placement Paper 2

CPU Intel P8085AH.Image via WikipediaPART-B





1) Virtual memory size depends on

[a] address lines [b] data bus

[c] disc space [d] a & c [e] none



Ans : a

-----------------------------------------------



2) Critical section is

[a]

[b] statements which are accessing shared resourses

Ans : b

-------------------------------------------------



3) load a

mul a

store t1

load b

mul b

store t2

mul t2

add t1



then the content in accumulator is



Ans : a**2+b**4

---------------------------------------------------

4) question (3) in old paper

5) q(4) in old paper

6) question (7) in old paper

7) q(9) in old paper

------------------------------





Q21 - Q23. Four questions given on the below data

X,Yand Z are senior engineers. A,B,C,D are junior engineers. Company wants to select 4 enginers. Two will be senior and two will be juniors. The company wants these engineers to work in the most productive way so they respect each person's likes/dislikes.

Y is not friends with A

Z is not friends with C

B is not friends with A

If B is selected then who will be the remaining 4 members ?

If C is selected, Z and ___ cannot be selected?

D is always selected if ___ is selected?



Q24. A speaks truth 70% of the times, B speaks truth 80% of the times.

What is the probability that both are contradicting each other is ?



Q25. ?((2x-3)/((x2 +x+1)2 )dx is ?



Q26. Ram starts from A walking 2 km North and turns right and walks 4 km and turns right again and walks 4 km and turns right again and walks 4 km and meets Radha at Bwalking in the opposite direction to Ram .

a) Which direction does Ram walk after the first turn?

b) Distance between A and B



Q27. If the equation x2 - 3x + a = 0 has the roots (0,1) then value of a is ?



Q28. A and B's temperature are 10?c and 20?c having same surface , then their ratio of rate of emmisions is ?



Q29. An atomic particle exists and has a particlular decay rate . It is in a train . When the train moves, a person observes for whether the decay rate

(a) increases

(b) decreases

(c) depend on the directions of movement of train



Q30. Which of the following exchanges positive ions

(a).cl-

(b) nh2-

(c) ch2

Ans. (b)



Q31. After execution of CMP, a instruction in Intel 8085 microprocessor

(a) ZF is set and CY is reset.

(b) ZF is set CY is unchanged

(c) ZF is reset, CY is set

(d) ZF is reset , CY is unchanged .

Ans. ZF is set and CY is reset



Q32. The best tool for editing a graphic image is ?



Q33. Network scheme defines

a.)one to one

b.) many to many

c.) one to ,many ?



Q34. A person wants to measures the length of a rod.First he measures with standing ideally then he maeasures by

moving parrel to the rod

(a)the length will decrease in second case

(b)length will be same

(c) length will increse in the second case.



Q35. One U-230 nucleus is placed in a train moving by velocity emiting alpha rays .When the train is at rest the

distance between nucleus and alpha particle is x . One passenger is observing the particle . When the train is moving

what is the distance between particle and nucleus ?

(a) x

(b) x + vt

(c) x - vt



Q36. What is the resulting solution when benzene and toluene are mixed ?



Q37. If the word FADENCOMT equals 345687921 then

What is FEAT

Find representation of 2998



Q38. Given 10 alphabets out of which 5 are to be chosen. How many words can be made with atleast one repetition.



Q39. Arrange by acidic values : phenol, nitrotolouene and o-cresol?



Q40. Find sum of 3 + 5/(1+22) + 7/(1 + 22 + 32) + ......

Ans. 3n/(1 + n)

The following are few sample questions that maybe asked in the software paper.We haven't been able to give the values in certain problems ; only the type of questions have been mentioned.



Q What sorting algos have their best and worst case times equal ?

Ans. O(nlogn) for mergesort and heap sort

Q. What page replacement algo . has minimumn number of page faults ?

Ans. Optimality algorithm



Q. What is the use of virtual base class in c++

Ans. Multiple lines between derived classes.



Q. Find the eccentricity of a given node in a directed graph



Q. Convert the infix to postfix for A-(B+C)*(D/E)

Ans. ABC+DE/*-



Q. What is swapping



Q. Assignment operator targets to

Ans. l-value



Q. A byte addressable computer has memory capacity of 2 power m Kbytes and can perform 2 power n operations

an instruction involving three operands and one operator needs maximum of ---bits

Ans. 3m + n



Q. In round robin scheduling, if time quatum is too large then it degenerates to

Ans. FCFS



Q. What is network schema?



Q. Packet Burst is ______



Q. Picard's method uses _______?

Ans. Successive Differentiation.



26. If the letters of the word "rachit" are arranged in all possible ways and these words are written

out as in a dictionary, what is the rank of the word "rachit".

(a) 485

(b) 480

(c) 478

(d) 481

Ans. (d)



27. Ravi's salary was reduced by 25%.Percentage increase to be effected to bring the salary

to the original level is

(a) 20%

(b) 25%

(c) 33 1/3%

(d) 30%

Ans. (c)



28. A and B can finish a piece of work in 20 days .B and C in 30 days and C and A in 40 days.

In how many days will A alone finish the job

(a) 48

(b) 34 2/7

(c) 44

(d) 45

Ans. (a)



29. How long will a train 100m long travelling at 72kmph take to overtake another train

200m long travelling at 54kmph

(a) 70sec

(b) 1min

(c) 1 min 15 sec

(d) 55 sec

Ans. (b)



30. What is the product of the irrational roots of the equation (2x-1)(2x-3)(2x-5)(2x-7)=9?

(a) 3/2

(b) 4

(c) 3

(d) 3/4

Ans. (a)



39.

? All toffees are chocolates

? Some toffees are not good for health

(a) Some chocolates are not good for health

(b) Some toffees are good for health

(c) No toffees are good for health

(d) Both (a) and (b)

Ans. (a)

The questions 40-46 are based on the following pattern.The problems below contain a question and two statements giving certain data. You have to decide whether the data given in the statements are sufficient for answering the questions.The correct answer is

(A) If statement (I) alone is sufficient but statement (II) alone is not sufficient.

(B) If statement(II) alone is sufficient but statement(I) alone is not sufficient.

(C) If both statements together are sufficient but neither of statements alone is sufficient.

(D) If both together are not sufficient.

(E) If statements (I) and (II) are not sufficient



40. What is the volume of a cubical box in cubic centimetres?

(I) One face of the box has an area of 49 sq.cms.

(II) The longest diagonal of the box is 20 cms.

Ans. D



41. Is z positive?

(I) y+z is positive

(II) y-z is positive

Ans. E



42. Is x>y ? x, y are real numbers?

(I) 8x = 6y

(II) x = y + 4

Ans. B



43. If a ground is rectangular, what is its width?

(I) The ratio of its length to its breadth is 7:2

(II) Perimeter of the playground is 396 mts.

Ans. C



44. If the present age of my father is 39 yrs and my present age is x yrs, what is x?

(I) Next year my mother will be four times as old as i would be.

(II) My brother is 2 years older than I and my father is 4 years older than my mother.

Ans. C



45. How many brothers and sisters are there in the family of seven children?

(I) Each boy in the family has as many sisters as brothers

(II) Each of the girl in the family has twice as many brothers as sisters

Ans. D



46. x is not equal to 0, is x + y = 0?

(I) x is the reciprocal of y

(II) x is not equal to 1

Ans. A


Enhanced by Zemanta