Sunday, 3 September 2017

Python Q & A

Produce A List With Unique Elements From A List With Duplicate Elements?

 Iterating the list is not a desirable solution. The right answer should look like this.

 Use A Dictionary To Keep Track Of The Frequency(Count) Of Each Word? Consider The Below Example.

Expected output sample.
Shell
1
{'Number':Frequency, '2':2, '3':2 
============================== 
def dic(words):
  wordList = {}
  for index in words:
    try:
      wordList[index] += 1
    except KeyError:
      wordList[index] = 1
  return wordList
wordList='1,3,2,4,5,3,2,1,4,3,2'.split(',')
print wordList
 
print dic(wordList)
 
Output#
['1', '3', '2', '4', '5', '3', '2', '1', '4', '3', '2']
{'1': 2, '3': 3, '2': 3, '5': 1, '4': 2}
 

Overloaded functions in python?

You generally don't need to overload functions in Python. Python is dynamically typed, and supports optional arguments to functions.
def myfunction(first, second, third = None):
    if third is None:
        #just use first and second
    else:
        #use all three

myfunction(1, 2) # third will be None, so enter the 'if' clause
myfunction(3, 4, 5) # third isn't None, it's 5, so enter the 'else' clause

Print Keys and values from Dict

print dict.keys()   # Prints all the keys
print dict.values()   # Prints all the values 

Conver String to tuple

tuple(s) − Converts s to a tuple.

Cover String to List

list(s) − Converts s to a list.

** Exponent − Performs exponential (power) calculation on operators. a**b = 10 to the power 20 if a = 10 and b = 20.
// Floor Division − The division of operands where the result is the quotient in which the digits after the decimal point are removed.
x = 15
y = 4
# Output: x / y = 3.75
print('x / y =',x/y)

# Output: x // y = 3
print('x // y =',x//y)
# Output: x ** y = 50625
print('x ** y =',x**y)
Random numbers:
from random import randrange, uniform

# randrange gives you an integral value
irand = randrange(0, 10)

# uniform gives you a floating-point value
frand = uniform(0, 10)
>>> import random
>>> values = list(range(10))
>>> random.choice(values)
5
choice also works for one item from a not-contiguous sample:

>>> import random
>>> nums = [x for x in range(10)]
>>> random.shuffle(nums)
>>> nums
[6, 3, 5, 4, 0, 1, 2, 9, 8, 7]
 

No comments:

Post a Comment